chiark / gitweb /
exit not _exit, for benefit of coverage testing
[disorder] / tests / dtest.py
1 #-*-python-*-
2 #
3 # This file is part of DisOrder.
4 # Copyright (C) 2007 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 2 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, but
12 # WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 # 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, write to the Free Software
18 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
19 # USA
20 #
21
22 """Utility module used by tests"""
23
24 import os,os.path,subprocess,sys,re,time,unicodedata,random
25
26 def fatal(s):
27     """Write an error message and exit"""
28     sys.stderr.write("ERROR: %s\n" % s)
29     sys.exit(1)
30
31 # Identify the top build directory
32 cwd = os.getcwd()
33 if os.path.exists("config.h"):
34     top_builddir = cwd
35 elif os.path.exists("alltests"):
36     top_builddir = os.path.dirname(cwd)
37 else:
38     fatal("cannot identify build directory")
39
40 # Make sure the Python build directory is on the module search path
41 sys.path.insert(0, os.path.join(top_builddir, "python"))
42 import disorder
43
44 # Make sure the build directories are on the executable search path
45 ospath = os.environ["PATH"].split(os.pathsep)
46 ospath.insert(0, os.path.join(top_builddir, "server"))
47 ospath.insert(0, os.path.join(top_builddir, "clients"))
48 os.environ["PATH"] = os.pathsep.join(ospath)
49
50 # Parse the makefile in the current directory to identify the source directory
51 top_srcdir = None
52 for l in file("Makefile"):
53     r = re.match("top_srcdir *= *(.*)",  l)
54     if r:
55         top_srcdir = r.group(1)
56         break
57 if not top_srcdir:
58     fatal("cannot identify source directory")
59
60 # The tests source directory must be on the module search path already since
61 # we found dtest.py
62
63 # -----------------------------------------------------------------------------
64
65 def copyfile(a,b):
66     """copyfile(A, B)
67 Copy A to B."""
68     open(b,"w").write(open(a).read())
69
70 def to_unicode(s):
71     """Convert UTF-8 to unicode.  A no-op if already unicode."""
72     if type(s) == unicode:
73         return s
74     else:
75         return unicode(s, "UTF-8")
76
77 def nfc(s):
78     """Convert UTF-8 string or unicode to NFC unicode."""
79     return  unicodedata.normalize("NFC", to_unicode(s))
80
81 def maketrack(s):
82     """maketrack(S)
83
84 Make track with relative path S exist"""
85     trackpath = "%s/%s" % (tracks, s)
86     trackdir = os.path.dirname(trackpath)
87     if not os.path.exists(trackdir):
88         os.makedirs(trackdir)
89     copyfile("%s/sounds/slap.ogg" % top_srcdir, trackpath)
90     # We record the tracks we created so they can be tested against
91     # server responses.  We put them into NFC since that's what the server
92     # uses internally.
93     bits = nfc(s).split('/')
94     dp = tracks
95     for d in bits [0:-1]:
96         dd = "%s/%s" % (dp,  d)
97         if dp not in dirs_by_dir:
98             dirs_by_dir[dp] = []
99         if dd not in dirs_by_dir[dp]:
100             dirs_by_dir[dp].append(dd)
101         dp = "%s/%s" % (dp, d)
102     if dp not in files_by_dir:
103         files_by_dir[dp] = []
104     files_by_dir[dp].append("%s/%s" % (dp, bits[-1]))
105
106 def stdtracks():
107     # We create some tracks with non-ASCII characters in the name and
108     # we (currently) force UTF-8.
109     #
110     # On a traditional UNIX filesystem, that treats filenames as byte strings
111     # with special significant for '/', this should just work, though the
112     # names will look wrong to ls(1) in a non UTF-8 locale.
113     #
114     # On Apple HFS+ filenames normalized to a decomposed form that isn't quite
115     # NFD, so our attempts to have both normalized and denormalized filenames
116     # is frustrated.  Provided we test on traditional filesytsems too this
117     # shouldn't be a problem.
118     # (See http://developer.apple.com/qa/qa2001/qa1173.html)
119
120     global dirs_by_dir, files_by_dir
121     dirs_by_dir={}
122     files_by_dir={}
123     
124     # C3 8C = 00CC LATIN CAPITAL LETTER I WITH GRAVE
125     # (in NFC)
126     maketrack("Joe Bloggs/First Album/01:F\xC3\x8Crst track.ogg")
127
128     maketrack("Joe Bloggs/First Album/02:Second track.ogg")
129
130     # CC 81 = 0301 COMBINING ACUTE ACCENT
131     # (giving an NFD i-acute)
132     maketrack("Joe Bloggs/First Album/03:ThI\xCC\x81rd track.ogg")
133     # ...hopefuly giving C3 8D = 00CD LATIN CAPITAL LETTER I WITH ACUTE
134     maketrack("Joe Bloggs/First Album/04:Fourth track.ogg")
135     maketrack("Joe Bloggs/First Album/05:Fifth track.ogg")
136     maketrack("Joe Bloggs/Second Album/01:First track.ogg")
137     maketrack("Joe Bloggs/Second Album/02:Second track.ogg")
138     maketrack("Joe Bloggs/Second Album/03:Third track.ogg")
139     maketrack("Joe Bloggs/Second Album/04:Fourth track.ogg")
140     maketrack("Joe Bloggs/Second Album/05:Fifth track.ogg")
141     maketrack("Joe Bloggs/Third Album/01:First_track.ogg")
142     maketrack("Joe Bloggs/Third Album/02:Second_track.ogg")
143     maketrack("Joe Bloggs/Third Album/03:Third_track.ogg")
144     maketrack("Joe Bloggs/Third Album/04:Fourth_track.ogg")
145     maketrack("Joe Bloggs/Third Album/05:Fifth_track.ogg")
146     maketrack("Fred Smith/Boring/01:Dull.ogg")
147     maketrack("Fred Smith/Boring/02:Tedious.ogg")
148     maketrack("Fred Smith/Boring/03:Drum Solo.ogg")
149     maketrack("Fred Smith/Boring/04:Yawn.ogg")
150     maketrack("misc/blahblahblah.ogg")
151     maketrack("Various/Greatest Hits/01:Jim Whatever - Spong.ogg")
152     maketrack("Various/Greatest Hits/02:Joe Bloggs - Yadda.ogg")
153  
154 def common_setup():
155     remove_dir(testroot)
156     os.mkdir(testroot)
157     global port
158     port = random.randint(49152, 65535)
159     open("%s/config" % testroot, "w").write(
160     """home %s
161 collection fs UTF-8 %s/tracks
162 scratch %s/scratch.ogg
163 gap 0
164 stopword 01 02 03 04 05 06 07 08 09 10
165 stopword 1 2 3 4 5 6 7 8 9
166 stopword 11 12 13 14 15 16 17 18 19 20
167 stopword 21 22 23 24 25 26 27 28 29 30
168 stopword the a an and to too in on of we i am as im for is
169 username fred
170 password fredpass
171 allow fred fredpass
172 trust fred
173 plugins
174 plugins %s/plugins
175 plugins %s/plugins/.libs
176 player *.mp3 execraw disorder-decode
177 player *.ogg execraw disorder-decode
178 player *.wav execraw disorder-decode
179 player *.flac execraw disorder-decode
180 tracklength *.mp3 disorder-tracklength
181 tracklength *.ogg disorder-tracklength
182 tracklength *.wav disorder-tracklength
183 tracklength *.flac disorder-tracklength
184 speaker_backend network
185 broadcast 127.0.0.1 %d
186 broadcast_from 127.0.0.1 %d
187 """ % (testroot, testroot, testroot, top_builddir, top_builddir,
188        port, port + 1))
189     copyfile("%s/sounds/scratch.ogg" % top_srcdir,
190              "%s/scratch.ogg" % testroot)
191
192 def start_daemon():
193     """start_daemon()
194
195 Start the daemon."""
196     global daemon, errs
197     assert daemon == None, "no daemon running"
198     print " starting daemon"
199     # remove the socket if it exists
200     socket = "%s/socket" % testroot
201     try:
202         os.remove(socket)
203     except:
204         pass
205     daemon = subprocess.Popen(["disorderd",
206                                "--foreground",
207                                "--config", "%s/config" % testroot],
208                               stderr=errs)
209     # Wait for the socket to be created
210     waited = 0
211     while not os.path.exists(socket):
212         rc = daemon.poll()
213         if rc is not None:
214             print "FATAL: daemon failed to start up"
215             sys.exit(1)
216         waited += 1
217         if waited == 1:
218             print "  waiting for socket..."
219         elif waited >= 60:
220             print "FATAL: took too long for socket to appear"
221             sys.exit(1)
222         time.sleep(1)
223     if waited > 0:
224         print "  took about %ds for socket to appear" % waited
225
226 def stop_daemon():
227     """stop_daemon()
228
229 Stop the daemon if it has not stopped already"""
230     global daemon
231     if daemon == None:
232         return
233     rc = daemon.poll()
234     if rc == None:
235         print " stopping daemon"
236         disorder.client().shutdown()
237         print "  waiting for daemon"
238         rc = daemon.wait()
239         print "  daemon has stopped"
240     else:
241         print "  daemon already stopped"
242     daemon = None
243
244 def run(module=None, report=True):
245     """dtest.run(MODULE)
246
247     Run the test in MODULE.  This can be a string (in which case the module
248     will be imported) or a module object."""
249     global tests
250     tests += 1
251     # Locate the test module
252     if module is None:
253         # We're running a test stand-alone
254         import __main__
255         module = __main__
256         name = os.path.splitext(os.path.basename(sys.argv[0]))[0]
257     else:
258         # We've been passed a module or a module name
259         if type(module) == str:
260             module = __import__(module)
261         name = module.__name__
262     # Open the error log
263     global errs
264     errs = open("%s.log" % name, "w")
265     # Ensure that disorder.py uses the test installation
266     disorder._configfile = "%s/config" % testroot
267     disorder._userconf = False
268     # Make config file etc
269     common_setup()
270     # Create some standard tracks
271     stdtracks()
272     try:
273         try:
274             module.test()
275         except AssertionError, e:
276             global failures
277             failures += 1
278             print "assertion failed: %s" % e.message
279     finally:
280         stop_daemon()
281     if report:
282         if failures:
283             print " FAILED"
284             sys.exit(1)
285         else:
286             print " OK"
287
288 def remove_dir(d):
289     """remove_dir(D)
290
291 Recursively delete directory D"""
292     if os.path.lexists(d):
293         if os.path.isdir(d):
294             for dd in os.listdir(d):
295                 remove_dir("%s/%s" % (d, dd))
296             os.rmdir(d)
297         else:
298             os.remove(d)
299
300 def check_files():
301     c = disorder.client()
302     failures = 0
303     for d in dirs_by_dir:
304         xdirs = dirs_by_dir[d]
305         dirs = c.directories(d)
306         xdirs.sort()
307         dirs.sort()
308         if dirs != xdirs:
309             print
310             print "directory: %s" % d
311             print "expected:  %s" % xdirs
312             print "got:       %s" % dirs
313             failures += 1
314     for d in files_by_dir:
315         xfiles = files_by_dir[d]
316         files = c.files(d)
317         xfiles.sort()
318         files.sort()
319         if files != xfiles:
320             print
321             print "directory: %s" % d
322             print "expected:  %s" % xfiles
323             print "got:       %s" % files
324             failures += 1
325     return failures
326
327 def command(args):
328     """Execute a command given as a list and return its stdout"""
329     p = subprocess.Popen(args, stdout=subprocess.PIPE)
330     lines = p.stdout.readlines()
331     rc = p.wait()
332     assert rc == 0, ("%s returned status %s" % (args, rc))
333     return lines
334
335 # -----------------------------------------------------------------------------
336 # Common setup
337
338 tests = 0
339 failures = 0
340 daemon = None
341 testroot = "%s/tests/testroot" % top_builddir
342 tracks = "%s/tracks" % testroot