Debian Codegraph @

src/CedarBackup3/testutil.py

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