chiark / gitweb /
exercise the C client a bit from tests
[disorder] / tests / dtest.py
CommitLineData
c5dbcd79 1#-*-python-*-
aa896435
RK
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#
c5dbcd79
RK
21
22"""Utility module used by tests"""
23
213b4064 24import os,os.path,subprocess,sys,re,time,unicodedata,random
3bfecfac
RK
25
26def 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
32cwd = os.getcwd()
33if os.path.exists("config.h"):
34 top_builddir = cwd
35elif os.path.exists("alltests"):
36 top_builddir = os.path.dirname(cwd)
37else:
38 fatal("cannot identify build directory")
39
40# Make sure the Python build directory is on the module search path
41sys.path.insert(0, os.path.join(top_builddir, "python"))
42import disorder
43
d48eab4d 44# Make sure the build directories are on the executable search path
3bfecfac
RK
45ospath = os.environ["PATH"].split(os.pathsep)
46ospath.insert(0, os.path.join(top_builddir, "server"))
d48eab4d 47ospath.insert(0, os.path.join(top_builddir, "clients"))
3bfecfac
RK
48os.environ["PATH"] = os.pathsep.join(ospath)
49
50# Parse the makefile in the current directory to identify the source directory
51top_srcdir = None
52for l in file("Makefile"):
53 r = re.match("top_srcdir *= *(.*)", l)
54 if r:
55 top_srcdir = r.group(1)
56 break
57if 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# -----------------------------------------------------------------------------
c5dbcd79
RK
64
65def copyfile(a,b):
66 """copyfile(A, B)
67Copy A to B."""
68 open(b,"w").write(open(a).read())
69
de5ccb1a
RK
70def 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
77def nfc(s):
78 """Convert UTF-8 string or unicode to NFC unicode."""
79 return unicodedata.normalize("NFC", to_unicode(s))
80
c5dbcd79
RK
81def maketrack(s):
82 """maketrack(S)
83
84Make track with relative path S exist"""
121e3654 85 trackpath = "%s/%s" % (tracks, s)
c5dbcd79
RK
86 trackdir = os.path.dirname(trackpath)
87 if not os.path.exists(trackdir):
88 os.makedirs(trackdir)
3bfecfac 89 copyfile("%s/sounds/slap.ogg" % top_srcdir, trackpath)
121e3654 90 # We record the tracks we created so they can be tested against
7bbe944b
RK
91 # server responses. We put them into NFC since that's what the server
92 # uses internally.
de5ccb1a 93 bits = nfc(s).split('/')
121e3654
RK
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]))
c5dbcd79
RK
105
106def stdtracks():
f9635e06
RK
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)
121e3654
RK
119
120 global dirs_by_dir, files_by_dir
121 dirs_by_dir={}
122 files_by_dir={}
f9635e06
RK
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
c5dbcd79 128 maketrack("Joe Bloggs/First Album/02:Second track.ogg")
f9635e06
RK
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
c5dbcd79
RK
134 maketrack("Joe Bloggs/First Album/04:Fourth track.ogg")
135 maketrack("Joe Bloggs/First Album/05:Fifth track.ogg")
c5dbcd79
RK
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")
de5ccb1a
RK
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")
c5dbcd79
RK
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")
0db97c0d 153
f9635e06
RK
154def common_setup():
155 remove_dir(testroot)
156 os.mkdir(testroot)
213b4064
RK
157 global port
158 port = random.randint(49152, 65535)
f9635e06 159 open("%s/config" % testroot, "w").write(
213b4064 160 """home %s
b6995afb
RK
161collection fs UTF-8 %s/tracks
162scratch %s/scratch.ogg
163gap 0
164stopword 01 02 03 04 05 06 07 08 09 10
165stopword 1 2 3 4 5 6 7 8 9
166stopword 11 12 13 14 15 16 17 18 19 20
167stopword 21 22 23 24 25 26 27 28 29 30
168stopword the a an and to too in on of we i am as im for is
169username fred
170password fredpass
171allow fred fredpass
40c30921 172plugins
deaaa115 173plugins %s/plugins
40c30921 174plugins %s/plugins/.libs
b6995afb
RK
175player *.mp3 execraw disorder-decode
176player *.ogg execraw disorder-decode
177player *.wav execraw disorder-decode
178player *.flac execraw disorder-decode
179tracklength *.mp3 disorder-tracklength
180tracklength *.ogg disorder-tracklength
181tracklength *.wav disorder-tracklength
182tracklength *.flac disorder-tracklength
213b4064
RK
183speaker_backend network
184broadcast 127.0.0.1 %d
185broadcast_from 127.0.0.1 %d
186""" % (testroot, testroot, testroot, top_builddir, top_builddir,
187 port, port + 1))
fbcfb257 188 copyfile("%s/sounds/scratch.ogg" % top_srcdir,
f9635e06
RK
189 "%s/scratch.ogg" % testroot)
190
1c8f3db8
RK
191def start_daemon():
192 """start_daemon()
c5dbcd79 193
1c8f3db8 194Start the daemon."""
fc9c24e3 195 global daemon, errs
213b4064 196 assert daemon == None, "no daemon running"
c5dbcd79 197 print " starting daemon"
1a4a6350
RK
198 # remove the socket if it exists
199 socket = "%s/socket" % testroot
200 try:
201 os.remove(socket)
202 except:
203 pass
c5dbcd79
RK
204 daemon = subprocess.Popen(["disorderd",
205 "--foreground",
206 "--config", "%s/config" % testroot],
207 stderr=errs)
1a4a6350
RK
208 # Wait for the socket to be created
209 waited = 0
210 while not os.path.exists(socket):
211 rc = daemon.poll()
212 if rc is not None:
213 print "FATAL: daemon failed to start up"
214 sys.exit(1)
215 waited += 1
216 if waited == 1:
217 print " waiting for socket..."
218 elif waited >= 60:
219 print "FATAL: took too long for socket to appear"
220 sys.exit(1)
221 time.sleep(1)
222 if waited > 0:
223 print " took about %ds for socket to appear" % waited
c5dbcd79 224
f9635e06
RK
225def stop_daemon():
226 """stop_daemon()
c5dbcd79
RK
227
228Stop the daemon if it has not stopped already"""
229 global daemon
5c07ba71
RK
230 if daemon == None:
231 return
c5dbcd79
RK
232 rc = daemon.poll()
233 if rc == None:
eee9d4b3 234 print " stopping daemon"
c5dbcd79 235 os.kill(daemon.pid, 15)
1a4a6350 236 print " waiting for daemon"
c5dbcd79 237 rc = daemon.wait()
1a4a6350
RK
238 print " daemon has stopped"
239 else:
240 print " daemon already stopped"
c5dbcd79
RK
241 daemon = None
242
5c07ba71
RK
243def run(module=None, report=True):
244 """dtest.run(MODULE)
245
246 Run the test in MODULE. This can be a string (in which case the module
247 will be imported) or a module object."""
c5dbcd79
RK
248 global tests
249 tests += 1
deaaa115 250 # Locate the test module
5c07ba71
RK
251 if module is None:
252 # We're running a test stand-alone
253 import __main__
254 module = __main__
255 name = os.path.splitext(os.path.basename(sys.argv[0]))[0]
256 else:
257 # We've been passed a module or a module name
258 if type(module) == str:
259 module = __import__(module)
260 name = module.__name__
deaaa115 261 # Open the error log
5c07ba71
RK
262 global errs
263 errs = open("%s.log" % name, "w")
deaaa115 264 # Ensure that disorder.py uses the test installation
1c8f3db8
RK
265 disorder._configfile = "%s/config" % testroot
266 disorder._userconf = False
3514766b 267 # Make config file etc
f9635e06 268 common_setup()
deaaa115
RK
269 # Create some standard tracks
270 stdtracks()
c5dbcd79 271 try:
eee9d4b3 272 try:
5c07ba71 273 module.test()
eee9d4b3
RK
274 except AssertionError, e:
275 global failures
276 failures += 1
213b4064 277 print "assertion failed: %s" % e.message
eee9d4b3 278 finally:
7ebd22d9 279 stop_daemon()
c5dbcd79
RK
280 if report:
281 if failures:
282 print " FAILED"
283 sys.exit(1)
284 else:
285 print " OK"
286
287def remove_dir(d):
288 """remove_dir(D)
289
290Recursively delete directory D"""
291 if os.path.lexists(d):
292 if os.path.isdir(d):
293 for dd in os.listdir(d):
294 remove_dir("%s/%s" % (d, dd))
295 os.rmdir(d)
296 else:
297 os.remove(d)
298
a4d8ba8f
RK
299def check_files():
300 c = disorder.client()
301 failures = 0
302 for d in dirs_by_dir:
303 xdirs = dirs_by_dir[d]
304 dirs = c.directories(d)
305 xdirs.sort()
306 dirs.sort()
307 if dirs != xdirs:
308 print
309 print "directory: %s" % d
310 print "expected: %s" % xdirs
311 print "got: %s" % dirs
312 failures += 1
313 for d in files_by_dir:
314 xfiles = files_by_dir[d]
315 files = c.files(d)
316 xfiles.sort()
317 files.sort()
318 if files != xfiles:
319 print
320 print "directory: %s" % d
321 print "expected: %s" % xfiles
322 print "got: %s" % files
323 failures += 1
324 return failures
325
d48eab4d
RK
326def command(args):
327 """Execute a command given as a list and return its stdout"""
328 p = subprocess.Popen(args, stdout=subprocess.PIPE)
329 lines = p.stdout.readlines()
330 rc = p.wait()
331 assert rc == 0, ("%s returned status %s" % (args, rc))
332 return lines
333
c5dbcd79
RK
334# -----------------------------------------------------------------------------
335# Common setup
336
337tests = 0
338failures = 0
339daemon = None
3bfecfac 340testroot = "%s/tests/testroot" % top_builddir
121e3654 341tracks = "%s/tracks" % testroot