Mass rename of certbot_nginx paths

This commit is contained in:
Will Greenberg
2026-03-17 17:58:52 -07:00
parent 1126ba0e88
commit 3e05ce27b2
12 changed files with 147 additions and 147 deletions
@@ -25,12 +25,12 @@ from certbot import util
from certbot.compat import os from certbot.compat import os
from certbot.display import util as display_util from certbot.display import util as display_util
from certbot.plugins import common from certbot.plugins import common
from certbot_nginx._internal import constants from certbot._internal.nginx import constants
from certbot_nginx._internal import display_ops from certbot._internal.nginx import display_ops
from certbot_nginx._internal import http_01 from certbot._internal.nginx import http_01
from certbot_nginx._internal import nginxparser from certbot._internal.nginx import nginxparser
from certbot_nginx._internal import obj from certbot._internal.nginx import obj
from certbot_nginx._internal import parser from certbot._internal.nginx import parser
NAME_RANK = 0 NAME_RANK = 0
START_WILDCARD_RANK = 1 START_WILDCARD_RANK = 1
@@ -52,7 +52,7 @@ class NginxConfigurator(common.Configurator):
:type config: certbot.configuration.NamespaceConfig :type config: certbot.configuration.NamespaceConfig
:ivar parser: Handles low level parsing :ivar parser: Handles low level parsing
:type parser: :class:`~certbot_nginx._internal.parser` :type parser: :class:`~certbot._internal.nginx.parser`
:ivar str save_notes: Human-readable config change notes :ivar str save_notes: Human-readable config change notes
@@ -173,8 +173,8 @@ class NginxConfigurator(common.Configurator):
file_manager = ExitStack() file_manager = ExitStack()
atexit.register(file_manager.close) atexit.register(file_manager.close)
ref = (importlib.resources.files("certbot_nginx").joinpath("_internal") ref = (importlib.resources.files("certbot").joinpath("_internal")
.joinpath("tls_configs").joinpath(config_filename)) .joinpath("nginx").joinpath("tls_configs").joinpath(config_filename))
return str(file_manager.enter_context(importlib.resources.as_file(ref))) return str(file_manager.enter_context(importlib.resources.as_file(ref)))
@@ -348,7 +348,7 @@ class NginxConfigurator(common.Configurator):
:param str target_name: domain name :param str target_name: domain name
:returns: ssl vhosts associated with name :returns: ssl vhosts associated with name
:rtype: list of :class:`~certbot_nginx._internal.obj.VirtualHost` :rtype: list of :class:`~certbot._internal.nginx.obj.VirtualHost`
""" """
return [vhost for vhost in self._choose_vhosts_common(target_name) if vhost.ssl] return [vhost for vhost in self._choose_vhosts_common(target_name) if vhost.ssl]
@@ -369,7 +369,7 @@ class NginxConfigurator(common.Configurator):
:param str fullchain_path: certificates to use when creating SSL vhosts :param str fullchain_path: certificates to use when creating SSL vhosts
:returns: ssl vhosts associated with name :returns: ssl vhosts associated with name
:rtype: list of :class:`~certbot_nginx._internal.obj.VirtualHost` :rtype: list of :class:`~certbot._internal.nginx.obj.VirtualHost`
""" """
vhosts = self._choose_vhosts_common(target_name) vhosts = self._choose_vhosts_common(target_name)
@@ -478,7 +478,7 @@ class NginxConfigurator(common.Configurator):
:param list matches: list of dicts containing the vhost, the matching name, :param list matches: list of dicts containing the vhost, the matching name,
and the numerical rank and the numerical rank
:returns: the most matching vhost :returns: the most matching vhost
:rtype: :class:`~certbot_nginx._internal.obj.VirtualHost` :rtype: :class:`~certbot._internal.nginx.obj.VirtualHost`
""" """
if not matches: if not matches:
@@ -564,7 +564,7 @@ class NginxConfigurator(common.Configurator):
:param str port: port number :param str port: port number
:returns: vhosts associated with name :returns: vhosts associated with name
:rtype: list of :class:`~certbot_nginx._internal.obj.VirtualHost` :rtype: list of :class:`~certbot._internal.nginx.obj.VirtualHost`
""" """
if util.is_wildcard_domain(target_name): if util.is_wildcard_domain(target_name):
@@ -586,7 +586,7 @@ class NginxConfigurator(common.Configurator):
:param str target_name: non-wildcard domain name :param str target_name: non-wildcard domain name
:returns: tuple of HTTP and HTTPS virtualhosts :returns: tuple of HTTP and HTTPS virtualhosts
:rtype: tuple of :class:`~certbot_nginx._internal.obj.VirtualHost` :rtype: tuple of :class:`~certbot._internal.nginx.obj.VirtualHost`
""" """
vhosts = [m['vhost'] for m in self._get_ranked_matches(target_name) if m and 'vhost' in m] vhosts = [m['vhost'] for m in self._get_ranked_matches(target_name) if m and 'vhost' in m]
@@ -712,7 +712,7 @@ class NginxConfigurator(common.Configurator):
Make a server SSL by adding new listen and SSL directives. Make a server SSL by adding new listen and SSL directives.
:param vhost: The vhost to add SSL to. :param vhost: The vhost to add SSL to.
:type vhost: :class:`~certbot_nginx._internal.obj.VirtualHost` :type vhost: :class:`~certbot._internal.nginx.obj.VirtualHost`
:param str key_path: key to use for SSL :param str key_path: key to use for SSL
:param str fullchain_path: certificates to use for SSL :param str fullchain_path: certificates to use for SSL
@@ -868,9 +868,9 @@ class NginxConfigurator(common.Configurator):
:param vhost: The server block to break up into two. :param vhost: The server block to break up into two.
:param list only_directives: If this exists, only duplicate these directives :param list only_directives: If this exists, only duplicate these directives
when splitting the block. when splitting the block.
:type vhost: :class:`~certbot_nginx._internal.obj.VirtualHost` :type vhost: :class:`~certbot._internal.nginx.obj.VirtualHost`
:returns: tuple (http_vhost, https_vhost) :returns: tuple (http_vhost, https_vhost)
:rtype: tuple of type :class:`~certbot_nginx._internal.obj.VirtualHost` :rtype: tuple of type :class:`~certbot._internal.nginx.obj.VirtualHost`
""" """
http_vhost = self.parser.duplicate_vhost(vhost, only_directives=only_directives) http_vhost = self.parser.duplicate_vhost(vhost, only_directives=only_directives)
@@ -4,7 +4,7 @@ from typing import Iterable
from typing import Optional from typing import Optional
from certbot.display import util as display_util from certbot.display import util as display_util
from certbot_nginx._internal.obj import VirtualHost from certbot._internal.nginx.obj import VirtualHost
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@@ -11,11 +11,11 @@ from certbot import errors
from certbot.achallenges import KeyAuthorizationAnnotatedChallenge from certbot.achallenges import KeyAuthorizationAnnotatedChallenge
from certbot.compat import os from certbot.compat import os
from certbot.plugins import common from certbot.plugins import common
from certbot_nginx._internal import nginxparser from certbot._internal.nginx import nginxparser
from certbot_nginx._internal.obj import Addr from certbot._internal.nginx.obj import Addr
if TYPE_CHECKING: if TYPE_CHECKING:
from certbot_nginx._internal.configurator import NginxConfigurator from certbot._internal.nginx.configurator import NginxConfigurator
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@@ -146,7 +146,7 @@ class NginxHttp01(common.ChallengePerformer):
def _default_listen_addresses(self) -> list[Addr]: def _default_listen_addresses(self) -> list[Addr]:
"""Finds addresses for a challenge block to listen on. """Finds addresses for a challenge block to listen on.
:returns: list of :class:`certbot_nginx._internal.obj.Addr` to apply :returns: list of :class:`certbot._internal.nginx.obj.Addr` to apply
:rtype: list :rtype: list
""" """
addresses: list[Addr] = [] addresses: list[Addr] = []
+10 -10
View File
@@ -18,9 +18,9 @@ import pyparsing
from certbot import errors from certbot import errors
from certbot.compat import os from certbot.compat import os
from certbot_nginx._internal import nginxparser from certbot._internal.nginx import nginxparser
from certbot_nginx._internal import obj from certbot._internal.nginx import obj
from certbot_nginx._internal.nginxparser import UnspacedList from certbot._internal.nginx.nginxparser import UnspacedList
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@@ -145,7 +145,7 @@ class NginxParser:
Technically this is a misnomer because Nginx does not have virtual Technically this is a misnomer because Nginx does not have virtual
hosts, it has 'server blocks'. hosts, it has 'server blocks'.
:returns: List of :class:`~certbot_nginx._internal.obj.VirtualHost` :returns: List of :class:`~certbot._internal.nginx.obj.VirtualHost`
objects found in configuration objects found in configuration
:rtype: list :rtype: list
@@ -286,7 +286,7 @@ class NginxParser:
def has_ssl_on_directive(self, vhost: obj.VirtualHost) -> bool: def has_ssl_on_directive(self, vhost: obj.VirtualHost) -> bool:
"""Does vhost have ssl on for all ports? """Does vhost have ssl on for all ports?
:param :class:`~certbot_nginx._internal.obj.VirtualHost` vhost: The vhost in question :param :class:`~certbot._internal.nginx.obj.VirtualHost` vhost: The vhost in question
:returns: True if 'ssl on' directive is included :returns: True if 'ssl on' directive is included
:rtype: bool :rtype: bool
@@ -313,7 +313,7 @@ class NginxParser:
..todo :: Doesn't match server blocks whose server_name directives are ..todo :: Doesn't match server blocks whose server_name directives are
split across multiple conf files. split across multiple conf files.
:param :class:`~certbot_nginx._internal.obj.VirtualHost` vhost: The vhost :param :class:`~certbot._internal.nginx.obj.VirtualHost` vhost: The vhost
whose information we use to match on whose information we use to match on
:param list directives: The directives to add :param list directives: The directives to add
:param bool insert_at_top: True if the directives need to be inserted at the top :param bool insert_at_top: True if the directives need to be inserted at the top
@@ -336,7 +336,7 @@ class NginxParser:
..todo :: Doesn't match server blocks whose server_name directives are ..todo :: Doesn't match server blocks whose server_name directives are
split across multiple conf files. split across multiple conf files.
:param :class:`~certbot_nginx._internal.obj.VirtualHost` vhost: The vhost :param :class:`~certbot._internal.nginx.obj.VirtualHost` vhost: The vhost
whose information we use to match on whose information we use to match on
:param list directives: The directives to add :param list directives: The directives to add
:param bool insert_at_top: True if the directives need to be inserted at the top :param bool insert_at_top: True if the directives need to be inserted at the top
@@ -350,7 +350,7 @@ class NginxParser:
match_func: Optional[Callable[[Any], bool]] = None) -> None: match_func: Optional[Callable[[Any], bool]] = None) -> None:
"""Remove all directives of type directive_name. """Remove all directives of type directive_name.
:param :class:`~certbot_nginx._internal.obj.VirtualHost` vhost: The vhost :param :class:`~certbot._internal.nginx.obj.VirtualHost` vhost: The vhost
to remove directives from to remove directives from
:param string directive_name: The directive type to remove :param string directive_name: The directive type to remove
:param callable match_func: Function of the directive that returns true for directives :param callable match_func: Function of the directive that returns true for directives
@@ -389,7 +389,7 @@ class NginxParser:
only_directives: Optional[list[Any]] = None) -> obj.VirtualHost: only_directives: Optional[list[Any]] = None) -> obj.VirtualHost:
"""Duplicate the vhost in the configuration files. """Duplicate the vhost in the configuration files.
:param :class:`~certbot_nginx._internal.obj.VirtualHost` vhost_template: The vhost :param :class:`~certbot._internal.nginx.obj.VirtualHost` vhost_template: The vhost
whose information we copy whose information we copy
:param bool remove_singleton_listen_params: If we should remove parameters :param bool remove_singleton_listen_params: If we should remove parameters
from listen directives in the block that can only be used once per address from listen directives in the block that can only be used once per address
@@ -397,7 +397,7 @@ class NginxParser:
looks at first level of depth; does not expand includes. looks at first level of depth; does not expand includes.
:returns: A vhost object for the newly created vhost :returns: A vhost object for the newly created vhost
:rtype: :class:`~certbot_nginx._internal.obj.VirtualHost` :rtype: :class:`~certbot._internal.nginx.obj.VirtualHost`
""" """
# TODO: https://github.com/certbot/certbot/issues/5185 # TODO: https://github.com/certbot/certbot/issues/5185
# put it in the same file as the template, at the same level # put it in the same file as the template, at the same level
@@ -1,4 +1,4 @@
"""Test for certbot_nginx._internal.configurator.""" """Test for certbot._internal.nginx.configurator."""
import sys import sys
from unittest import mock from unittest import mock
@@ -11,11 +11,11 @@ from certbot import crypto_util
from certbot import errors from certbot import errors
from certbot.compat import os from certbot.compat import os
from certbot.tests import util as certbot_test_util from certbot.tests import util as certbot_test_util
from certbot_nginx._internal import obj from certbot._internal.nginx import obj
from certbot_nginx._internal import parser from certbot._internal.nginx import parser
from certbot_nginx._internal.configurator import _redirect_block_for_domain from certbot._internal.nginx.configurator import _redirect_block_for_domain
from certbot_nginx._internal.nginxparser import UnspacedList from certbot._internal.nginx.nginxparser import UnspacedList
from certbot_nginx._internal.tests import test_util as util from certbot._internal.nginx.tests import test_util as util
class NginxConfiguratorTest(util.NginxTest): class NginxConfiguratorTest(util.NginxTest):
@@ -27,11 +27,11 @@ class NginxConfiguratorTest(util.NginxTest):
self.config = self.get_nginx_configurator( self.config = self.get_nginx_configurator(
self.config_path, self.config_dir, self.work_dir, self.logs_dir) self.config_path, self.config_dir, self.work_dir, self.logs_dir)
patch = mock.patch('certbot_nginx._internal.configurator.display_util.notify') patch = mock.patch('certbot._internal.nginx.configurator.display_util.notify')
self.mock_notify = patch.start() self.mock_notify = patch.start()
self.addCleanup(patch.stop) self.addCleanup(patch.stop)
@mock.patch("certbot_nginx._internal.configurator.util.exe_exists") @mock.patch("certbot._internal.nginx.configurator.util.exe_exists")
def test_prepare_no_install(self, mock_exe_exists): def test_prepare_no_install(self, mock_exe_exists):
mock_exe_exists.return_value = False mock_exe_exists.return_value = False
with pytest.raises(errors.NoInstallationError): with pytest.raises(errors.NoInstallationError):
@@ -41,8 +41,8 @@ class NginxConfiguratorTest(util.NginxTest):
assert (1, 6, 2) == self.config.version assert (1, 6, 2) == self.config.version
assert 16 == len(self.config.parser.parsed) assert 16 == len(self.config.parser.parsed)
@mock.patch("certbot_nginx._internal.configurator.util.exe_exists") @mock.patch("certbot._internal.nginx.configurator.util.exe_exists")
@mock.patch("certbot_nginx._internal.configurator.subprocess.run") @mock.patch("certbot._internal.nginx.configurator.subprocess.run")
def test_prepare_initializes_version(self, mock_run, mock_exe_exists): def test_prepare_initializes_version(self, mock_run, mock_exe_exists):
mock_run.return_value.stdout = "" mock_run.return_value.stdout = ""
mock_run.return_value.stderr = "\n".join( mock_run.return_value.stderr = "\n".join(
@@ -76,7 +76,7 @@ class NginxConfiguratorTest(util.NginxTest):
self.config.config_test = mock.Mock() self.config.config_test = mock.Mock()
certbot_test_util.lock_and_call(self._test_prepare_locked, server_root) certbot_test_util.lock_and_call(self._test_prepare_locked, server_root)
@mock.patch("certbot_nginx._internal.configurator.util.exe_exists") @mock.patch("certbot._internal.nginx.configurator.util.exe_exists")
def _test_prepare_locked(self, unused_exe_exists): def _test_prepare_locked(self, unused_exe_exists):
try: try:
self.config.prepare() self.config.prepare()
@@ -87,8 +87,8 @@ class NginxConfiguratorTest(util.NginxTest):
else: # pragma: no cover else: # pragma: no cover
self.fail("Exception wasn't raised!") self.fail("Exception wasn't raised!")
@mock.patch("certbot_nginx._internal.configurator.socket.gethostname") @mock.patch("certbot._internal.nginx.configurator.socket.gethostname")
@mock.patch("certbot_nginx._internal.configurator.socket.gethostbyaddr") @mock.patch("certbot._internal.nginx.configurator.socket.gethostbyaddr")
def test_get_all_names(self, mock_gethostbyaddr, mock_gethostname): def test_get_all_names(self, mock_gethostbyaddr, mock_gethostname):
mock_gethostbyaddr.return_value = ('155.225.50.69.nephoscale.net', [], []) mock_gethostbyaddr.return_value = ('155.225.50.69.nephoscale.net', [], [])
mock_gethostname.return_value = ('example.net') mock_gethostname.return_value = ('example.net')
@@ -268,7 +268,7 @@ class NginxConfiguratorTest(util.NginxTest):
"example/chain.pem", "example/chain.pem",
None) None)
@mock.patch('certbot_nginx._internal.parser.NginxParser.update_or_add_server_directives') @mock.patch('certbot._internal.nginx.parser.NginxParser.update_or_add_server_directives')
def test_deploy_cert_raise_on_add_error(self, mock_update_or_add_server_directives): def test_deploy_cert_raise_on_add_error(self, mock_update_or_add_server_directives):
mock_update_or_add_server_directives.side_effect = errors.MisconfigurationError() mock_update_or_add_server_directives.side_effect = errors.MisconfigurationError()
with pytest.raises(errors.PluginError): with pytest.raises(errors.PluginError):
@@ -364,9 +364,9 @@ class NginxConfiguratorTest(util.NginxTest):
]] == \ ]] == \
parsed_migration_conf[0] parsed_migration_conf[0]
@mock.patch("certbot_nginx._internal.configurator.http_01.NginxHttp01.perform") @mock.patch("certbot._internal.nginx.configurator.http_01.NginxHttp01.perform")
@mock.patch("certbot_nginx._internal.configurator.NginxConfigurator.restart") @mock.patch("certbot._internal.nginx.configurator.NginxConfigurator.restart")
@mock.patch("certbot_nginx._internal.configurator.NginxConfigurator.revert_challenge_config") @mock.patch("certbot._internal.nginx.configurator.NginxConfigurator.revert_challenge_config")
def test_perform_and_cleanup(self, mock_revert, mock_restart, mock_http_perform): def test_perform_and_cleanup(self, mock_revert, mock_restart, mock_http_perform):
# Only tests functionality specific to configurator.perform # Only tests functionality specific to configurator.perform
# Note: As more challenges are offered this will have to be expanded # Note: As more challenges are offered this will have to be expanded
@@ -394,7 +394,7 @@ class NginxConfiguratorTest(util.NginxTest):
assert mock_revert.call_count == 1 assert mock_revert.call_count == 1
assert mock_restart.call_count == 2 assert mock_restart.call_count == 2
@mock.patch("certbot_nginx._internal.configurator.subprocess.run") @mock.patch("certbot._internal.nginx.configurator.subprocess.run")
def test_get_version(self, mock_run): def test_get_version(self, mock_run):
mock_run.return_value.stdout = "" mock_run.return_value.stdout = ""
mock_run.return_value.stderr = "\n".join( mock_run.return_value.stderr = "\n".join(
@@ -455,7 +455,7 @@ class NginxConfiguratorTest(util.NginxTest):
with pytest.raises(errors.PluginError): with pytest.raises(errors.PluginError):
self.config.get_version() self.config.get_version()
@mock.patch("certbot_nginx._internal.configurator.subprocess.run") @mock.patch("certbot._internal.nginx.configurator.subprocess.run")
def test_get_openssl_version(self, mock_run): def test_get_openssl_version(self, mock_run):
# pylint: disable=protected-access # pylint: disable=protected-access
mock_run.return_value.stdout = "" mock_run.return_value.stdout = ""
@@ -517,8 +517,8 @@ class NginxConfiguratorTest(util.NginxTest):
""" """
assert self.config._get_openssl_version() == "" assert self.config._get_openssl_version() == ""
@mock.patch("certbot_nginx._internal.configurator.subprocess.run") @mock.patch("certbot._internal.nginx.configurator.subprocess.run")
@mock.patch("certbot_nginx._internal.configurator.time") @mock.patch("certbot._internal.nginx.configurator.time")
def test_nginx_restart(self, mock_time, mock_run): def test_nginx_restart(self, mock_time, mock_run):
mocked = mock_run.return_value mocked = mock_run.return_value
mocked.stdout = '' mocked.stdout = ''
@@ -528,8 +528,8 @@ class NginxConfiguratorTest(util.NginxTest):
assert mock_run.call_count == 1 assert mock_run.call_count == 1
mock_time.sleep.assert_called_once_with(0.1234) mock_time.sleep.assert_called_once_with(0.1234)
@mock.patch("certbot_nginx._internal.configurator.subprocess.run") @mock.patch("certbot._internal.nginx.configurator.subprocess.run")
@mock.patch("certbot_nginx._internal.configurator.logger.debug") @mock.patch("certbot._internal.nginx.configurator.logger.debug")
def test_nginx_restart_fail(self, mock_log_debug, mock_run): def test_nginx_restart_fail(self, mock_log_debug, mock_run):
mocked = mock_run.return_value mocked = mock_run.return_value
mocked.stdout = '' mocked.stdout = ''
@@ -540,7 +540,7 @@ class NginxConfiguratorTest(util.NginxTest):
assert mock_run.call_count == 2 assert mock_run.call_count == 2
mock_log_debug.assert_called_once_with("nginx reload failed:\n%s", "") mock_log_debug.assert_called_once_with("nginx reload failed:\n%s", "")
@mock.patch("certbot_nginx._internal.configurator.subprocess.run") @mock.patch("certbot._internal.nginx.configurator.subprocess.run")
def test_no_nginx_start(self, mock_run): def test_no_nginx_start(self, mock_run):
mock_run.side_effect = OSError("Can't find program") mock_run.side_effect = OSError("Can't find program")
with pytest.raises(errors.MisconfigurationError): with pytest.raises(errors.MisconfigurationError):
@@ -687,20 +687,20 @@ class NginxConfiguratorTest(util.NginxTest):
self.config.enhance("migration.com", self.config.enhance("migration.com",
"ensure-http-header", "Strict-Transport-Security") "ensure-http-header", "Strict-Transport-Security")
@mock.patch('certbot_nginx._internal.obj.VirtualHost.contains_list') @mock.patch('certbot._internal.nginx.obj.VirtualHost.contains_list')
def test_certbot_redirect_exists(self, mock_contains_list): def test_certbot_redirect_exists(self, mock_contains_list):
# Test that we add no redirect statement if there is already a # Test that we add no redirect statement if there is already a
# redirect in the block that is managed by certbot # redirect in the block that is managed by certbot
# Has a certbot redirect # Has a certbot redirect
mock_contains_list.return_value = True mock_contains_list.return_value = True
with mock.patch("certbot_nginx._internal.configurator.logger") as mock_logger: with mock.patch("certbot._internal.nginx.configurator.logger") as mock_logger:
self.config.enhance("www.example.com", "redirect") self.config.enhance("www.example.com", "redirect")
assert mock_logger.info.call_args[0][0] == \ assert mock_logger.info.call_args[0][0] == \
"Traffic on port %s already redirecting to ssl in %s" "Traffic on port %s already redirecting to ssl in %s"
def test_redirect_dont_enhance(self): def test_redirect_dont_enhance(self):
# Test that we don't accidentally add redirect to ssl-only block # Test that we don't accidentally add redirect to ssl-only block
with mock.patch("certbot_nginx._internal.configurator.logger") as mock_logger: with mock.patch("certbot._internal.nginx.configurator.logger") as mock_logger:
self.config.enhance("geese.com", "redirect") self.config.enhance("geese.com", "redirect")
assert mock_logger.info.call_args[0][0] == \ assert mock_logger.info.call_args[0][0] == \
'No matching insecure server blocks listening on port %s found.' 'No matching insecure server blocks listening on port %s found.'
@@ -895,7 +895,7 @@ class NginxConfiguratorTest(util.NginxTest):
assert util.contains_at_depth(generated_conf, expected, 2) assert util.contains_at_depth(generated_conf, expected, 2)
@mock.patch('certbot.reverter.logger') @mock.patch('certbot.reverter.logger')
@mock.patch('certbot_nginx._internal.parser.NginxParser.load') @mock.patch('certbot._internal.nginx.parser.NginxParser.load')
def test_parser_reload_after_config_changes(self, mock_parser_load, unused_mock_logger): def test_parser_reload_after_config_changes(self, mock_parser_load, unused_mock_logger):
self.config.recovery_routine() self.config.recovery_routine()
self.config.revert_challenge_config() self.config.revert_challenge_config()
@@ -904,7 +904,7 @@ class NginxConfiguratorTest(util.NginxTest):
def test_choose_vhosts_wildcard(self): def test_choose_vhosts_wildcard(self):
# pylint: disable=protected-access # pylint: disable=protected-access
mock_path = "certbot_nginx._internal.display_ops.select_vhost_multiple" mock_path = "certbot._internal.nginx.display_ops.select_vhost_multiple"
with mock.patch(mock_path) as mock_select_vhs: with mock.patch(mock_path) as mock_select_vhs:
vhost = [x for x in self.config.parser.get_vhosts() vhost = [x for x in self.config.parser.get_vhosts()
if 'summer.com' in x.names][0] if 'summer.com' in x.names][0]
@@ -920,7 +920,7 @@ class NginxConfiguratorTest(util.NginxTest):
def test_choose_vhosts_wildcard_redirect(self): def test_choose_vhosts_wildcard_redirect(self):
# pylint: disable=protected-access # pylint: disable=protected-access
mock_path = "certbot_nginx._internal.display_ops.select_vhost_multiple" mock_path = "certbot._internal.nginx.display_ops.select_vhost_multiple"
with mock.patch(mock_path) as mock_select_vhs: with mock.patch(mock_path) as mock_select_vhs:
vhost = [x for x in self.config.parser.get_vhosts() vhost = [x for x in self.config.parser.get_vhosts()
if 'summer.com' in x.names][0] if 'summer.com' in x.names][0]
@@ -941,7 +941,7 @@ class NginxConfiguratorTest(util.NginxTest):
if 'geese.com' in x.names][0] if 'geese.com' in x.names][0]
mock_choose_vhosts.return_value = [vhost] mock_choose_vhosts.return_value = [vhost]
self.config._choose_vhosts_wildcard = mock_choose_vhosts self.config._choose_vhosts_wildcard = mock_choose_vhosts
mock_d = "certbot_nginx._internal.configurator.NginxConfigurator._deploy_cert" mock_d = "certbot._internal.nginx.configurator.NginxConfigurator._deploy_cert"
with mock.patch(mock_d) as mock_dep: with mock.patch(mock_d) as mock_dep:
self.config.deploy_cert("*.com", "/tmp/path", self.config.deploy_cert("*.com", "/tmp/path",
"/tmp/path", "/tmp/path", "/tmp/path") "/tmp/path", "/tmp/path", "/tmp/path")
@@ -949,7 +949,7 @@ class NginxConfiguratorTest(util.NginxTest):
assert len(mock_dep.call_args_list) == 1 assert len(mock_dep.call_args_list) == 1
assert vhost == mock_dep.call_args_list[0][0][0] assert vhost == mock_dep.call_args_list[0][0][0]
@mock.patch("certbot_nginx._internal.display_ops.select_vhost_multiple") @mock.patch("certbot._internal.nginx.display_ops.select_vhost_multiple")
def test_deploy_cert_wildcard_no_vhosts(self, mock_dialog): def test_deploy_cert_wildcard_no_vhosts(self, mock_dialog):
# pylint: disable=protected-access # pylint: disable=protected-access
mock_dialog.return_value = [] mock_dialog.return_value = []
@@ -957,7 +957,7 @@ class NginxConfiguratorTest(util.NginxTest):
self.config.deploy_cert("*.wild.cat", "/tmp/path", "/tmp/path", self.config.deploy_cert("*.wild.cat", "/tmp/path", "/tmp/path",
"/tmp/path", "/tmp/path") "/tmp/path", "/tmp/path")
@mock.patch("certbot_nginx._internal.display_ops.select_vhost_multiple") @mock.patch("certbot._internal.nginx.display_ops.select_vhost_multiple")
def test_enhance_wildcard_ocsp_after_install(self, mock_dialog): def test_enhance_wildcard_ocsp_after_install(self, mock_dialog):
# pylint: disable=protected-access # pylint: disable=protected-access
vhost = [x for x in self.config.parser.get_vhosts() vhost = [x for x in self.config.parser.get_vhosts()
@@ -966,7 +966,7 @@ class NginxConfiguratorTest(util.NginxTest):
self.config.enhance("*.com", "staple-ocsp", "example/chain.pem") self.config.enhance("*.com", "staple-ocsp", "example/chain.pem")
assert not mock_dialog.called assert not mock_dialog.called
@mock.patch("certbot_nginx._internal.display_ops.select_vhost_multiple") @mock.patch("certbot._internal.nginx.display_ops.select_vhost_multiple")
def test_enhance_wildcard_redirect_or_ocsp_no_install(self, mock_dialog): def test_enhance_wildcard_redirect_or_ocsp_no_install(self, mock_dialog):
# we need to select an SSL enabled vhost here for the OCSP stapling # we need to select an SSL enabled vhost here for the OCSP stapling
# enhancement # enhancement
@@ -976,7 +976,7 @@ class NginxConfiguratorTest(util.NginxTest):
self.config.enhance("*.com", "staple-ocsp", "example/chain.pem") self.config.enhance("*.com", "staple-ocsp", "example/chain.pem")
assert mock_dialog.called is True assert mock_dialog.called is True
@mock.patch("certbot_nginx._internal.display_ops.select_vhost_multiple") @mock.patch("certbot._internal.nginx.display_ops.select_vhost_multiple")
def test_enhance_wildcard_double_redirect(self, mock_dialog): def test_enhance_wildcard_double_redirect(self, mock_dialog):
# pylint: disable=protected-access # pylint: disable=protected-access
vhost = [x for x in self.config.parser.get_vhosts() vhost = [x for x in self.config.parser.get_vhosts()
@@ -987,7 +987,7 @@ class NginxConfiguratorTest(util.NginxTest):
def test_choose_vhosts_wildcard_no_ssl_filter_port(self): def test_choose_vhosts_wildcard_no_ssl_filter_port(self):
# pylint: disable=protected-access # pylint: disable=protected-access
mock_path = "certbot_nginx._internal.display_ops.select_vhost_multiple" mock_path = "certbot._internal.nginx.display_ops.select_vhost_multiple"
with mock.patch(mock_path) as mock_select_vhs: with mock.patch(mock_path) as mock_select_vhs:
mock_select_vhs.return_value = [] mock_select_vhs.return_value = []
self.config._choose_vhosts_wildcard("*.com", self.config._choose_vhosts_wildcard("*.com",
@@ -1055,14 +1055,14 @@ class InstallSslOptionsConfTest(util.NginxTest):
return _hash return _hash
def test_prev_file_updates_to_current(self): def test_prev_file_updates_to_current(self):
from certbot_nginx._internal.constants import ALL_SSL_OPTIONS_HASHES from certbot._internal.nginx.constants import ALL_SSL_OPTIONS_HASHES
with mock.patch('certbot.crypto_util.sha256sum', with mock.patch('certbot.crypto_util.sha256sum',
new=self._mock_hash_except_ssl_conf_src(ALL_SSL_OPTIONS_HASHES[0])): new=self._mock_hash_except_ssl_conf_src(ALL_SSL_OPTIONS_HASHES[0])):
self._call() self._call()
self._assert_current_file() self._assert_current_file()
def test_prev_file_updates_to_current_old_nginx(self): def test_prev_file_updates_to_current_old_nginx(self):
from certbot_nginx._internal.constants import ALL_SSL_OPTIONS_HASHES from certbot._internal.nginx.constants import ALL_SSL_OPTIONS_HASHES
self.config.version = (1, 5, 8) self.config.version = (1, 5, 8)
with mock.patch('certbot.crypto_util.sha256sum', with mock.patch('certbot.crypto_util.sha256sum',
new=self._mock_hash_except_ssl_conf_src(ALL_SSL_OPTIONS_HASHES[0])): new=self._mock_hash_except_ssl_conf_src(ALL_SSL_OPTIONS_HASHES[0])):
@@ -1099,7 +1099,7 @@ class InstallSslOptionsConfTest(util.NginxTest):
assert not mock_logger.warning.called assert not mock_logger.warning.called
def test_current_file_hash_in_all_hashes(self): def test_current_file_hash_in_all_hashes(self):
from certbot_nginx._internal.constants import ALL_SSL_OPTIONS_HASHES from certbot._internal.nginx.constants import ALL_SSL_OPTIONS_HASHES
assert self._current_ssl_options_hash() in ALL_SSL_OPTIONS_HASHES, \ assert self._current_ssl_options_hash() in ALL_SSL_OPTIONS_HASHES, \
"Constants.ALL_SSL_OPTIONS_HASHES must be appended" \ "Constants.ALL_SSL_OPTIONS_HASHES must be appended" \
" with the sha256 hash of self.config.mod_ssl_conf when it is updated." " with the sha256 hash of self.config.mod_ssl_conf when it is updated."
@@ -1113,10 +1113,10 @@ class InstallSslOptionsConfTest(util.NginxTest):
""" """
import importlib.resources import importlib.resources
from certbot_nginx._internal.constants import ALL_SSL_OPTIONS_HASHES from certbot._internal.nginx.constants import ALL_SSL_OPTIONS_HASHES
tls_configs_ref = importlib.resources.files("certbot_nginx").joinpath( tls_configs_ref = importlib.resources.files("certbot").joinpath(
"_internal", "tls_configs") "_internal", "nginx", "tls_configs")
with importlib.resources.as_file(tls_configs_ref) as tls_configs_dir: with importlib.resources.as_file(tls_configs_ref) as tls_configs_dir:
for tls_config_file in os.listdir(tls_configs_dir): for tls_config_file in os.listdir(tls_configs_dir):
file_hash = crypto_util.sha256sum(os.path.join(tls_configs_dir, tls_config_file)) file_hash = crypto_util.sha256sum(os.path.join(tls_configs_dir, tls_config_file))
@@ -1149,10 +1149,10 @@ class InstallSslOptionsConfTest(util.NginxTest):
class DetermineDefaultServerRootTest(certbot_test_util.ConfigTestCase): class DetermineDefaultServerRootTest(certbot_test_util.ConfigTestCase):
"""Tests for certbot_nginx._internal.configurator._determine_default_server_root.""" """Tests for certbot._internal.nginx.configurator._determine_default_server_root."""
def _call(self): def _call(self):
from certbot_nginx._internal.configurator import _determine_default_server_root from certbot._internal.nginx.configurator import _determine_default_server_root
return _determine_default_server_root() return _determine_default_server_root()
@mock.patch.dict(os.environ, {"CERTBOT_DOCS": "1"}) @mock.patch.dict(os.environ, {"CERTBOT_DOCS": "1"})
@@ -1,17 +1,17 @@
"""Test certbot_nginx._internal.display_ops.""" """Test certbot._internal.nginx.display_ops."""
import sys import sys
import pytest import pytest
from certbot.display import util as display_util from certbot.display import util as display_util
from certbot.tests import util as certbot_util from certbot.tests import util as certbot_util
from certbot_nginx._internal import parser from certbot._internal.nginx import parser
from certbot_nginx._internal.display_ops import select_vhost_multiple from certbot._internal.nginx.display_ops import select_vhost_multiple
from certbot_nginx._internal.tests import test_util as util from certbot._internal.nginx.tests import test_util as util
class SelectVhostMultiTest(util.NginxTest): class SelectVhostMultiTest(util.NginxTest):
"""Tests for certbot_nginx._internal.display_ops.select_vhost_multiple.""" """Tests for certbot._internal.nginx.display_ops.select_vhost_multiple."""
def setUp(self): def setUp(self):
super().setUp() super().setUp()
@@ -1,4 +1,4 @@
"""Tests for certbot_nginx._internal.http_01""" """Tests for certbot._internal.nginx.http_01"""
import sys import sys
from unittest import mock from unittest import mock
@@ -9,8 +9,8 @@ from acme import challenges, messages
from certbot import achallenges from certbot import achallenges
from certbot.tests import acme_util from certbot.tests import acme_util
from certbot.tests import util as test_util from certbot.tests import util as test_util
from certbot_nginx._internal.obj import Addr from certbot._internal.nginx.obj import Addr
from certbot_nginx._internal.tests import test_util as util from certbot._internal.nginx.tests import test_util as util
AUTH_KEY = jose.JWKRSA.load(test_util.load_vector("rsa512_key.pem")) AUTH_KEY = jose.JWKRSA.load(test_util.load_vector("rsa512_key.pem"))
@@ -59,14 +59,14 @@ class HttpPerformTest(util.NginxTest):
config = self.get_nginx_configurator( config = self.get_nginx_configurator(
self.config_path, self.config_dir, self.work_dir, self.logs_dir) self.config_path, self.config_dir, self.work_dir, self.logs_dir)
from certbot_nginx._internal import http_01 from certbot._internal.nginx import http_01
self.http01 = http_01.NginxHttp01(config) self.http01 = http_01.NginxHttp01(config)
def test_perform0(self): def test_perform0(self):
responses = self.http01.perform() responses = self.http01.perform()
assert [] == responses assert [] == responses
@mock.patch("certbot_nginx._internal.configurator.NginxConfigurator.save") @mock.patch("certbot._internal.nginx.configurator.NginxConfigurator.save")
def test_perform1(self, mock_save): def test_perform1(self, mock_save):
self.http01.add_chall(self.achalls[0]) self.http01.add_chall(self.achalls[0])
response = self.achalls[0].response(self.account_key) response = self.achalls[0].response(self.account_key)
@@ -112,7 +112,7 @@ class HttpPerformTest(util.NginxTest):
# self.assertEqual(vhost.addrs, set(v_addr2_print)) # self.assertEqual(vhost.addrs, set(v_addr2_print))
# self.assertEqual(vhost.names, set([response.z_domain.decode('ascii')])) # self.assertEqual(vhost.names, set([response.z_domain.decode('ascii')]))
@mock.patch('certbot_nginx._internal.parser.NginxParser.add_server_directives') @mock.patch('certbot._internal.nginx.parser.NginxParser.add_server_directives')
def test_mod_config_http_and_https(self, mock_add_server_directives): def test_mod_config_http_and_https(self, mock_add_server_directives):
"""A server_name with both HTTP and HTTPS vhosts should get modded in both vhosts""" """A server_name with both HTTP and HTTPS vhosts should get modded in both vhosts"""
self.configuration.https_port = 443 self.configuration.https_port = 443
@@ -123,8 +123,8 @@ class HttpPerformTest(util.NginxTest):
# 2 * 'rewrite' + 2 * 'return 200 keyauthz' = 4 # 2 * 'rewrite' + 2 * 'return 200 keyauthz' = 4
assert mock_add_server_directives.call_count == 4 assert mock_add_server_directives.call_count == 4
@mock.patch('certbot_nginx._internal.parser.nginxparser.dump') @mock.patch('certbot._internal.nginx.parser.nginxparser.dump')
@mock.patch('certbot_nginx._internal.parser.NginxParser.add_server_directives') @mock.patch('certbot._internal.nginx.parser.NginxParser.add_server_directives')
def test_mod_config_only_https(self, mock_add_server_directives, mock_dump): def test_mod_config_only_https(self, mock_add_server_directives, mock_dump):
"""A server_name with only an HTTPS vhost should get modded""" """A server_name with only an HTTPS vhost should get modded"""
self.http01.add_chall(self.achalls[4]) # ipv6ssl.com self.http01.add_chall(self.achalls[4]) # ipv6ssl.com
@@ -136,7 +136,7 @@ class HttpPerformTest(util.NginxTest):
# should have been created and written to the challenge conf file # should have been created and written to the challenge conf file
assert mock_dump.call_args[0][0] != [] assert mock_dump.call_args[0][0] != []
@mock.patch('certbot_nginx._internal.parser.NginxParser.add_server_directives') @mock.patch('certbot._internal.nginx.parser.NginxParser.add_server_directives')
def test_mod_config_deduplicate(self, mock_add_server_directives): def test_mod_config_deduplicate(self, mock_add_server_directives):
"""A vhost that appears in both HTTP and HTTPS vhosts only gets modded once""" """A vhost that appears in both HTTP and HTTPS vhosts only gets modded once"""
achall = achallenges.KeyAuthorizationAnnotatedChallenge( achall = achallenges.KeyAuthorizationAnnotatedChallenge(
@@ -198,7 +198,7 @@ class HttpPerformTest(util.NginxTest):
f.write(original_example_com) f.write(original_example_com)
self.http01.configurator.parser.load() self.http01.configurator.parser.load()
@mock.patch("certbot_nginx._internal.configurator.NginxConfigurator.ipv6_info") @mock.patch("certbot._internal.nginx.configurator.NginxConfigurator.ipv6_info")
def test_default_listen_addresses_no_memoization(self, ipv6_info): def test_default_listen_addresses_no_memoization(self, ipv6_info):
# pylint: disable=protected-access # pylint: disable=protected-access
ipv6_info.return_value = (True, True) ipv6_info.return_value = (True, True)
@@ -208,7 +208,7 @@ class HttpPerformTest(util.NginxTest):
self.http01._default_listen_addresses() self.http01._default_listen_addresses()
assert ipv6_info.call_count == 2 assert ipv6_info.call_count == 2
@mock.patch("certbot_nginx._internal.configurator.NginxConfigurator.ipv6_info") @mock.patch("certbot._internal.nginx.configurator.NginxConfigurator.ipv6_info")
def test_default_listen_addresses_t_t(self, ipv6_info): def test_default_listen_addresses_t_t(self, ipv6_info):
# pylint: disable=protected-access # pylint: disable=protected-access
ipv6_info.return_value = (True, True) ipv6_info.return_value = (True, True)
@@ -217,7 +217,7 @@ class HttpPerformTest(util.NginxTest):
http_ipv6_addr = Addr.fromstring("[::]:80") http_ipv6_addr = Addr.fromstring("[::]:80")
assert addrs == [http_addr, http_ipv6_addr] assert addrs == [http_addr, http_ipv6_addr]
@mock.patch("certbot_nginx._internal.configurator.NginxConfigurator.ipv6_info") @mock.patch("certbot._internal.nginx.configurator.NginxConfigurator.ipv6_info")
def test_default_listen_addresses_t_f(self, ipv6_info): def test_default_listen_addresses_t_f(self, ipv6_info):
# pylint: disable=protected-access # pylint: disable=protected-access
ipv6_info.return_value = (True, False) ipv6_info.return_value = (True, False)
@@ -226,7 +226,7 @@ class HttpPerformTest(util.NginxTest):
http_ipv6_addr = Addr.fromstring("[::]:80 ipv6only=on") http_ipv6_addr = Addr.fromstring("[::]:80 ipv6only=on")
assert addrs == [http_addr, http_ipv6_addr] assert addrs == [http_addr, http_ipv6_addr]
@mock.patch("certbot_nginx._internal.configurator.NginxConfigurator.ipv6_info") @mock.patch("certbot._internal.nginx.configurator.NginxConfigurator.ipv6_info")
def test_default_listen_addresses_f_f(self, ipv6_info): def test_default_listen_addresses_f_f(self, ipv6_info):
# pylint: disable=protected-access # pylint: disable=protected-access
ipv6_info.return_value = (False, False) ipv6_info.return_value = (False, False)
@@ -1,4 +1,4 @@
"""Test for certbot_nginx._internal.nginxparser.""" """Test for certbot._internal.nginx.nginxparser."""
import copy import copy
import operator import operator
import sys import sys
@@ -8,13 +8,13 @@ import unittest
from pyparsing import ParseException from pyparsing import ParseException
import pytest import pytest
from certbot_nginx._internal.nginxparser import dump from certbot._internal.nginx.nginxparser import dump
from certbot_nginx._internal.nginxparser import dumps from certbot._internal.nginx.nginxparser import dumps
from certbot_nginx._internal.nginxparser import load from certbot._internal.nginx.nginxparser import load
from certbot_nginx._internal.nginxparser import loads from certbot._internal.nginx.nginxparser import loads
from certbot_nginx._internal.nginxparser import RawNginxParser from certbot._internal.nginx.nginxparser import RawNginxParser
from certbot_nginx._internal.nginxparser import UnspacedList from certbot._internal.nginx.nginxparser import UnspacedList
from certbot_nginx._internal.tests import test_util as util from certbot._internal.nginx.tests import test_util as util
FIRST = operator.itemgetter(0) FIRST = operator.itemgetter(0)
@@ -1,4 +1,4 @@
"""Test the helper objects in certbot_nginx._internal.obj.""" """Test the helper objects in certbot._internal.nginx.obj."""
import itertools import itertools
import sys import sys
import unittest import unittest
@@ -9,7 +9,7 @@ import pytest
class AddrTest(unittest.TestCase): class AddrTest(unittest.TestCase):
"""Test the Addr class.""" """Test the Addr class."""
def setUp(self): def setUp(self):
from certbot_nginx._internal.obj import Addr from certbot._internal.nginx.obj import Addr
self.addr1 = Addr.fromstring("192.168.1.1") self.addr1 = Addr.fromstring("192.168.1.1")
self.addr2 = Addr.fromstring("192.168.1.1:* ssl") self.addr2 = Addr.fromstring("192.168.1.1:* ssl")
self.addr3 = Addr.fromstring("192.168.1.1:80") self.addr3 = Addr.fromstring("192.168.1.1:80")
@@ -52,7 +52,7 @@ class AddrTest(unittest.TestCase):
assert self.addr7.default is True assert self.addr7.default is True
def test_fromstring_socket(self): def test_fromstring_socket(self):
from certbot_nginx._internal.obj import Addr, SocketAddrError from certbot._internal.nginx.obj import Addr, SocketAddrError
socket_string = r"unix:/var/run/nginx.sock" socket_string = r"unix:/var/run/nginx.sock"
with pytest.raises(SocketAddrError, match=socket_string): with pytest.raises(SocketAddrError, match=socket_string):
Addr.fromstring(socket_string) Addr.fromstring(socket_string)
@@ -77,14 +77,14 @@ class AddrTest(unittest.TestCase):
assert self.addr6.to_string(include_default=False) == "80" assert self.addr6.to_string(include_default=False) == "80"
def test_eq(self): def test_eq(self):
from certbot_nginx._internal.obj import Addr from certbot._internal.nginx.obj import Addr
new_addr1 = Addr.fromstring("192.168.1.1 spdy") new_addr1 = Addr.fromstring("192.168.1.1 spdy")
assert self.addr1 == new_addr1 assert self.addr1 == new_addr1
assert self.addr1 != self.addr2 assert self.addr1 != self.addr2
assert self.addr1 != 3333 assert self.addr1 != 3333
def test_equivalent_any_addresses(self): def test_equivalent_any_addresses(self):
from certbot_nginx._internal.obj import Addr from certbot._internal.nginx.obj import Addr
any_addresses = ("0.0.0.0:80 default_server ssl", any_addresses = ("0.0.0.0:80 default_server ssl",
"80 default_server ssl", "80 default_server ssl",
"*:80 default_server ssl", "*:80 default_server ssl",
@@ -102,7 +102,7 @@ class AddrTest(unittest.TestCase):
Addr.fromstring(any_address) Addr.fromstring(any_address)
def test_set_inclusion(self): def test_set_inclusion(self):
from certbot_nginx._internal.obj import Addr from certbot._internal.nginx.obj import Addr
set_a = {self.addr1, self.addr2} set_a = {self.addr1, self.addr2}
addr1b = Addr.fromstring("192.168.1.1") addr1b = Addr.fromstring("192.168.1.1")
addr2b = Addr.fromstring("192.168.1.1:* ssl") addr2b = Addr.fromstring("192.168.1.1:* ssl")
@@ -114,8 +114,8 @@ class AddrTest(unittest.TestCase):
class VirtualHostTest(unittest.TestCase): class VirtualHostTest(unittest.TestCase):
"""Test the VirtualHost class.""" """Test the VirtualHost class."""
def setUp(self): def setUp(self):
from certbot_nginx._internal.obj import Addr from certbot._internal.nginx.obj import Addr
from certbot_nginx._internal.obj import VirtualHost from certbot._internal.nginx.obj import VirtualHost
raw1 = [ raw1 = [
['listen', '69.50.225.155:9000'], ['listen', '69.50.225.155:9000'],
[['if', '($scheme', '!=', '"https") '], [['if', '($scheme', '!=', '"https") '],
@@ -164,8 +164,8 @@ class VirtualHostTest(unittest.TestCase):
{'localhost'}, raw_has_hsts, []) {'localhost'}, raw_has_hsts, [])
def test_eq(self): def test_eq(self):
from certbot_nginx._internal.obj import Addr from certbot._internal.nginx.obj import Addr
from certbot_nginx._internal.obj import VirtualHost from certbot._internal.nginx.obj import VirtualHost
vhost1b = VirtualHost( vhost1b = VirtualHost(
"filep", "filep",
{Addr.fromstring("localhost blah")}, False, False, {Addr.fromstring("localhost blah")}, False, False,
@@ -188,9 +188,9 @@ class VirtualHostTest(unittest.TestCase):
assert self.vhost1.has_header('Bogus-Header') is False assert self.vhost1.has_header('Bogus-Header') is False
def test_contains_list(self): def test_contains_list(self):
from certbot_nginx._internal.configurator import _test_block_from_block from certbot._internal.nginx.configurator import _test_block_from_block
from certbot_nginx._internal.obj import Addr from certbot._internal.nginx.obj import Addr
from certbot_nginx._internal.obj import VirtualHost from certbot._internal.nginx.obj import VirtualHost
test_block = [ test_block = [
['\n ', 'return', ' ', '301', ' ', 'https://$host$request_uri'], ['\n ', 'return', ' ', '301', ' ', 'https://$host$request_uri'],
['\n'] ['\n']
@@ -9,19 +9,19 @@ from unittest import mock
import pytest import pytest
from certbot_nginx._internal.parser_obj import COMMENT_BLOCK from certbot._internal.nginx.parser_obj import COMMENT_BLOCK
from certbot_nginx._internal.parser_obj import parse_raw from certbot._internal.nginx.parser_obj import parse_raw
class CommentHelpersTest(unittest.TestCase): class CommentHelpersTest(unittest.TestCase):
def test_is_comment(self): def test_is_comment(self):
from certbot_nginx._internal.parser_obj import _is_comment from certbot._internal.nginx.parser_obj import _is_comment
assert _is_comment(parse_raw(['#'])) assert _is_comment(parse_raw(['#']))
assert _is_comment(parse_raw(['#', ' literally anything else'])) assert _is_comment(parse_raw(['#', ' literally anything else']))
assert not _is_comment(parse_raw(['not', 'even', 'a', 'comment'])) assert not _is_comment(parse_raw(['not', 'even', 'a', 'comment']))
def test_is_certbot_comment(self): def test_is_certbot_comment(self):
from certbot_nginx._internal.parser_obj import _is_certbot_comment from certbot._internal.nginx.parser_obj import _is_certbot_comment
assert _is_certbot_comment( assert _is_certbot_comment(
parse_raw(COMMENT_BLOCK)) parse_raw(COMMENT_BLOCK))
assert not _is_certbot_comment( assert not _is_certbot_comment(
@@ -32,8 +32,8 @@ class CommentHelpersTest(unittest.TestCase):
parse_raw(['not', 'even', 'a', 'comment'])) parse_raw(['not', 'even', 'a', 'comment']))
def test_certbot_comment(self): def test_certbot_comment(self):
from certbot_nginx._internal.parser_obj import _certbot_comment from certbot._internal.nginx.parser_obj import _certbot_comment
from certbot_nginx._internal.parser_obj import _is_certbot_comment from certbot._internal.nginx.parser_obj import _is_certbot_comment
comment = _certbot_comment(None) comment = _certbot_comment(None)
assert _is_certbot_comment(comment) assert _is_certbot_comment(comment)
assert comment.dump() == COMMENT_BLOCK assert comment.dump() == COMMENT_BLOCK
@@ -43,7 +43,7 @@ class CommentHelpersTest(unittest.TestCase):
class ParsingHooksTest(unittest.TestCase): class ParsingHooksTest(unittest.TestCase):
def test_is_sentence(self): def test_is_sentence(self):
from certbot_nginx._internal.parser_obj import Sentence from certbot._internal.nginx.parser_obj import Sentence
assert not Sentence.should_parse([]) assert not Sentence.should_parse([])
assert Sentence.should_parse(['']) assert Sentence.should_parse([''])
assert Sentence.should_parse(['word']) assert Sentence.should_parse(['word'])
@@ -52,7 +52,7 @@ class ParsingHooksTest(unittest.TestCase):
assert not Sentence.should_parse(['word', []]) assert not Sentence.should_parse(['word', []])
def test_is_block(self): def test_is_block(self):
from certbot_nginx._internal.parser_obj import Block from certbot._internal.nginx.parser_obj import Block
assert not Block.should_parse([]) assert not Block.should_parse([])
assert not Block.should_parse(['']) assert not Block.should_parse([''])
assert not Block.should_parse(['two', 'words']) assert not Block.should_parse(['two', 'words'])
@@ -64,7 +64,7 @@ class ParsingHooksTest(unittest.TestCase):
assert Block.should_parse([['block_name'], [['many'], ['statements'], 'here']]) assert Block.should_parse([['block_name'], [['many'], ['statements'], 'here']])
assert Block.should_parse([['if', ' ', '(whatever)'], ['hi']]) assert Block.should_parse([['if', ' ', '(whatever)'], ['hi']])
@mock.patch("certbot_nginx._internal.parser_obj.Parsable.parsing_hooks") @mock.patch("certbot._internal.nginx.parser_obj.Parsable.parsing_hooks")
def test_parse_raw(self, parsing_hooks): def test_parse_raw(self, parsing_hooks):
fake_parser1 = mock.Mock() fake_parser1 = mock.Mock()
fake_parser1.should_parse = lambda x: True fake_parser1.should_parse = lambda x: True
@@ -82,7 +82,7 @@ class ParsingHooksTest(unittest.TestCase):
fake_parser1().parse.assert_not_called() fake_parser1().parse.assert_not_called()
fake_parser2().parse.assert_called_once() fake_parser2().parse.assert_called_once()
@mock.patch("certbot_nginx._internal.parser_obj.Parsable.parsing_hooks") @mock.patch("certbot._internal.nginx.parser_obj.Parsable.parsing_hooks")
def test_parse_raw_no_match(self, parsing_hooks): def test_parse_raw_no_match(self, parsing_hooks):
from certbot import errors from certbot import errors
fake_parser1 = mock.Mock() fake_parser1 = mock.Mock()
@@ -94,7 +94,7 @@ class ParsingHooksTest(unittest.TestCase):
with pytest.raises(errors.MisconfigurationError): with pytest.raises(errors.MisconfigurationError):
parse_raw([]) parse_raw([])
@mock.patch("certbot_nginx._internal.parser_obj.Parsable.parsing_hooks") @mock.patch("certbot._internal.nginx.parser_obj.Parsable.parsing_hooks")
def test_parse_raw_passes_add_spaces(self, parsing_hooks): def test_parse_raw_passes_add_spaces(self, parsing_hooks):
fake_parser1 = mock.Mock() fake_parser1 = mock.Mock()
fake_parser1.should_parse = lambda x: True fake_parser1.should_parse = lambda x: True
@@ -107,7 +107,7 @@ class ParsingHooksTest(unittest.TestCase):
class SentenceTest(unittest.TestCase): class SentenceTest(unittest.TestCase):
def setUp(self): def setUp(self):
from certbot_nginx._internal.parser_obj import Sentence from certbot._internal.nginx.parser_obj import Sentence
self.sentence = Sentence(None) self.sentence = Sentence(None)
def test_parse_bad_sentence_raises_error(self): def test_parse_bad_sentence_raises_error(self):
@@ -157,7 +157,7 @@ class SentenceTest(unittest.TestCase):
class BlockTest(unittest.TestCase): class BlockTest(unittest.TestCase):
def setUp(self): def setUp(self):
from certbot_nginx._internal.parser_obj import Block from certbot._internal.nginx.parser_obj import Block
self.bloc = Block(None) self.bloc = Block(None)
self.name = ['server', 'name'] self.name = ['server', 'name']
self.contents = [['thing', '1'], ['thing', '2'], ['another', 'one']] self.contents = [['thing', '1'], ['thing', '2'], ['another', 'one']]
@@ -173,8 +173,8 @@ class BlockTest(unittest.TestCase):
def test_iterate_match(self): def test_iterate_match(self):
# can match on contents while expanded # can match on contents while expanded
from certbot_nginx._internal.parser_obj import Block from certbot._internal.nginx.parser_obj import Block
from certbot_nginx._internal.parser_obj import Sentence from certbot._internal.nginx.parser_obj import Sentence
expected = [['thing', '1'], ['thing', '2']] expected = [['thing', '1'], ['thing', '2']]
for i, elem in enumerate(self.bloc.iterate(expanded=True, for i, elem in enumerate(self.bloc.iterate(expanded=True,
match=lambda x: isinstance(x, Sentence) and 'thing' in x.words)): match=lambda x: isinstance(x, Sentence) and 'thing' in x.words)):
@@ -216,7 +216,7 @@ class BlockTest(unittest.TestCase):
class StatementsTest(unittest.TestCase): class StatementsTest(unittest.TestCase):
def setUp(self): def setUp(self):
from certbot_nginx._internal.parser_obj import Statements from certbot._internal.nginx.parser_obj import Statements
self.statements = Statements(None) self.statements = Statements(None)
self.raw = [ self.raw = [
['sentence', 'one'], ['sentence', 'one'],
@@ -1,4 +1,4 @@
"""Tests for certbot_nginx._internal.parser.""" """Tests for certbot._internal.nginx.parser."""
import glob import glob
import re import re
import shutil import shutil
@@ -8,10 +8,10 @@ import pytest
from certbot import errors from certbot import errors
from certbot.compat import os from certbot.compat import os
from certbot_nginx._internal import nginxparser from certbot._internal.nginx import nginxparser
from certbot_nginx._internal import obj from certbot._internal.nginx import obj
from certbot_nginx._internal import parser from certbot._internal.nginx import parser
from certbot_nginx._internal.tests import test_util as util from certbot._internal.nginx.tests import test_util as util
class NginxParserTest(util.NginxTest): class NginxParserTest(util.NginxTest):
@@ -264,7 +264,7 @@ class NginxParserTest(util.NginxTest):
[['foo', 'bar'], ['ssl_certificate', [['foo', 'bar'], ['ssl_certificate',
'/etc/ssl/cert2.pem']]) '/etc/ssl/cert2.pem']])
nparser.add_server_directives(mock_vhost, [['foo', 'bar']]) nparser.add_server_directives(mock_vhost, [['foo', 'bar']])
from certbot_nginx._internal.parser import COMMENT from certbot._internal.nginx.parser import COMMENT
assert nparser.parsed[example_com] == \ assert nparser.parsed[example_com] == \
[[['server'], [['listen', '69.50.225.155:9000'], [[['server'], [['listen', '69.50.225.155:9000'],
['listen', '127.0.0.1'], ['listen', '127.0.0.1'],
@@ -298,7 +298,7 @@ class NginxParserTest(util.NginxTest):
nparser.add_server_directives(mock_vhost, nparser.add_server_directives(mock_vhost,
[['\n ', 'include', ' ', [['\n ', 'include', ' ',
nparser.abs_path('comment_in_file.conf')]]) nparser.abs_path('comment_in_file.conf')]])
from certbot_nginx._internal.parser import COMMENT from certbot._internal.nginx.parser import COMMENT
assert nparser.parsed[example_com] == \ assert nparser.parsed[example_com] == \
[[['server'], [['listen', '69.50.225.155:9000'], [[['server'], [['listen', '69.50.225.155:9000'],
['listen', '127.0.0.1'], ['listen', '127.0.0.1'],
@@ -317,7 +317,7 @@ class NginxParserTest(util.NginxTest):
mock_vhost = obj.VirtualHost(filep, None, None, None, target, None, [0]) mock_vhost = obj.VirtualHost(filep, None, None, None, target, None, [0])
nparser.update_or_add_server_directives( nparser.update_or_add_server_directives(
mock_vhost, [['server_name', 'foobar.com']]) mock_vhost, [['server_name', 'foobar.com']])
from certbot_nginx._internal.parser import COMMENT from certbot._internal.nginx.parser import COMMENT
assert nparser.parsed[filep] == \ assert nparser.parsed[filep] == \
[[['server'], [['listen', '69.50.225.155:9000'], [[['server'], [['listen', '69.50.225.155:9000'],
['listen', '127.0.0.1'], ['listen', '127.0.0.1'],
@@ -378,8 +378,8 @@ class NginxParserTest(util.NginxTest):
["\n", "a", " ", "b", "\n"], ["\n", "a", " ", "b", "\n"],
["c", " ", "d"], ["c", " ", "d"],
["\n", "e", " ", "f"]]) ["\n", "e", " ", "f"]])
from certbot_nginx._internal.parser import COMMENT_BLOCK from certbot._internal.nginx.parser import COMMENT_BLOCK
from certbot_nginx._internal.parser import comment_directive from certbot._internal.nginx.parser import comment_directive
comment_directive(block, 1) comment_directive(block, 1)
comment_directive(block, 0) comment_directive(block, 0)
assert block.spaced == [ assert block.spaced == [
@@ -403,7 +403,7 @@ class NginxParserTest(util.NginxTest):
ssl_prefer_server_ciphers on; ssl_prefer_server_ciphers on;
}""") }""")
block = server_block[0][1] block = server_block[0][1]
from certbot_nginx._internal.parser import _comment_out_directive from certbot._internal.nginx.parser import _comment_out_directive
_comment_out_directive(block, 4, "blah1") _comment_out_directive(block, 4, "blah1")
_comment_out_directive(block, 5, "blah2") _comment_out_directive(block, 5, "blah2")
_comment_out_directive(block, 6, "blah3") _comment_out_directive(block, 6, "blah3")
@@ -1,4 +1,4 @@
"""Common utilities for certbot_nginx.""" """Common test utilities for the nginx plugin."""
import copy import copy
import importlib.resources import importlib.resources
import shutil import shutil
@@ -12,8 +12,8 @@ from certbot import util
from certbot.compat import os from certbot.compat import os
from certbot.plugins import common from certbot.plugins import common
from certbot.tests import util as test_util from certbot.tests import util as test_util
from certbot_nginx._internal import configurator from certbot._internal.nginx import configurator
from certbot_nginx._internal import nginxparser from certbot._internal.nginx import nginxparser
class NginxTest(test_util.ConfigTestCase): class NginxTest(test_util.ConfigTestCase):
@@ -63,9 +63,9 @@ class NginxTest(test_util.ConfigTestCase):
self.configuration.http01_port = 80 self.configuration.http01_port = 80
self.configuration.https_port = 5001 self.configuration.https_port = 5001
with mock.patch("certbot_nginx._internal.configurator.NginxConfigurator." with mock.patch("certbot._internal.nginx.configurator.NginxConfigurator."
"config_test"): "config_test"):
with mock.patch("certbot_nginx._internal.configurator.util." with mock.patch("certbot._internal.nginx.configurator.util."
"exe_exists") as mock_exe_exists: "exe_exists") as mock_exe_exists:
mock_exe_exists.return_value = True mock_exe_exists.return_value = True
config = configurator.NginxConfigurator( config = configurator.NginxConfigurator(