read file as bytes, and factor out the open for testing

This commit is contained in:
Erica Portnoy 2020-03-11 16:45:29 -07:00
parent f8bce99d44
commit ed66b891fa
2 changed files with 18 additions and 8 deletions

View file

@ -237,6 +237,15 @@ class ApacheConfigurator(common.Installer):
"""Full absolute path to digest of updated SSL configuration file."""
return os.path.join(self.config.config_dir, constants.UPDATED_MOD_SSL_CONF_DIGEST)
def _open_module_file(self, ssl_module_location):
"""Extract the open lines of openssl_version for testing purposes"""
try:
with open(ssl_module_location, mode="rb") as f:
contents = f.read()
except IOError as error:
return None
return contents
def openssl_version(self):
"""Lazily retrieve openssl version"""
if self._openssl_version:
@ -251,13 +260,12 @@ class ApacheConfigurator(common.Installer):
logger.warning("Could not find ssl_module; not disabling session tickets.")
return None
# Step 2. Grep in the .so for openssl version
try:
with open(ssl_module_location) as f:
contents = f.read()
except IOError as error:
contents = self._open_module_file(ssl_module_location)
if not contents:
logger.warning("Unable to read ssl_module file; not disabling session tickets.")
return None
# looks like: OpenSSL 1.0.2s 28 May 2019
contents = contents.decode('UTF-8')
matches = re.findall(r"OpenSSL ([0-9]\.[^ ]+) ", contents)
if not matches:
logger.warning("Could not find OpenSSL version; not disabling session tickets.")

View file

@ -1796,8 +1796,9 @@ class InstallSslOptionsConfTest(util.ApacheTest):
OpenSSL 1.0.2g 1 Mar 2016
"""
self.config.parser.modules['ssl_module'] = '/fake/path'
mock_file = mock.mock_open(read_data=some_string_contents)
with mock.patch("certbot_apache._internal.configurator.open", mock_file):
with mock.patch("certbot_apache._internal.configurator."
"ApacheConfigurator._open_module_file") as mock_omf:
mock_omf.return_value = some_string_contents.encode('UTF-8')
self.assertEqual(self.config.openssl_version(), "1.0.2g")
def test_current_version(self):
@ -1827,8 +1828,9 @@ class InstallSslOptionsConfTest(util.ApacheTest):
self.assertTrue("Unable to read" in mock_log.call_args[0][0])
contents_missing_openssl = "these contents won't match the regex"
mock_file = mock.mock_open(read_data=contents_missing_openssl)
with mock.patch("certbot_apache._internal.configurator.open", mock_file):
with mock.patch("certbot_apache._internal.configurator."
"ApacheConfigurator._open_module_file") as mock_omf:
mock_omf.return_value = contents_missing_openssl.encode('UTF-8')
with mock.patch("certbot_apache._internal.configurator.logger.warning") as mock_log:
# Check that correct logger.warning was printed
self.assertEqual(self.config.openssl_version(), None)