PageRenderTime 44ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 0ms

/tests/dtest.py

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