certbot/certbot-nginx/tests/test_util.py

131 lines
4.6 KiB
Python
Raw Permalink Normal View History

"""Common utilities for certbot_nginx."""
2016-06-18 17:52:07 -04:00
import copy
2019-04-02 16:48:22 -04:00
import shutil
import tempfile
2015-03-23 13:53:44 -04:00
import josepy as jose
try:
import mock
Deprecate zope.component in favor of an direct calls to functions from `certbot.display.util` module (#8835) * Implement certbot services * Various fixes * Local oldest requirements * Clean imports * Add unit tests for certbot.services * Clean code * Protect against nullity of global services * Fix CLI * Fix tests * Consistent test behavior * Various fixes * Clean code * Remove reporter service, migrate display service in certbot.display.util. * Fix test * Fix apache compatibility test * Fix oldest test * Setup certbot.display.service module * Reintegrate in util * Fix imports * Fix tests and documentation * Refactor * Cleanup * Cleanup * Clean imports * Add unit tests * Borrow sphinx build fix from #8863 * Fix type * Add comment * Do not reuse existing display service, which never exist at that time * Make get_display() private * Fix lint * Make display internal * Fix circular dependencies * Fixing circular dependencies * Rename patch methods and update docstring * Update deprecation messages * Update certbot/certbot/_internal/display/obj.py Co-authored-by: Brad Warren <bmw@users.noreply.github.com> * Update certbot/certbot/tests/util.py Co-authored-by: Brad Warren <bmw@users.noreply.github.com> * Update certbot/certbot/tests/util.py Co-authored-by: Brad Warren <bmw@users.noreply.github.com> * Update certbot/certbot/tests/util.py Co-authored-by: Brad Warren <bmw@users.noreply.github.com> * Update certbot/certbot/tests/util.py Co-authored-by: Brad Warren <bmw@users.noreply.github.com> * Add links * Avoid relying on internal certbot packages from certbot-apache * Keep same behavior for patch_get_utility* * Better diff * Add changelog * Update certbot/certbot/tests/util.py Co-authored-by: Brad Warren <bmw@users.noreply.github.com> Co-authored-by: Brad Warren <bmw@users.noreply.github.com>
2021-07-19 20:09:06 -04:00
except ImportError: # pragma: no cover
from unittest import mock # type: ignore
2019-04-02 16:48:22 -04:00
import pkg_resources
2015-03-23 13:53:44 -04:00
from certbot import util
2019-04-12 16:32:52 -04:00
from certbot.compat import os
from certbot.plugins import common
2019-04-02 16:48:22 -04:00
from certbot.tests import util as test_util
from certbot_nginx._internal import configurator
from certbot_nginx._internal import nginxparser
2015-03-23 13:53:44 -04:00
class NginxTest(test_util.ConfigTestCase):
2015-03-23 13:53:44 -04:00
def setUp(self):
super().setUp()
2015-03-23 13:53:44 -04:00
self.configuration = self.config
self.config = None
self.temp_dir, self.config_dir, self.work_dir = common.dir_setup(
"etc_nginx", __name__)
self.logs_dir = tempfile.mkdtemp('logs')
2015-03-23 13:53:44 -04:00
self.config_path = os.path.join(self.temp_dir, "etc_nginx")
2015-03-23 13:53:44 -04:00
2015-08-05 18:39:31 -04:00
self.rsa512jwk = jose.JWKRSA.load(test_util.load_vector(
"rsa512_key.pem"))
def tearDown(self):
# Cleanup opened resources after a test. This is usually done through atexit handlers in
# Certbot, but during tests, atexit will not run registered functions before tearDown is
# called and instead will run them right before the entire test process exits.
# It is a problem on Windows, that does not accept to clean resources before closing them.
util._release_locks() # pylint: disable=protected-access
shutil.rmtree(self.temp_dir)
shutil.rmtree(self.config_dir)
shutil.rmtree(self.work_dir)
shutil.rmtree(self.logs_dir)
def get_nginx_configurator(self, config_path, config_dir, work_dir, logs_dir,
version=(1, 6, 2), openssl_version="1.0.2g"):
"""Create an Nginx Configurator with the specified options."""
backups = os.path.join(work_dir, "backups")
self.configuration.nginx_server_root = config_path
self.configuration.nginx_sleep_seconds = 0.1234
self.configuration.le_vhost_ext = "-le-ssl.conf"
self.configuration.config_dir = config_dir
self.configuration.work_dir = work_dir
self.configuration.logs_dir = logs_dir
self.configuration.backup_dir = backups
self.configuration.temp_checkpoint_dir = os.path.join(work_dir, "temp_checkpoints")
self.configuration.in_progress_dir = os.path.join(backups, "IN_PROGRESS")
self.configuration.server = "https://acme-server.org:443/new"
self.configuration.http01_port = 80
self.configuration.https_port = 5001
with mock.patch("certbot_nginx._internal.configurator.NginxConfigurator."
"config_test"):
with mock.patch("certbot_nginx._internal.configurator.util."
"exe_exists") as mock_exe_exists:
mock_exe_exists.return_value = True
config = configurator.NginxConfigurator(
self.configuration,
name="nginx",
version=version,
openssl_version=openssl_version)
config.prepare()
return config
def get_data_filename(filename):
2015-04-17 20:05:00 -04:00
"""Gets the filename of a test data file."""
return pkg_resources.resource_filename(
__name__, os.path.join(
"testdata", "etc_nginx", filename))
2015-03-23 13:53:44 -04:00
def filter_comments(tree):
"""Filter comment nodes from parsed configurations."""
def traverse(tree):
"""Generator dropping comment nodes"""
2016-06-18 17:52:07 -04:00
for entry in tree:
2016-07-14 21:15:01 -04:00
# key, values = entry
spaceless = [e for e in entry if not nginxparser.spacey(e)]
if spaceless:
key = spaceless[0]
values = spaceless[1] if len(spaceless) > 1 else None
else:
key = values = ""
if isinstance(key, list):
2016-06-18 17:52:07 -04:00
new = copy.deepcopy(entry)
new[1] = filter_comments(values)
yield new
else:
2016-07-14 21:15:01 -04:00
if key != '#' and spaceless:
yield spaceless
return list(traverse(tree))
2015-10-11 14:28:39 -04:00
def contains_at_depth(haystack, needle, n):
2015-10-11 14:28:39 -04:00
"""Is the needle in haystack at depth n?
Return true if the needle is present in one of the sub-iterables in haystack
at depth n. Haystack must be an iterable.
"""
2015-10-11 15:19:39 -04:00
# Specifically use hasattr rather than isinstance(..., collections.Iterable)
# because we want to include lists but reject strings.
if not hasattr(haystack, '__iter__') or hasattr(haystack, 'strip'):
return False
if n == 0:
return needle in haystack
for item in haystack:
if contains_at_depth(item, needle, n - 1):
return True
return False