Package CedarBackup2 :: Module testutil
[hide private]
[frames] | no frames]

Source Code for Module CedarBackup2.testutil

  1  # -*- coding: iso-8859-1 -*- 
  2  # vim: set ft=python ts=3 sw=3 expandtab: 
  3  # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # 
  4  # 
  5  #              C E D A R 
  6  #          S O L U T I O N S       "Software done right." 
  7  #           S O F T W A R E 
  8  # 
  9  # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # 
 10  # 
 11  # Copyright (c) 2004-2006 Kenneth J. Pronovici. 
 12  # All rights reserved. 
 13  # 
 14  # This program is free software; you can redistribute it and/or 
 15  # modify it under the terms of the GNU General Public License, 
 16  # Version 2, as published by the Free Software Foundation. 
 17  # 
 18  # This program is distributed in the hope that it will be useful, 
 19  # but WITHOUT ANY WARRANTY; without even the implied warranty of 
 20  # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 
 21  # 
 22  # Copies of the GNU General Public License are available from 
 23  # the Free Software Foundation website, http://www.gnu.org/. 
 24  # 
 25  # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # 
 26  # 
 27  # Author   : Kenneth J. Pronovici <pronovic@ieee.org> 
 28  # Language : Python (>= 2.3) 
 29  # Project  : Cedar Backup, release 2 
 30  # Revision : $Id: testutil.py 1232 2007-09-20 03:07:07Z pronovic $ 
 31  # Purpose  : Provides unit-testing utilities. 
 32  # 
 33  # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # 
 34   
 35  ######################################################################## 
 36  # Module documentation 
 37  ######################################################################## 
 38   
 39  """ 
 40  Provides unit-testing utilities.  
 41   
 42  These utilities are kept here, separate from util.py, because they provide 
 43  common functionality that I do not want exported "publicly" once Cedar Backup 
 44  is installed on a system.  They are only used for unit testing, and are only 
 45  useful within the source tree. 
 46   
 47  Many of these functions are in here because they are "good enough" for unit 
 48  test work but are not robust enough to be real public functions.  Others (like 
 49  L{removedir} do what they are supposed to, but I don't want responsibility for 
 50  making them available to others. 
 51   
 52  @sort: findResources, commandAvailable, 
 53         buildPath, removedir, extractTar, changeFileAge, 
 54         getMaskAsMode, getLogin, failUnlessAssignRaises, runningAsRoot, 
 55         platformMacOsX, platformWindows, platformHasEcho,  
 56         platformSupportsLinks, platformSupportsPermissions, 
 57         platformRequiresBinaryRead 
 58   
 59  @author: Kenneth J. Pronovici <pronovic@ieee.org> 
 60  """ 
 61   
 62   
 63  ######################################################################## 
 64  # Imported modules 
 65  ######################################################################## 
 66   
 67  import sys 
 68  import os 
 69  import tarfile 
 70  import time 
 71  import getpass 
 72  import random 
 73  import string 
 74  import platform 
 75  import logging 
 76  from StringIO import StringIO 
 77   
 78  from CedarBackup2.util import encodePath, executeCommand 
 79   
 80   
 81  ######################################################################## 
 82  # Public functions 
 83  ######################################################################## 
 84   
 85  ############################## 
 86  # setupDebugLogger() function 
 87  ############################## 
 88   
89 -def setupDebugLogger():
90 """ 91 Sets up a screen logger for debugging purposes. 92 93 Normally, the CLI functionality configures the logger so that 94 things get written to the right place. However, for debugging 95 it's sometimes nice to just get everything -- debug information 96 and output -- dumped to the screen. This function takes care 97 of that. 98 """ 99 logger = logging.getLogger("CedarBackup2") 100 logger.setLevel(logging.DEBUG) # let the logger see all messages 101 formatter = logging.Formatter(fmt="%(message)s") 102 handler = logging.StreamHandler(strm=sys.stdout) 103 handler.setFormatter(formatter) 104 handler.setLevel(logging.DEBUG) 105 logger.addHandler(handler)
106 107 108 ########################### 109 # findResources() function 110 ########################### 111
112 -def findResources(resources, dataDirs):
113 """ 114 Returns a dictionary of locations for various resources. 115 @param resources: List of required resources. 116 @param dataDirs: List of data directories to search within for resources. 117 @return: Dictionary mapping resource name to resource path. 118 @raise Exception: If some resource cannot be found. 119 """ 120 mapping = { } 121 for resource in resources: 122 for resourceDir in dataDirs: 123 path = os.path.join(resourceDir, resource); 124 if os.path.exists(path): 125 mapping[resource] = path 126 break 127 else: 128 raise Exception("Unable to find resource [%s]." % resource) 129 return mapping
130 131 132 ############################## 133 # commandAvailable() function 134 ############################## 135
136 -def commandAvailable(command):
137 """ 138 Indicates whether a command is available on $PATH somewhere. 139 This should work on both Windows and UNIX platforms. 140 @param command: Commang to search for 141 @return: Boolean true/false depending on whether command is available. 142 """ 143 if os.environ.has_key("PATH"): 144 for path in os.environ["PATH"].split(os.sep): 145 if os.path.exists(os.path.join(path, command)): 146 return True 147 return False
148 149 150 ####################### 151 # buildPath() function 152 ####################### 153
154 -def buildPath(components):
155 """ 156 Builds a complete path from a list of components. 157 For instance, constructs C{"/a/b/c"} from C{["/a", "b", "c",]}. 158 @param components: List of components. 159 @returns: String path constructed from components. 160 @raise ValueError: If a path cannot be encoded properly. 161 """ 162 path = components[0] 163 for component in components[1:]: 164 path = os.path.join(path, component) 165 return encodePath(path)
166 167 168 ####################### 169 # removedir() function 170 ####################### 171
172 -def removedir(tree):
173 """ 174 Recursively removes an entire directory. 175 This is basically taken from an example on python.com. 176 @param tree: Directory tree to remove. 177 @raise ValueError: If a path cannot be encoded properly. 178 """ 179 tree = encodePath(tree) 180 for root, dirs, files in os.walk(tree, topdown=False): 181 for name in files: 182 path = os.path.join(root, name) 183 if os.path.islink(path): 184 os.remove(path) 185 elif os.path.isfile(path): 186 os.remove(path) 187 for name in dirs: 188 path = os.path.join(root, name) 189 if os.path.islink(path): 190 os.remove(path) 191 elif os.path.isdir(path): 192 os.rmdir(path) 193 os.rmdir(tree)
194 195 196 ######################## 197 # extractTar() function 198 ######################## 199
200 -def extractTar(tmpdir, filepath):
201 """ 202 Extracts the indicated tar file to the indicated tmpdir. 203 @param tmpdir: Temp directory to extract to. 204 @param filepath: Path to tarfile to extract. 205 @raise ValueError: If a path cannot be encoded properly. 206 """ 207 tmpdir = encodePath(tmpdir) 208 filepath = encodePath(filepath) 209 tar = tarfile.open(filepath) 210 tar.posix = False 211 for tarinfo in tar: 212 tar.extract(tarinfo, tmpdir)
213 214 215 ########################### 216 # changeFileAge() function 217 ########################### 218
219 -def changeFileAge(filename, subtract=None):
220 """ 221 Changes a file age using the C{os.utime} function. 222 @param filename: File to operate on. 223 @param subtract: Number of seconds to subtract from the current time. 224 @raise ValueError: If a path cannot be encoded properly. 225 """ 226 filename = encodePath(filename) 227 if subtract is None: 228 os.utime(filename, None) 229 else: 230 newTime = time.time() - subtract 231 os.utime(filename, (newTime, newTime))
232 233 234 ########################### 235 # getMaskAsMode() function 236 ########################### 237
238 -def getMaskAsMode():
239 """ 240 Returns the user's current umask inverted to a mode. 241 A mode is mostly a bitwise inversion of a mask, i.e. mask 002 is mode 775. 242 @return: Umask converted to a mode, as an integer. 243 """ 244 umask = os.umask(0777) 245 os.umask(umask) 246 return int(~umask & 0777) # invert, then use only lower bytes
247 248 249 ###################### 250 # getLogin() function 251 ###################### 252
253 -def getLogin():
254 """ 255 Returns the name of the currently-logged in user. This might fail under 256 some circumstances - but if it does, our tests would fail anyway. 257 """ 258 return getpass.getuser()
259 260 261 ############################ 262 # randomFilename() function 263 ############################ 264
265 -def randomFilename(length, prefix=None, suffix=None):
266 """ 267 Generates a random filename with the given length. 268 @param length: Length of filename. 269 @return Random filename. 270 """ 271 characters = [None] * length 272 for i in xrange(length): 273 characters[i] = random.choice(string.uppercase) 274 if prefix is None: 275 prefix = "" 276 if suffix is None: 277 suffix = "" 278 return "%s%s%s" % (prefix, "".join(characters), suffix)
279 280 281 #################################### 282 # failUnlessAssignRaises() function 283 #################################### 284
285 -def failUnlessAssignRaises(testCase, exception, object, property, value):
286 """ 287 Equivalent of C{failUnlessRaises}, but used for property assignments instead. 288 289 It's nice to be able to use C{failUnlessRaises} to check that a method call 290 raises the exception that you expect. Unfortunately, this method can't be 291 used to check Python propery assignments, even though these property 292 assignments are actually implemented underneath as methods. 293 294 This function (which can be easily called by unit test classes) provides an 295 easy way to wrap the assignment checks. It's not pretty, or as intuitive as 296 the original check it's modeled on, but it does work. 297 298 Let's assume you make this method call:: 299 300 testCase.failUnlessAssignRaises(ValueError, collectDir, "absolutePath", absolutePath) 301 302 If you do this, a test case failure will be raised unless the assignment:: 303 304 collectDir.absolutePath = absolutePath 305 306 fails with a C{ValueError} exception. The failure message differentiates 307 between the case where no exception was raised and the case where the wrong 308 exception was raised. 309 310 @note: Internally, the C{missed} and C{instead} variables are used rather 311 than directly calling C{testCase.fail} upon noticing a problem because the 312 act of "failure" itself generates an exception that would be caught by the 313 general C{except} clause. 314 315 @param testCase: PyUnit test case object (i.e. self). 316 @param exception: Exception that is expected to be raised. 317 @param object: Object whose property is to be assigned to. 318 @param property: Name of the property, as a string. 319 @param value: Value that is to be assigned to the property. 320 321 @see: C{unittest.TestCase.failUnlessRaises} 322 """ 323 missed = False 324 instead = None 325 try: 326 exec "object.%s = value" % property 327 missed = True 328 except exception: pass 329 except Exception, e: instead = e 330 if missed: 331 testCase.fail("Expected assignment to raise %s, but got no exception." % (exception.__name__)) 332 if instead is not None: 333 testCase.fail("Expected assignment to raise %s, but got %s instead." % (ValueError, instead.__class__.__name__))
334 335 336 ########################### 337 # captureOutput() function 338 ########################### 339
340 -def captureOutput(callable):
341 """ 342 Captures the output (stdout, stderr) of a function or a method. 343 344 Some of our functions don't do anything other than just print output. We 345 need a way to test these functions (at least nominally) but we don't want 346 any of the output spoiling the test suite output. 347 348 This function just creates a dummy file descriptor that can be used as a 349 target by the callable function, rather than C{stdout} or C{stderr}. 350 351 @note: This method assumes that C{callable} doesn't take any arguments 352 besides keyword argument C{fd} to specify the file descriptor. 353 354 @param callable: Callable function or method. 355 356 @return: Output of function, as one big string. 357 """ 358 fd = StringIO() 359 callable(fd=fd) 360 result = fd.getvalue() 361 fd.close() 362 return result
363 364 365 ######################### 366 # _isPlatform() function 367 ######################### 368
369 -def _isPlatform(name):
370 """ 371 Returns boolean indicating whether we're running on the indicated platform. 372 @param name: Platform name to check, currently one of "windows" or "macosx" 373 """ 374 if name == "windows": 375 return platform.platform(True, True).startswith("Windows") 376 elif name == "macosx": 377 return sys.platform == "darwin" 378 else: 379 raise ValueError("Unknown platform [%s]." % name)
380 381 382 ############################ 383 # platformMacOsX() function 384 ############################ 385
386 -def platformMacOsX():
387 """ 388 Returns boolean indicating whether this is the Mac OS X platform. 389 """ 390 return _isPlatform("macosx")
391 392 393 ############################# 394 # platformWindows() function 395 ############################# 396
397 -def platformWindows():
398 """ 399 Returns boolean indicating whether this is the Windows platform. 400 """ 401 return _isPlatform("windows")
402 403 404 ################################### 405 # platformSupportsLinks() function 406 ################################### 407 415 416 417 ######################################### 418 # platformSupportsPermissions() function 419 ######################################### 420
421 -def platformSupportsPermissions():
422 """ 423 Returns boolean indicating whether the platform supports UNIX-style file permissions. 424 Some platforms, like Windows, do not support permissions, and tests need to take 425 this into account. 426 """ 427 return not platformWindows()
428 429 430 ######################################## 431 # platformRequiresBinaryRead() function 432 ######################################## 433
434 -def platformRequiresBinaryRead():
435 """ 436 Returns boolean indicating whether the platform requires binary reads. 437 Some platforms, like Windows, require a special flag to read binary data 438 from files. 439 """ 440 return platformWindows()
441 442 443 ############################# 444 # platformHasEcho() function 445 ############################# 446
447 -def platformHasEcho():
448 """ 449 Returns boolean indicating whether the platform has a sensible echo command. 450 On some platforms, like Windows, echo doesn't really work for tests. 451 """ 452 return not platformWindows()
453 454 455 ########################### 456 # runningAsRoot() function 457 ########################### 458
459 -def runningAsRoot():
460 """ 461 Returns boolean indicating whether the effective user id is root. 462 This is always true on platforms that have no concept of root, like Windows. 463 """ 464 if platformWindows(): 465 return True 466 else: 467 return os.geteuid() == 0
468 469 470 ############################## 471 # availableLocales() function 472 ############################## 473
474 -def availableLocales():
475 """ 476 Returns a list of available locales on the system 477 @return: List of string locale names 478 """ 479 locales = [] 480 output = executeCommand(["locale"], [ "-a", ], returnOutput=True, ignoreStderr=True)[1] 481 for line in output: 482 locales.append(line.rstrip()) 483 return locales
484