chiark / gitweb /
049eadfd9204165235758a37ded22974bb1e5524
[disorder] / tests / dtest.py
1 #-*-python-*-
2 #
3 # This file is part of DisOrder.
4 # Copyright (C) 2007-2009 Richard Kettlewell
5 #
6 # This program is free software: you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation, either version 3 of the License, or
9 # (at your option) any later version.
10 #
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 # GNU General Public License for more details.
15
16 # You should have received a copy of the GNU General Public License
17 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
18 #
19
20 """Utility module used by tests"""
21
22 import os,os.path,subprocess,sys,re,time,unicodedata,random,socket,traceback
23
24 def fatal(s):
25     """Write an error message and exit"""
26     sys.stderr.write("ERROR: %s\n" % s)
27     sys.exit(1)
28
29 # Identify the top build directory
30 cwd = os.getcwd()
31 if os.path.exists("config.h"):
32     top_builddir = cwd
33 elif os.path.exists("../config.h"):
34     top_builddir = os.path.dirname(cwd)
35 else:
36     fatal("cannot identify build directory")
37
38 # Make sure the Python build directory is on the module search path
39 sys.path.insert(0, os.path.join(top_builddir, "python"))
40 import disorder
41
42 # Make sure the build directories are on the executable search path
43 ospath = os.environ["PATH"].split(os.pathsep)
44 ospath.insert(0, os.path.join(top_builddir, "server"))
45 ospath.insert(0, os.path.join(top_builddir, "clients"))
46 ospath.insert(0, os.path.join(top_builddir, "tests"))
47 os.environ["PATH"] = os.pathsep.join(ospath)
48
49 # Parse the makefile in the current directory to identify the source directory
50 top_srcdir = None
51 for l in file("Makefile"):
52     r = re.match("top_srcdir *= *(.*)",  l)
53     if r:
54         top_srcdir = r.group(1)
55         break
56 if not top_srcdir:
57     fatal("cannot identify source directory")
58
59 # The tests source directory must be on the module search path already since
60 # we found dtest.py
61
62 # -----------------------------------------------------------------------------
63
64 def copyfile(a,b):
65     """copyfile(A, B)
66 Copy A to B."""
67     open(b,"w").write(open(a).read())
68
69 def to_unicode(s):
70     """Convert UTF-8 to unicode.  A no-op if already unicode."""
71     if type(s) == unicode:
72         return s
73     else:
74         return unicode(s, "UTF-8")
75
76 def nfc(s):
77     """Convert UTF-8 string or unicode to NFC unicode."""
78     return  unicodedata.normalize("NFC", to_unicode(s))
79
80 def maketrack(s):
81     """maketrack(S)
82
83 Make track with relative path S exist"""
84     trackpath = "%s/%s" % (tracks, s)
85     trackdir = os.path.dirname(trackpath)
86     if not os.path.exists(trackdir):
87         os.makedirs(trackdir)
88     copyfile("%s/sounds/long.ogg" % top_srcdir, trackpath)
89     # We record the tracks we created so they can be tested against
90     # server responses.  We put them into NFC since that's what the server
91     # uses internally.
92     bits = nfc(s).split('/')
93     dp = tracks
94     for d in bits [0:-1]:
95         dd = "%s/%s" % (dp,  d)
96         if dp not in dirs_by_dir:
97             dirs_by_dir[dp] = []
98         if dd not in dirs_by_dir[dp]:
99             dirs_by_dir[dp].append(dd)
100         dp = "%s/%s" % (dp, d)
101     if dp not in files_by_dir:
102         files_by_dir[dp] = []
103     files_by_dir[dp].append("%s/%s" % (dp, bits[-1]))
104
105 def stdtracks():
106     # We create some tracks with non-ASCII characters in the name and
107     # we (currently) force UTF-8.
108     #
109     # On a traditional UNIX filesystem, that treats filenames as byte strings
110     # with special significant for '/', this should just work, though the
111     # names will look wrong to ls(1) in a non UTF-8 locale.
112     #
113     # On Apple HFS+ filenames normalized to a decomposed form that isn't quite
114     # NFD, so our attempts to have both normalized and denormalized filenames
115     # is frustrated.  Provided we test on traditional filesytsems too this
116     # shouldn't be a problem.
117     # (See http://developer.apple.com/qa/qa2001/qa1173.html)
118
119     global dirs_by_dir, files_by_dir
120     dirs_by_dir={}
121     files_by_dir={}
122     
123     # C3 8C = 00CC LATIN CAPITAL LETTER I WITH GRAVE
124     # (in NFC)
125     maketrack("Joe Bloggs/First Album/01:F\xC3\x8Crst track.ogg")
126
127     maketrack("Joe Bloggs/First Album/02:Second track.ogg")
128
129     # CC 81 = 0301 COMBINING ACUTE ACCENT
130     # (giving an NFD i-acute)
131     maketrack("Joe Bloggs/First Album/03:ThI\xCC\x81rd track.ogg")
132     # ...hopefuly giving C3 8D = 00CD LATIN CAPITAL LETTER I WITH ACUTE
133     maketrack("Joe Bloggs/First Album/04:Fourth track.ogg")
134     maketrack("Joe Bloggs/First Album/05:Fifth track.ogg")
135     maketrack("Joe Bloggs/Second Album/01:First track.ogg")
136     maketrack("Joe Bloggs/Second Album/02:Second track.ogg")
137     maketrack("Joe Bloggs/Second Album/03:Third track.ogg")
138     maketrack("Joe Bloggs/Second Album/04:Fourth track.ogg")
139     maketrack("Joe Bloggs/Second Album/05:Fifth track.ogg")
140     maketrack("Joe Bloggs/Third Album/01:First_track.ogg")
141     maketrack("Joe Bloggs/Third Album/02:Second_track.ogg")
142     maketrack("Joe Bloggs/Third Album/03:Third_track.ogg")
143     maketrack("Joe Bloggs/Third Album/04:Fourth_track.ogg")
144     maketrack("Joe Bloggs/Third Album/05:Fifth_track.ogg")
145     maketrack("Fred Smith/Boring/01:Dull.ogg")
146     maketrack("Fred Smith/Boring/02:Tedious.ogg")
147     maketrack("Fred Smith/Boring/03:Drum Solo.ogg")
148     maketrack("Fred Smith/Boring/04:Yawn.ogg")
149     maketrack("misc/blahblahblah.ogg")
150     maketrack("Various/Greatest Hits/01:Jim Whatever - Spong.ogg")
151     maketrack("Various/Greatest Hits/02:Joe Bloggs - Yadda.ogg")
152
153 def bindable(p):
154     """bindable(P)
155
156     Return True iff UDP port P is bindable, else False"""
157     s = socket.socket(socket.AF_INET,
158                       socket.SOCK_DGRAM,
159                       socket.IPPROTO_UDP)
160     try:
161         s.bind(("127.0.0.1", p))
162         s.close()
163         return True
164     except:
165         return False
166
167 def default_config(encoding="UTF-8"):
168     """Write the default config"""
169     open("%s/config" % testroot, "w").write(
170     """home %s/home
171 collection fs %s %s/tracks
172 scratch %s/scratch.ogg
173 queue_pad 5
174 stopword 01 02 03 04 05 06 07 08 09 10
175 stopword 1 2 3 4 5 6 7 8 9
176 stopword 11 12 13 14 15 16 17 18 19 20
177 stopword 21 22 23 24 25 26 27 28 29 30
178 stopword the a an and to too in on of we i am as im for is
179 username fred
180 password fredpass
181 plugins
182 plugins %s/plugins
183 plugins %s/plugins/.libs
184 player *.mp3 execraw disorder-decode
185 player *.ogg execraw disorder-decode
186 player *.wav execraw disorder-decode
187 player *.flac execraw disorder-decode
188 tracklength *.mp3 disorder-tracklength
189 tracklength *.ogg disorder-tracklength
190 tracklength *.wav disorder-tracklength
191 tracklength *.flac disorder-tracklength
192 api rtp
193 broadcast 127.0.0.1 %d
194 broadcast_from 127.0.0.1 %d
195 mail_sender no.such.user.sorry@greenend.org.uk
196 """ % (testroot, encoding, testroot, testroot, top_builddir, top_builddir,
197        port, port + 1))
198
199 def common_setup():
200     remove_dir(testroot)
201     os.mkdir(testroot)
202     # Choose a port
203     global port
204     port = random.randint(49152, 65530)
205     while not bindable(port + 1):
206         print "port %d is not bindable, trying another" % (port + 1)
207         port = random.randint(49152, 65530)
208     # Log anything sent to that port
209     packetlog = "%s/packetlog" % testroot
210     subprocess.Popen(["disorder-udplog",
211                       "--output", packetlog,
212                       "127.0.0.1", "%d" % port])
213     # disorder-udplog will quit when its parent process terminates
214     copyfile("%s/sounds/scratch.ogg" % top_srcdir,
215              "%s/scratch.ogg" % testroot)
216     default_config()
217
218 def start_daemon():
219     """start_daemon()
220
221 Start the daemon."""
222     global daemon, errs, port
223     assert daemon == None, "no daemon running"
224     if not bindable(port + 1):
225         print "waiting for port %d to become bindable again..." % (port + 1)
226         time.sleep(1)
227         while not bindable(port + 1):
228             time.sleep(1)
229     print " starting daemon"
230     # remove the socket if it exists
231     socket = "%s/home/socket" % testroot
232     if os.path.exists(socket):
233         os.remove(socket)
234     daemon = subprocess.Popen(["disorderd",
235                                "--foreground",
236                                "--config", "%s/config" % testroot],
237                               stderr=errs)
238     # Wait for the socket to be created
239     waited = 0
240     sleep_resolution = 0.125
241     while not os.path.exists(socket):
242         rc = daemon.poll()
243         if rc is not None:
244             print "FATAL: daemon failed to start up"
245             sys.exit(1)
246         waited += sleep_resolution
247         if sleep_resolution < 1:
248             sleep_resolution *= 2
249         if waited == 1:
250             print "  waiting for socket..."
251         elif waited >= 60:
252             print "FATAL: took too long for socket to appear"
253             sys.exit(1)
254         time.sleep(sleep_resolution)
255     if waited > 0:
256         print "  took about %ss for socket to appear" % waited
257     # Wait for root user to be created
258     command(["disorderd",
259              "--config", disorder._configfile,
260              "--wait-for-root"])
261
262 def create_user(username="fred", password="fredpass"):
263     """create_user(USERNAME, PASSWORD)
264
265     Create a user, abusing direct database access to do so.  Gives the
266     user rights 'all', allowing them to do anything."""
267     print " creating user %s" % username
268     command(["disorder",
269              "--config", disorder._configfile, "--no-per-user-config",
270              "--user", "root", "adduser", username, password])
271     command(["disorder",
272              "--config", disorder._configfile, "--no-per-user-config",
273              "--user", "root", "edituser", username, "rights", "all"])
274
275 def rescan(c=None):
276     print " initiating rescan"
277     if c is None:
278         c = disorder.client()
279     c.rescan('wait')
280     print " rescan completed"
281
282 def stop_daemon():
283     """stop_daemon()
284
285 Stop the daemon if it has not stopped already"""
286     global daemon
287     if daemon == None:
288         print " (daemon not running)"
289         return
290     rc = daemon.poll()
291     if rc == None:
292         print " stopping daemon"
293         os.kill(daemon.pid, 15)
294         print "  waiting for daemon"
295         rc = daemon.wait()
296         print "  daemon has stopped (rc=%d)" % rc
297     else:
298         print "  daemon already stopped"
299     daemon = None
300
301 def run(module=None, report=True):
302     """dtest.run(MODULE)
303
304     Run the test in MODULE.  This can be a string (in which case the module
305     will be imported) or a module object."""
306     global tests, failures
307     tests += 1
308     # Locate the test module
309     if module is None:
310         # We're running a test stand-alone
311         import __main__
312         module = __main__
313         name = os.path.splitext(os.path.basename(sys.argv[0]))[0]
314     else:
315         # We've been passed a module or a module name
316         if type(module) == str:
317             module = __import__(module)
318         name = module.__name__
319     print "--- %s ---" % name
320     # Open the error log
321     global errs
322     logfile = "%s.log" % name
323     try:
324         os.remove(logfile)
325     except:
326         pass
327     errs = open(logfile, "a")
328     # Ensure that disorder.py uses the test installation
329     disorder._configfile = "%s/config" % testroot
330     disorder._userconf = False
331     # Make config file etc
332     common_setup()
333     # Create some standard tracks
334     stdtracks()
335     try:
336         module.test()
337     except Exception, e:
338         traceback.print_exc(None, sys.stderr)
339         failures += 1
340     finally:
341         stop_daemon()
342         os.system("ps -ef | grep disorderd")
343     if report:
344         if failures:
345             print " FAILED"
346             sys.exit(1)
347         else:
348             print " OK"
349
350 def remove_dir(d):
351     """remove_dir(D)
352
353 Recursively delete directory D"""
354     if os.path.lexists(d):
355         if os.path.isdir(d):
356             for dd in os.listdir(d):
357                 remove_dir("%s/%s" % (d, dd))
358             os.rmdir(d)
359         else:
360             os.remove(d)
361
362 def lists_have_same_contents(l1, l2):
363     """lists_have_same_contents(L1, L2)
364
365     Return True if L1 and L2 have equal members, in any order; else False."""
366     s1 = []
367     s1.extend(l1)
368     s1.sort()
369     s2 = []
370     s2.extend(l2)
371     s2.sort()
372     return map(nfc, s1) == map(nfc, s2)
373
374 def check_files(chatty=True):
375     c = disorder.client()
376     failures = 0
377     for d in dirs_by_dir:
378         xdirs = dirs_by_dir[d]
379         dirs = c.directories(d)
380         if not lists_have_same_contents(xdirs, dirs):
381             if chatty:
382                 print
383                 print "directory: %s" % d
384                 print "expected:  %s" % xdirs
385                 print "got:       %s" % dirs
386             failures += 1
387     for d in files_by_dir:
388         xfiles = files_by_dir[d]
389         files = c.files(d)
390         if not lists_have_same_contents(xfiles, files):
391             if chatty:
392                 print
393                 print "directory: %s" % d
394                 print "expected:  %s" % xfiles
395                 print "got:       %s" % files
396             failures += 1
397     return failures
398
399 def command(args):
400     """Execute a command given as a list and return its stdout"""
401     p = subprocess.Popen(args, stdout=subprocess.PIPE)
402     lines = p.stdout.readlines()
403     rc = p.wait()
404     assert rc == 0, ("%s returned status %s" % (args, rc))
405     return lines
406
407 # -----------------------------------------------------------------------------
408 # Common setup
409
410 tests = 0
411 failures = 0
412 daemon = None
413 testroot = "%s/tests/testroot" % top_builddir
414 tracks = "%s/tracks" % testroot