Coverage for certbot/tests/util.py : 95%

Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
"""Test utilities.
.. warning:: This module is not part of the public API.
"""
"""Path to a test vector.""" __name__, os.path.join('testdata', *names))
"""Load contents of a test vector.""" # luckily, resource_string opens file in binary mode __name__, os.path.join('testdata', *names)) # Try at most to convert CRLF to LF when data is text # Failed to process the file with standard encoding. # Most likely not a text file, return its bytes untouched.
elif ext.lower() == '.der': return loader_der else: # pragma: no cover raise ValueError("Loader could not be recognized based on extension")
"""Load certificate.""" names[-1], OpenSSL.crypto.FILETYPE_PEM, OpenSSL.crypto.FILETYPE_ASN1)
"""Load certificate request.""" loader = _guess_loader( names[-1], OpenSSL.crypto.FILETYPE_PEM, OpenSSL.crypto.FILETYPE_ASN1) return OpenSSL.crypto.load_certificate_request(loader, load_vector(*names))
"""Load ComparableX509 certificate request.""" return jose.ComparableX509(load_csr(*names))
"""Load RSA private key.""" serialization.load_der_private_key) load_vector(*names), password=None, backend=default_backend()))
"""Load pyOpenSSL private key.""" names[-1], OpenSSL.crypto.FILETYPE_PEM, OpenSSL.crypto.FILETYPE_ASN1)
def skip_unless(condition, reason): # pragma: no cover """Skip tests unless a condition holds.
This implements the basic functionality of unittest.skipUnless which is only available on Python 2.7+.
:param bool condition: If ``False``, the test will be skipped :param str reason: the reason for skipping the test
:rtype: callable :returns: decorator that hides tests unless condition is ``True``
""" if hasattr(unittest, "skipUnless"): return unittest.skipUnless(condition, reason) elif condition: return lambda cls: cls else: return lambda cls: None
"""Creates a lineage defined by testfile.
This creates the archive, live, and renewal directories if necessary and creates a simple lineage.
:param str config_dir: path to the configuration directory :param str testfile: configuration file to base the lineage on
:returns: path to the renewal conf file for the created lineage :rtype: str
"""
config_dir, constants.RENEWAL_CONFIGS_DIR) config_dir, constants.ARCHIVE_DIR, lineage_name) config_dir, constants.LIVE_DIR, lineage_name)
os.path.join(archive_dir, kind))
os.path.join(live_dir, '{0}.pem'.format(kind)))
line.replace('MAGICDIR', config_dir) for line in src)
"""Patch zope.component.getUtility to use a special mock IDisplay.
The mock IDisplay works like a regular mock object, except it also also asserts that methods are called with valid arguments.
:param str target: path to patch
:returns: mock zope.component.getUtility :rtype: mock.MagicMock
"""
stdout=None): """Patch zope.component.getUtility to use a special mock IDisplay.
The mock IDisplay works like a regular mock object, except it also also asserts that methods are called with valid arguments.
The `message` argument passed to the IDisplay methods is passed to stdout's write method.
:param str target: path to patch :param object stdout: object to write standard output to; it is expected to have a `write` method
:returns: mock zope.component.getUtility :rtype: mock.MagicMock
"""
"""Mock object with the ability to freeze attributes.
This class works like a regular mock.MagicMock object, except attributes and behavior set before the object is frozen cannot be changed during tests.
If a func argument is provided to the constructor, this function is called first when an instance of FreezableMock is called, followed by the usual behavior defined by MagicMock. The return value of func is ignored.
"""
"""Freeze object preventing further changes."""
return getattr(object.__getattribute__(self, '_mock'), name) else:
""" Before it is frozen, attributes are set on the FreezableMock instance and added to the _frozen_set. Attributes in the _frozen_set cannot be changed after the FreezableMock is frozen. In this case, they are set on the underlying _mock.
In cases of return_value and side_effect, these attributes are always passed through to the instance's _mock and added to the _frozen_set before the object is frozen.
""" raise AttributeError('Cannot change frozen attribute ' + name) else:
else:
"""Write to message to stdout. """
""" Mock function for IDisplay methods. """ _assert_valid_call(args, kwargs) _write_msg(*args, **kwargs)
func=_write_msg) else: func=mock_method)
# pylint: disable=star-args
"""Base test class which sets up and tears down a temporary directory"""
"""Execute before test"""
"""Execute after test""" # On Windows we have various files which are not correctly closed at the time of tearDown. # For know, we log them until a proper file close handling is written. # Useful for development only, so no warning when we are on a CI process. """On error handler""" if not os.environ.get('APPVEYOR'): # pragma: no cover message = ('Following error occurred when deleting the tempdir {0}' ' for path {1} during tearDown process: {2}' .format(self.tempdir, path, str(excinfo))) warnings.warn(message)
"""Test class which sets up a NamespaceConfig object.
""" mock.MagicMock(**constants.CLI_DEFAULTS) )
""" Acquire a file lock on given path, then wait to release it. This worker is coordinated using events to signal when the lock should be acquired and released. :param multiprocessing.Event event_in: event object to signal when to release the lock :param multiprocessing.Event event_out: event object to signal when the lock is acquired :param path: the path to lock """ my_lock = lock.lock_dir(path) else: finally:
""" Grab a lock on path_to_lock from a foreign process then execute the callback. :param callable callback: object to call after acquiring the lock :param str path_to_lock: path to file or directory to lock """ # Reload certbot.util module to reset internal _LOCKS dictionary.
# Wait confirmation that lock is acquired # Execute the callback # Trigger unlock from foreign process
# Wait for process termination
"""Decorator to skip permanently a test on Windows. A reason is required.""" """Wrapped version"""
"""Decorator to skip temporarily a broken test on Windows.""" sys.platform == 'win32' and os.environ.get('SKIP_BROKEN_TESTS_ON_WINDOWS', 'true') == 'true', reason)(function)
""" Return the given path joined to the tempdir path for the current platform Eg.: 'cert' => /tmp/cert (Linux) or 'C:\\Users\\currentuser\\AppData\\Temp\\cert' (Windows) """ |