test 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 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/slap.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 common_setup():
154 remove_dir(testroot)
155 os.mkdir(testroot)
156 open("%s/config" % testroot, "w").write(
157 """player *.ogg shell 'echo "$TRACK" >> %s/played.log'
158 home %s
159 collection fs UTF-8 %s/tracks
160 scratch %s/scratch.ogg
161 gap 0
162 stopword 01 02 03 04 05 06 07 08 09 10
163 stopword 1 2 3 4 5 6 7 8 9
164 stopword 11 12 13 14 15 16 17 18 19 20
165 stopword 21 22 23 24 25 26 27 28 29 30
166 stopword the a an and to too in on of we i am as im for is
167 username fred
168 password fredpass
169 allow fred fredpass
170 plugins %s/plugins
171 player *.mp3 execraw disorder-decode
172 player *.ogg execraw disorder-decode
173 player *.wav execraw disorder-decode
174 player *.flac execraw disorder-decode
175 tracklength *.mp3 disorder-tracklength
176 tracklength *.ogg disorder-tracklength
177 tracklength *.wav disorder-tracklength
178 tracklength *.flac disorder-tracklength
179 """ % (testroot, testroot, testroot, testroot, top_builddir))
180 copyfile("%s/sounds/scratch.ogg" % top_srcdir,
181 "%s/scratch.ogg" % testroot)
182
183 def start_daemon():
184 """start_daemon()
185
186 Start the daemon."""
187 global daemon, errs
188 assert daemon == None
189 print " starting daemon"
190 # remove the socket if it exists
191 socket = "%s/socket" % testroot
192 try:
193 os.remove(socket)
194 except:
195 pass
196 daemon = subprocess.Popen(["disorderd",
197 "--foreground",
198 "--config", "%s/config" % testroot],
199 stderr=errs)
200 # Wait for the socket to be created
201 waited = 0
202 while not os.path.exists(socket):
203 rc = daemon.poll()
204 if rc is not None:
205 print "FATAL: daemon failed to start up"
206 sys.exit(1)
207 waited += 1
208 if waited == 1:
209 print " waiting for socket..."
210 elif waited >= 60:
211 print "FATAL: took too long for socket to appear"
212 sys.exit(1)
213 time.sleep(1)
214 if waited > 0:
215 print " took about %ds for socket to appear" % waited
216
217 def stop_daemon():
218 """stop_daemon()
219
220 Stop the daemon if it has not stopped already"""
221 global daemon
222 if daemon == None:
223 return
224 rc = daemon.poll()
225 if rc == None:
226 print " stopping daemon"
227 os.kill(daemon.pid, 15)
228 print " waiting for daemon"
229 rc = daemon.wait()
230 print " daemon has stopped"
231 else:
232 print " daemon already stopped"
233 daemon = None
234
235 def run(module=None, report=True):
236 """dtest.run(MODULE)
237
238 Run the test in MODULE. This can be a string (in which case the module
239 will be imported) or a module object."""
240 global tests
241 tests += 1
242 # Locate the test module
243 if module is None:
244 # We're running a test stand-alone
245 import __main__
246 module = __main__
247 name = os.path.splitext(os.path.basename(sys.argv[0]))[0]
248 else:
249 # We've been passed a module or a module name
250 if type(module) == str:
251 module = __import__(module)
252 name = module.__name__
253 # Open the error log
254 global errs
255 errs = open("%s.log" % name, "w")
256 # Ensure that disorder.py uses the test installation
257 disorder._configfile = "%s/config" % testroot
258 disorder._userconf = False
259 # Make config file etc
260 common_setup()
261 # Create some standard tracks
262 stdtracks()
263 try:
264 try:
265 module.test()
266 except AssertionError, e:
267 global failures
268 failures += 1
269 print e
270 finally:
271 stop_daemon()
272 if report:
273 if failures:
274 print " FAILED"
275 sys.exit(1)
276 else:
277 print " OK"
278
279 def remove_dir(d):
280 """remove_dir(D)
281
282 Recursively delete directory D"""
283 if os.path.lexists(d):
284 if os.path.isdir(d):
285 for dd in os.listdir(d):
286 remove_dir("%s/%s" % (d, dd))
287 os.rmdir(d)
288 else:
289 os.remove(d)
290
291 def check_files():
292 c = disorder.client()
293 failures = 0
294 for d in dirs_by_dir:
295 xdirs = dirs_by_dir[d]
296 dirs = c.directories(d)
297 xdirs.sort()
298 dirs.sort()
299 if dirs != xdirs:
300 print
301 print "directory: %s" % d
302 print "expected: %s" % xdirs
303 print "got: %s" % dirs
304 failures += 1
305 for d in files_by_dir:
306 xfiles = files_by_dir[d]
307 files = c.files(d)
308 xfiles.sort()
309 files.sort()
310 if files != xfiles:
311 print
312 print "directory: %s" % d
313 print "expected: %s" % xfiles
314 print "got: %s" % files
315 failures += 1
316 return failures
317
318 # -----------------------------------------------------------------------------
319 # Common setup
320
321 tests = 0
322 failures = 0
323 daemon = None
324 testroot = "%s/tests/testroot" % top_builddir
325 tracks = "%s/tracks" % testroot