chiark / gitweb /
fix disorder.py search
[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
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 server build directory is on the executable search path
45 ospath = os.environ["PATH"].split(os.pathsep)
46 ospath.insert(0, os.path.join(top_builddir, "server"))
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 maketrack(s):
70     """maketrack(S)
71
72 Make track with relative path S exist"""
73     trackpath = "%s/%s" % (tracks, s)
74     trackdir = os.path.dirname(trackpath)
75     if not os.path.exists(trackdir):
76         os.makedirs(trackdir)
77     copyfile("%s/sounds/slap.ogg" % top_srcdir, trackpath)
78     # We record the tracks we created so they can be tested against
79     # server responses.  We put them into NFC since that's what the server
80     # uses internally.
81     bits = unicodedata.normalize("NFC",
82                                  unicode(s, "UTF-8")).split('/')
83     dp = tracks
84     for d in bits [0:-1]:
85         dd = "%s/%s" % (dp,  d)
86         if dp not in dirs_by_dir:
87             dirs_by_dir[dp] = []
88         if dd not in dirs_by_dir[dp]:
89             dirs_by_dir[dp].append(dd)
90         dp = "%s/%s" % (dp, d)
91     if dp not in files_by_dir:
92         files_by_dir[dp] = []
93     files_by_dir[dp].append("%s/%s" % (dp, bits[-1]))
94
95 def stdtracks():
96     # We create some tracks with non-ASCII characters in the name and
97     # we (currently) force UTF-8.
98     #
99     # On a traditional UNIX filesystem, that treats filenames as byte strings
100     # with special significant for '/', this should just work, though the
101     # names will look wrong to ls(1) in a non UTF-8 locale.
102     #
103     # On Apple HFS+ filenames normalized to a decomposed form that isn't quite
104     # NFD, so our attempts to have both normalized and denormalized filenames
105     # is frustrated.  Provided we test on traditional filesytsems too this
106     # shouldn't be a problem.
107     # (See http://developer.apple.com/qa/qa2001/qa1173.html)
108
109     global dirs_by_dir, files_by_dir
110     dirs_by_dir={}
111     files_by_dir={}
112     
113     # C3 8C = 00CC LATIN CAPITAL LETTER I WITH GRAVE
114     # (in NFC)
115     maketrack("Joe Bloggs/First Album/01:F\xC3\x8Crst track.ogg")
116
117     maketrack("Joe Bloggs/First Album/02:Second track.ogg")
118
119     # CC 81 = 0301 COMBINING ACUTE ACCENT
120     # (giving an NFD i-acute)
121     maketrack("Joe Bloggs/First Album/03:ThI\xCC\x81rd track.ogg")
122     # ...hopefuly giving C3 8D = 00CD LATIN CAPITAL LETTER I WITH ACUTE
123     maketrack("Joe Bloggs/First Album/04:Fourth track.ogg")
124     maketrack("Joe Bloggs/First Album/05:Fifth track.ogg")
125     maketrack("Joe Bloggs/Second Album/01:First track.ogg")
126     maketrack("Joe Bloggs/Second Album/02:Second track.ogg")
127     maketrack("Joe Bloggs/Second Album/03:Third track.ogg")
128     maketrack("Joe Bloggs/Second Album/04:Fourth track.ogg")
129     maketrack("Joe Bloggs/Second Album/05:Fifth track.ogg")
130     maketrack("Joe Bloggs/Third Album/01:First track.ogg")
131     maketrack("Joe Bloggs/Third Album/02:Second track.ogg")
132     maketrack("Joe Bloggs/Third Album/03:Third track.ogg")
133     maketrack("Joe Bloggs/Third Album/04:Fourth track.ogg")
134     maketrack("Joe Bloggs/Third Album/05:Fifth track.ogg")
135     maketrack("Fred Smith/Boring/01:Dull.ogg")
136     maketrack("Fred Smith/Boring/02:Tedious.ogg")
137     maketrack("Fred Smith/Boring/03:Drum Solo.ogg")
138     maketrack("Fred Smith/Boring/04:Yawn.ogg")
139     maketrack("misc/blahblahblah.ogg")
140     maketrack("Various/Greatest Hits/01:Jim Whatever - Spong.ogg")
141     maketrack("Various/Greatest Hits/02:Joe Bloggs - Yadda.ogg")
142  
143 def common_setup():
144     remove_dir(testroot)
145     os.mkdir(testroot)
146     open("%s/config" % testroot, "w").write(
147     """player *.ogg shell 'echo "$TRACK" >> %s/played.log'
148 home %s
149 collection fs UTF-8 %s/tracks
150 scratch %s/scratch.ogg
151 gap 0
152 stopword 01 02 03 04 05 06 07 08 09 10
153 stopword 1 2 3 4 5 6 7 8 9
154 stopword 11 12 13 14 15 16 17 18 19 20
155 stopword 21 22 23 24 25 26 27 28 29 30
156 stopword the a an and to too in on of we i am as im for is
157 username fred
158 password fredpass
159 allow fred fredpass
160 plugins %s/plugins
161 player *.mp3 execraw disorder-decode
162 player *.ogg execraw disorder-decode
163 player *.wav execraw disorder-decode
164 player *.flac execraw disorder-decode
165 tracklength *.mp3 disorder-tracklength
166 tracklength *.ogg disorder-tracklength
167 tracklength *.wav disorder-tracklength
168 tracklength *.flac disorder-tracklength
169 """ % (testroot, testroot, testroot, testroot, top_builddir))
170     copyfile("%s/sounds/scratch.ogg" % top_srcdir,
171              "%s/scratch.ogg" % testroot)
172
173 def start_daemon():
174     """start_daemon()
175
176 Start the daemon."""
177     global daemon, errs
178     assert daemon == None
179     print " starting daemon"
180     # remove the socket if it exists
181     socket = "%s/socket" % testroot
182     try:
183         os.remove(socket)
184     except:
185         pass
186     daemon = subprocess.Popen(["disorderd",
187                                "--foreground",
188                                "--config", "%s/config" % testroot],
189                               stderr=errs)
190     # Wait for the socket to be created
191     waited = 0
192     while not os.path.exists(socket):
193         rc = daemon.poll()
194         if rc is not None:
195             print "FATAL: daemon failed to start up"
196             sys.exit(1)
197         waited += 1
198         if waited == 1:
199             print "  waiting for socket..."
200         elif waited >= 60:
201             print "FATAL: took too long for socket to appear"
202             sys.exit(1)
203         time.sleep(1)
204     if waited > 0:
205         print "  took about %ds for socket to appear" % waited
206
207 def stop_daemon():
208     """stop_daemon()
209
210 Stop the daemon if it has not stopped already"""
211     global daemon
212     if daemon == None:
213         return
214     rc = daemon.poll()
215     if rc == None:
216         print " stopping daemon"
217         os.kill(daemon.pid, 15)
218         print "  waiting for daemon"
219         rc = daemon.wait()
220         print "  daemon has stopped"
221     else:
222         print "  daemon already stopped"
223     daemon = None
224
225 def run(module=None, report=True):
226     """dtest.run(MODULE)
227
228     Run the test in MODULE.  This can be a string (in which case the module
229     will be imported) or a module object."""
230     global tests
231     tests += 1
232     # Locate the test module
233     if module is None:
234         # We're running a test stand-alone
235         import __main__
236         module = __main__
237         name = os.path.splitext(os.path.basename(sys.argv[0]))[0]
238     else:
239         # We've been passed a module or a module name
240         if type(module) == str:
241             module = __import__(module)
242         name = module.__name__
243     # Open the error log
244     global errs
245     errs = open("%s.log" % name, "w")
246     # Ensure that disorder.py uses the test installation
247     disorder._configfile = "%s/config" % testroot
248     disorder._userconf = False
249     # Make config file etc
250     common_setup()
251     # Create some standard tracks
252     stdtracks()
253     try:
254         try:
255             module.test()
256         except AssertionError, e:
257             global failures
258             failures += 1
259             print e
260     finally:
261         stop_daemon()
262     if report:
263         if failures:
264             print " FAILED"
265             sys.exit(1)
266         else:
267             print " OK"
268
269 def remove_dir(d):
270     """remove_dir(D)
271
272 Recursively delete directory D"""
273     if os.path.lexists(d):
274         if os.path.isdir(d):
275             for dd in os.listdir(d):
276                 remove_dir("%s/%s" % (d, dd))
277             os.rmdir(d)
278         else:
279             os.remove(d)
280
281 def check_files():
282     c = disorder.client()
283     failures = 0
284     for d in dirs_by_dir:
285         xdirs = dirs_by_dir[d]
286         dirs = c.directories(d)
287         xdirs.sort()
288         dirs.sort()
289         if dirs != xdirs:
290             print
291             print "directory: %s" % d
292             print "expected:  %s" % xdirs
293             print "got:       %s" % dirs
294             failures += 1
295     for d in files_by_dir:
296         xfiles = files_by_dir[d]
297         files = c.files(d)
298         xfiles.sort()
299         files.sort()
300         if files != xfiles:
301             print
302             print "directory: %s" % d
303             print "expected:  %s" % xfiles
304             print "got:       %s" % files
305             failures += 1
306     return failures
307
308 # -----------------------------------------------------------------------------
309 # Common setup
310
311 tests = 0
312 failures = 0
313 daemon = None
314 testroot = "%s/tests/testroot" % top_builddir
315 tracks = "%s/tracks" % testroot