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,2008 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 969 2010-05-22 16:25:56Z 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         platformDebian, platformMacOsX, platformCygwin, platformWindows,  
 56         platformHasEcho, 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  from CedarBackup2.config import Config, OptionsConfig 
 80  from CedarBackup2.customize import customizeOverrides 
 81  from CedarBackup2.cli import setupPathResolver 
 82   
 83   
 84  ######################################################################## 
 85  # Public functions 
 86  ######################################################################## 
 87   
 88  ############################## 
 89  # setupDebugLogger() function 
 90  ############################## 
 91   
92 -def setupDebugLogger():
93 """ 94 Sets up a screen logger for debugging purposes. 95 96 Normally, the CLI functionality configures the logger so that 97 things get written to the right place. However, for debugging 98 it's sometimes nice to just get everything -- debug information 99 and output -- dumped to the screen. This function takes care 100 of that. 101 """ 102 logger = logging.getLogger("CedarBackup2") 103 logger.setLevel(logging.DEBUG) # let the logger see all messages 104 formatter = logging.Formatter(fmt="%(message)s") 105 handler = logging.StreamHandler(strm=sys.stdout) 106 handler.setFormatter(formatter) 107 handler.setLevel(logging.DEBUG) 108 logger.addHandler(handler)
109 110 111 ################# 112 # setupOverrides 113 ################# 114
115 -def setupOverrides():
116 """ 117 Set up any platform-specific overrides that might be required. 118 119 When packages are built, this is done manually (hardcoded) in customize.py 120 and the overrides are set up in cli.cli(). This way, no runtime checks need 121 to be done. This is safe, because the package maintainer knows exactly 122 which platform (Debian or not) the package is being built for. 123 124 Unit tests are different, because they might be run anywhere. So, we 125 attempt to make a guess about plaform using platformDebian(), and use that 126 to set up the custom overrides so that platform-specific unit tests continue 127 to work. 128 """ 129 config = Config() 130 config.options = OptionsConfig() 131 if platformDebian(): 132 customizeOverrides(config, platform="debian") 133 else: 134 customizeOverrides(config, platform="standard") 135 setupPathResolver(config)
136 137 138 ########################### 139 # findResources() function 140 ########################### 141
142 -def findResources(resources, dataDirs):
143 """ 144 Returns a dictionary of locations for various resources. 145 @param resources: List of required resources. 146 @param dataDirs: List of data directories to search within for resources. 147 @return: Dictionary mapping resource name to resource path. 148 @raise Exception: If some resource cannot be found. 149 """ 150 mapping = { } 151 for resource in resources: 152 for resourceDir in dataDirs: 153 path = os.path.join(resourceDir, resource); 154 if os.path.exists(path): 155 mapping[resource] = path 156 break 157 else: 158 raise Exception("Unable to find resource [%s]." % resource) 159 return mapping
160 161 162 ############################## 163 # commandAvailable() function 164 ############################## 165
166 -def commandAvailable(command):
167 """ 168 Indicates whether a command is available on $PATH somewhere. 169 This should work on both Windows and UNIX platforms. 170 @param command: Commang to search for 171 @return: Boolean true/false depending on whether command is available. 172 """ 173 if os.environ.has_key("PATH"): 174 for path in os.environ["PATH"].split(os.sep): 175 if os.path.exists(os.path.join(path, command)): 176 return True 177 return False
178 179 180 ####################### 181 # buildPath() function 182 ####################### 183
184 -def buildPath(components):
185 """ 186 Builds a complete path from a list of components. 187 For instance, constructs C{"/a/b/c"} from C{["/a", "b", "c",]}. 188 @param components: List of components. 189 @returns: String path constructed from components. 190 @raise ValueError: If a path cannot be encoded properly. 191 """ 192 path = components[0] 193 for component in components[1:]: 194 path = os.path.join(path, component) 195 return encodePath(path)
196 197 198 ####################### 199 # removedir() function 200 ####################### 201
202 -def removedir(tree):
203 """ 204 Recursively removes an entire directory. 205 This is basically taken from an example on python.com. 206 @param tree: Directory tree to remove. 207 @raise ValueError: If a path cannot be encoded properly. 208 """ 209 tree = encodePath(tree) 210 for root, dirs, files in os.walk(tree, topdown=False): 211 for name in files: 212 path = os.path.join(root, name) 213 if os.path.islink(path): 214 os.remove(path) 215 elif os.path.isfile(path): 216 os.remove(path) 217 for name in dirs: 218 path = os.path.join(root, name) 219 if os.path.islink(path): 220 os.remove(path) 221 elif os.path.isdir(path): 222 os.rmdir(path) 223 os.rmdir(tree)
224 225 226 ######################## 227 # extractTar() function 228 ######################## 229
230 -def extractTar(tmpdir, filepath):
231 """ 232 Extracts the indicated tar file to the indicated tmpdir. 233 @param tmpdir: Temp directory to extract to. 234 @param filepath: Path to tarfile to extract. 235 @raise ValueError: If a path cannot be encoded properly. 236 """ 237 tmpdir = encodePath(tmpdir) 238 filepath = encodePath(filepath) 239 tar = tarfile.open(filepath) 240 try: 241 tar.format = tarfile.GNU_FORMAT 242 except: 243 tar.posix = False 244 for tarinfo in tar: 245 tar.extract(tarinfo, tmpdir)
246 247 248 ########################### 249 # changeFileAge() function 250 ########################### 251
252 -def changeFileAge(filename, subtract=None):
253 """ 254 Changes a file age using the C{os.utime} function. 255 256 @note: Some platforms don't seem to be able to set an age precisely. As a 257 result, whereas we might have intended to set an age of 86400 seconds, we 258 actually get an age of 86399.375 seconds. When util.calculateFileAge() 259 looks at that the file, it calculates an age of 0.999992766204 days, which 260 then gets truncated down to zero whole days. The tests get very confused. 261 To work around this, I always subtract off one additional second as a fudge 262 factor. That way, the file age will be I{at least} as old as requested 263 later on. 264 265 @param filename: File to operate on. 266 @param subtract: Number of seconds to subtract from the current time. 267 @raise ValueError: If a path cannot be encoded properly. 268 """ 269 filename = encodePath(filename) 270 newTime = time.time() - 1; 271 if subtract is not None: 272 newTime -= subtract 273 os.utime(filename, (newTime, newTime))
274 275 276 ########################### 277 # getMaskAsMode() function 278 ########################### 279
280 -def getMaskAsMode():
281 """ 282 Returns the user's current umask inverted to a mode. 283 A mode is mostly a bitwise inversion of a mask, i.e. mask 002 is mode 775. 284 @return: Umask converted to a mode, as an integer. 285 """ 286 umask = os.umask(0777) 287 os.umask(umask) 288 return int(~umask & 0777) # invert, then use only lower bytes
289 290 291 ###################### 292 # getLogin() function 293 ###################### 294
295 -def getLogin():
296 """ 297 Returns the name of the currently-logged in user. This might fail under 298 some circumstances - but if it does, our tests would fail anyway. 299 """ 300 return getpass.getuser()
301 302 303 ############################ 304 # randomFilename() function 305 ############################ 306
307 -def randomFilename(length, prefix=None, suffix=None):
308 """ 309 Generates a random filename with the given length. 310 @param length: Length of filename. 311 @return Random filename. 312 """ 313 characters = [None] * length 314 for i in xrange(length): 315 characters[i] = random.choice(string.uppercase) 316 if prefix is None: 317 prefix = "" 318 if suffix is None: 319 suffix = "" 320 return "%s%s%s" % (prefix, "".join(characters), suffix)
321 322 323 #################################### 324 # failUnlessAssignRaises() function 325 #################################### 326
327 -def failUnlessAssignRaises(testCase, exception, object, property, value):
328 """ 329 Equivalent of C{failUnlessRaises}, but used for property assignments instead. 330 331 It's nice to be able to use C{failUnlessRaises} to check that a method call 332 raises the exception that you expect. Unfortunately, this method can't be 333 used to check Python propery assignments, even though these property 334 assignments are actually implemented underneath as methods. 335 336 This function (which can be easily called by unit test classes) provides an 337 easy way to wrap the assignment checks. It's not pretty, or as intuitive as 338 the original check it's modeled on, but it does work. 339 340 Let's assume you make this method call:: 341 342 testCase.failUnlessAssignRaises(ValueError, collectDir, "absolutePath", absolutePath) 343 344 If you do this, a test case failure will be raised unless the assignment:: 345 346 collectDir.absolutePath = absolutePath 347 348 fails with a C{ValueError} exception. The failure message differentiates 349 between the case where no exception was raised and the case where the wrong 350 exception was raised. 351 352 @note: Internally, the C{missed} and C{instead} variables are used rather 353 than directly calling C{testCase.fail} upon noticing a problem because the 354 act of "failure" itself generates an exception that would be caught by the 355 general C{except} clause. 356 357 @param testCase: PyUnit test case object (i.e. self). 358 @param exception: Exception that is expected to be raised. 359 @param object: Object whose property is to be assigned to. 360 @param property: Name of the property, as a string. 361 @param value: Value that is to be assigned to the property. 362 363 @see: C{unittest.TestCase.failUnlessRaises} 364 """ 365 missed = False 366 instead = None 367 try: 368 exec "object.%s = value" % property 369 missed = True 370 except exception: pass 371 except Exception, e: instead = e 372 if missed: 373 testCase.fail("Expected assignment to raise %s, but got no exception." % (exception.__name__)) 374 if instead is not None: 375 testCase.fail("Expected assignment to raise %s, but got %s instead." % (ValueError, instead.__class__.__name__))
376 377 378 ########################### 379 # captureOutput() function 380 ########################### 381
382 -def captureOutput(callable):
383 """ 384 Captures the output (stdout, stderr) of a function or a method. 385 386 Some of our functions don't do anything other than just print output. We 387 need a way to test these functions (at least nominally) but we don't want 388 any of the output spoiling the test suite output. 389 390 This function just creates a dummy file descriptor that can be used as a 391 target by the callable function, rather than C{stdout} or C{stderr}. 392 393 @note: This method assumes that C{callable} doesn't take any arguments 394 besides keyword argument C{fd} to specify the file descriptor. 395 396 @param callable: Callable function or method. 397 398 @return: Output of function, as one big string. 399 """ 400 fd = StringIO() 401 callable(fd=fd) 402 result = fd.getvalue() 403 fd.close() 404 return result
405 406 407 ######################### 408 # _isPlatform() function 409 ######################### 410
411 -def _isPlatform(name):
412 """ 413 Returns boolean indicating whether we're running on the indicated platform. 414 @param name: Platform name to check, currently one of "windows" or "macosx" 415 """ 416 if name == "windows": 417 return platform.platform(True, True).startswith("Windows") 418 elif name == "macosx": 419 return sys.platform == "darwin" 420 elif name == "debian": 421 return platform.platform(False, False).find("debian") > 0 422 elif name == "cygwin": 423 return platform.platform(True, True).startswith("CYGWIN") 424 else: 425 raise ValueError("Unknown platform [%s]." % name)
426 427 428 ############################ 429 # platformDebian() function 430 ############################ 431
432 -def platformDebian():
433 """ 434 Returns boolean indicating whether this is the Debian platform. 435 """ 436 return _isPlatform("debian")
437 438 439 ############################ 440 # platformMacOsX() function 441 ############################ 442
443 -def platformMacOsX():
444 """ 445 Returns boolean indicating whether this is the Mac OS X platform. 446 """ 447 return _isPlatform("macosx")
448 449 450 ############################# 451 # platformWindows() function 452 ############################# 453
454 -def platformWindows():
455 """ 456 Returns boolean indicating whether this is the Windows platform. 457 """ 458 return _isPlatform("windows")
459 460 461 ############################ 462 # platformCygwin() function 463 ############################ 464
465 -def platformCygwin():
466 """ 467 Returns boolean indicating whether this is the Cygwin platform. 468 """ 469 return _isPlatform("cygwin")
470 471 472 ################################### 473 # platformSupportsLinks() function 474 ################################### 475 483 484 485 ######################################### 486 # platformSupportsPermissions() function 487 ######################################### 488
489 -def platformSupportsPermissions():
490 """ 491 Returns boolean indicating whether the platform supports UNIX-style file permissions. 492 Some platforms, like Windows, do not support permissions, and tests need to take 493 this into account. 494 """ 495 return not platformWindows()
496 497 498 ######################################## 499 # platformRequiresBinaryRead() function 500 ######################################## 501
502 -def platformRequiresBinaryRead():
503 """ 504 Returns boolean indicating whether the platform requires binary reads. 505 Some platforms, like Windows, require a special flag to read binary data 506 from files. 507 """ 508 return platformWindows()
509 510 511 ############################# 512 # platformHasEcho() function 513 ############################# 514
515 -def platformHasEcho():
516 """ 517 Returns boolean indicating whether the platform has a sensible echo command. 518 On some platforms, like Windows, echo doesn't really work for tests. 519 """ 520 return not platformWindows()
521 522 523 ########################### 524 # runningAsRoot() function 525 ########################### 526
527 -def runningAsRoot():
528 """ 529 Returns boolean indicating whether the effective user id is root. 530 This is always true on platforms that have no concept of root, like Windows. 531 """ 532 if platformWindows(): 533 return True 534 else: 535 return os.geteuid() == 0
536 537 538 ############################## 539 # availableLocales() function 540 ############################## 541
542 -def availableLocales():
543 """ 544 Returns a list of available locales on the system 545 @return: List of string locale names 546 """ 547 locales = [] 548 output = executeCommand(["locale"], [ "-a", ], returnOutput=True, ignoreStderr=True)[1] 549 for line in output: 550 locales.append(line.rstrip()) 551 return locales
552 553 554 #################################### 555 # hexFloatLiteralAllowed() function 556 #################################### 557
558 -def hexFloatLiteralAllowed():
559 """ 560 Indicates whether hex float literals are allowed by the interpreter. 561 562 As far back as 2004, some Python documentation indicated that octal and hex 563 notation applied only to integer literals. However, prior to Python 2.5, it 564 was legal to construct a float with an argument like 0xAC on some platforms. 565 This check provides a an indication of whether the current interpreter 566 supports that behavior. 567 568 This check exists so that unit tests can continue to test the same thing as 569 always for pre-2.5 interpreters (i.e. making sure backwards compatibility 570 doesn't break) while still continuing to work for later interpreters. 571 572 The returned value is True if hex float literals are allowed, False otherwise. 573 """ 574 if map(int, [sys.version_info[0], sys.version_info[1]]) < [2, 5] and not platformWindows(): 575 return True 576 return False
577