diff options
author | Mads Jensen <mje@inducks.org> | 2022-01-04 00:05:21 +0300 |
---|---|---|
committer | GitHub <noreply@github.com> | 2022-01-04 00:05:21 +0300 |
commit | a0dbe1e85035f12e194d91148836d830871ec554 (patch) | |
tree | 53e2a9796195f5e7b8ee9566756820e4d02b0a67 | |
parent | eeca208c8f57304590ac1af80b496e61021aaa45 (diff) |
Improve assertions in certbot-apache tests. (#9131)
* Improve assertions in certbot-apache tests.
Replacements inspired by flake8-assertive.
* Fix test failures
* assertEqual is not for None :D
* Pass all tests :)
-rw-r--r-- | certbot-apache/tests/augeasnode_test.py | 50 | ||||
-rw-r--r-- | certbot-apache/tests/autohsts_test.py | 23 | ||||
-rw-r--r-- | certbot-apache/tests/centos6_test.py | 29 | ||||
-rw-r--r-- | certbot-apache/tests/centos_test.py | 13 | ||||
-rw-r--r-- | certbot-apache/tests/complex_parsing_test.py | 11 | ||||
-rw-r--r-- | certbot-apache/tests/configurator_reverter_test.py | 19 | ||||
-rw-r--r-- | certbot-apache/tests/configurator_test.py | 260 | ||||
-rw-r--r-- | certbot-apache/tests/debian_test.py | 31 | ||||
-rw-r--r-- | certbot-apache/tests/display_ops_test.py | 16 | ||||
-rw-r--r-- | certbot-apache/tests/dualnode_test.py | 91 | ||||
-rw-r--r-- | certbot-apache/tests/fedora_test.py | 12 | ||||
-rw-r--r-- | certbot-apache/tests/gentoo_test.py | 11 | ||||
-rw-r--r-- | certbot-apache/tests/http_01_test.py | 24 | ||||
-rw-r--r-- | certbot-apache/tests/obj_test.py | 63 | ||||
-rw-r--r-- | certbot-apache/tests/parser_test.py | 28 | ||||
-rw-r--r-- | certbot-apache/tests/parsernode_configurator_test.py | 2 | ||||
-rw-r--r-- | certbot-apache/tests/util.py | 2 |
17 files changed, 330 insertions, 355 deletions
diff --git a/certbot-apache/tests/augeasnode_test.py b/certbot-apache/tests/augeasnode_test.py index 85a17ab31..1e11b5eb3 100644 --- a/certbot-apache/tests/augeasnode_test.py +++ b/certbot-apache/tests/augeasnode_test.py @@ -25,24 +25,29 @@ def _get_augeasnode_mock(filepath): metadata=metadata) return augeasnode_mock + class AugeasParserNodeTest(util.ApacheTest): # pylint: disable=too-many-public-methods """Test AugeasParserNode using available test configurations""" def setUp(self): # pylint: disable=arguments-differ super().setUp() - with mock.patch("certbot_apache._internal.configurator.ApacheConfigurator.get_parsernode_root") as mock_parsernode: + with mock.patch( + "certbot_apache._internal.configurator.ApacheConfigurator.get_parsernode_root" + ) as mock_parsernode: mock_parsernode.side_effect = _get_augeasnode_mock( os.path.join(self.config_path, "apache2.conf")) self.config = util.get_apache_configurator( - self.config_path, self.vhost_path, self.config_dir, self.work_dir, use_parsernode=True) + self.config_path, self.vhost_path, self.config_dir, self.work_dir, + use_parsernode=True, + ) self.vh_truth = util.get_vh_truth( self.temp_dir, "debian_apache_2_4/multiple_vhosts") def test_save(self): with mock.patch('certbot_apache._internal.parser.ApacheParser.save') as mock_save: self.config.parser_root.save("A save message") - self.assertTrue(mock_save.called) + self.assertIs(mock_save.called, True) self.assertEqual(mock_save.call_args[0][0], "A save message") def test_unsaved_files(self): @@ -67,7 +72,8 @@ class AugeasParserNodeTest(util.ApacheTest): # pylint: disable=too-many-public- "/Anything": "Anything", } for test in testcases: - self.assertEqual(block._aug_get_name(test), testcases[test]) # pylint: disable=protected-access + # pylint: disable=protected-access + self.assertEqual(block._aug_get_name(test), testcases[test]) def test_find_blocks(self): blocks = self.config.parser_root.find_blocks("VirtualHost", exclude=False) @@ -81,7 +87,7 @@ class AugeasParserNodeTest(util.ApacheTest): # pylint: disable=too-many-public- def test_find_directive_found(self): directives = self.config.parser_root.find_directives("Listen") self.assertEqual(len(directives), 1) - self.assertTrue(directives[0].filepath.endswith("/apache2/ports.conf")) + self.assertIs(directives[0].filepath.endswith("/apache2/ports.conf"), True) self.assertEqual(directives[0].parameters, (u'80',)) def test_find_directive_notfound(self): @@ -96,29 +102,29 @@ class AugeasParserNodeTest(util.ApacheTest): # pylint: disable=too-many-public- servername = vh.find_directives("servername") self.assertEqual(servername[0].parameters[0], "certbot.demo") found = True - self.assertTrue(found) + self.assertIs(found, True) def test_find_comments(self): rootcomment = self.config.parser_root.find_comments( "This is the main Apache server configuration file. " ) self.assertEqual(len(rootcomment), 1) - self.assertTrue(rootcomment[0].filepath.endswith( + self.assertIs(rootcomment[0].filepath.endswith( "debian_apache_2_4/multiple_vhosts/apache2/apache2.conf" - )) + ), True) def test_set_parameters(self): servernames = self.config.parser_root.find_directives("servername") names: List[str] = [] for servername in servernames: names += servername.parameters - self.assertFalse("going_to_set_this" in names) + self.assertNotIn("going_to_set_this", names) servernames[0].set_parameters(["something", "going_to_set_this"]) servernames = self.config.parser_root.find_directives("servername") names = [] for servername in servernames: names += servername.parameters - self.assertTrue("going_to_set_this" in names) + self.assertIn("going_to_set_this", names) def test_set_parameters_atinit(self): from certbot_apache._internal.augeasparser import AugeasDirectiveNode @@ -131,7 +137,7 @@ class AugeasParserNodeTest(util.ApacheTest): # pylint: disable=too-many-public- ancestor=assertions.PASS, metadata=servernames[0].metadata ) - self.assertTrue(mock_set.called) + self.assertIs(mock_set.called, True) self.assertEqual( mock_set.call_args_list[0][0][0], ["test", "setting", "these"] @@ -151,7 +157,7 @@ class AugeasParserNodeTest(util.ApacheTest): # pylint: disable=too-many-public- self.assertEqual(len(servername.parameters), 3) servername.set_parameters(["thisshouldnotexistpreviously"]) found = True - self.assertTrue(found) + self.assertIs(found, True) # Verify params servernames = self.config.parser_root.find_directives("servername") @@ -161,7 +167,7 @@ class AugeasParserNodeTest(util.ApacheTest): # pylint: disable=too-many-public- self.assertEqual(len(servername.parameters), 1) servername.set_parameters(["thisshouldnotexistpreviously"]) found = True - self.assertTrue(found) + self.assertIs(found, True) def test_add_child_comment(self): newc = self.config.parser_root.add_child_comment("The content") @@ -201,7 +207,7 @@ class AugeasParserNodeTest(util.ApacheTest): # pylint: disable=too-many-public- rpath, self.config.parser_root.metadata["augeaspath"] ) - self.assertTrue(directive.startswith("NewBlock")) + self.assertIs(directive.startswith("NewBlock"), True) def test_add_child_block_beginning(self): self.config.parser_root.add_child_block( @@ -212,7 +218,7 @@ class AugeasParserNodeTest(util.ApacheTest): # pylint: disable=too-many-public- root_path = self.config.parser_root.metadata["augeaspath"] # Get first child first = parser.aug.match("{}/*[1]".format(root_path)) - self.assertTrue(first[0].endswith("Beginning")) + self.assertIs(first[0].endswith("Beginning"), True) def test_add_child_block_append(self): self.config.parser_root.add_child_block( @@ -222,7 +228,7 @@ class AugeasParserNodeTest(util.ApacheTest): # pylint: disable=too-many-public- root_path = self.config.parser_root.metadata["augeaspath"] # Get last child last = parser.aug.match("{}/*[last()]".format(root_path)) - self.assertTrue(last[0].endswith("VeryLast")) + self.assertIs(last[0].endswith("VeryLast"), True) def test_add_child_block_append_alt(self): self.config.parser_root.add_child_block( @@ -233,7 +239,7 @@ class AugeasParserNodeTest(util.ApacheTest): # pylint: disable=too-many-public- root_path = self.config.parser_root.metadata["augeaspath"] # Get last child last = parser.aug.match("{}/*[last()]".format(root_path)) - self.assertTrue(last[0].endswith("VeryLastAlt")) + self.assertIs(last[0].endswith("VeryLastAlt"), True) def test_add_child_block_middle(self): self.config.parser_root.add_child_block( @@ -244,7 +250,7 @@ class AugeasParserNodeTest(util.ApacheTest): # pylint: disable=too-many-public- root_path = self.config.parser_root.metadata["augeaspath"] # Augeas indices start at 1 :( middle = parser.aug.match("{}/*[6]".format(root_path)) - self.assertTrue(middle[0].endswith("Middle")) + self.assertIs(middle[0].endswith("Middle"), True) def test_add_child_block_existing_name(self): parser = self.config.parser_root.parser @@ -257,7 +263,7 @@ class AugeasParserNodeTest(util.ApacheTest): # pylint: disable=too-many-public- ) new_block = parser.aug.match("{}/VirtualHost[2]".format(root_path)) self.assertEqual(len(new_block), 1) - self.assertTrue(vh.metadata["augeaspath"].endswith("VirtualHost[2]")) + self.assertIs(vh.metadata["augeaspath"].endswith("VirtualHost[2]"), True) def test_node_init_error_bad_augeaspath(self): from certbot_apache._internal.augeasparser import AugeasBlockNode @@ -302,7 +308,7 @@ class AugeasParserNodeTest(util.ApacheTest): # pylint: disable=too-many-public- self.assertEqual(len(dirs), 1) self.assertEqual(dirs[0].parameters, ("with", "parameters")) # The new directive was added to the very first line of the config - self.assertTrue(dirs[0].metadata["augeaspath"].endswith("[1]")) + self.assertIs(dirs[0].metadata["augeaspath"].endswith("[1]"), True) def test_add_child_directive_exception(self): self.assertRaises( @@ -328,8 +334,8 @@ class AugeasParserNodeTest(util.ApacheTest): # pylint: disable=too-many-public- ancs = vh.find_ancestors("Macro") self.assertEqual(len(ancs), 0) nonmacro_test = True - self.assertTrue(macro_test) - self.assertTrue(nonmacro_test) + self.assertIs(macro_test, True) + self.assertIs(nonmacro_test, True) def test_find_ancestors_bad_path(self): self.config.parser_root.metadata["augeaspath"] = "" diff --git a/certbot-apache/tests/autohsts_test.py b/certbot-apache/tests/autohsts_test.py index 72d26a33a..664d791bd 100644 --- a/certbot-apache/tests/autohsts_test.py +++ b/certbot-apache/tests/autohsts_test.py @@ -47,7 +47,7 @@ class AutoHSTSTest(util.ApacheTest): self.config.parser.modules.pop("headers_module", None) self.config.parser.modules.pop("mod_header.c", None) self.config.enable_autohsts(mock.MagicMock(), ["ocspvhost.com"]) - self.assertTrue(mock_enable.called) + self.assertIs(mock_enable.called, True) @mock.patch("certbot_apache._internal.configurator.ApacheConfigurator.restart") def test_autohsts_deploy_already_exists(self, _restart): @@ -74,7 +74,7 @@ class AutoHSTSTest(util.ApacheTest): # Verify increased value self.assertEqual(self.get_autohsts_value(self.vh_truth[7].path), inc_val) - self.assertTrue(mock_prepare.called) + self.assertIs(mock_prepare.called, True) @mock.patch("certbot_apache._internal.configurator.ApacheConfigurator.restart") @mock.patch("certbot_apache._internal.configurator.ApacheConfigurator._autohsts_increase") @@ -88,7 +88,7 @@ class AutoHSTSTest(util.ApacheTest): self.config.update_autohsts(mock.MagicMock()) # Freq not patched, so value shouldn't increase - self.assertFalse(mock_increase.called) + self.assertIs(mock_increase.called, False) @mock.patch("certbot_apache._internal.configurator.ApacheConfigurator.restart") @@ -135,13 +135,13 @@ class AutoHSTSTest(util.ApacheTest): # Time mock is used to make sure that the execution does not # continue when no autohsts entries exist in pluginstorage self.config.update_autohsts(mock.MagicMock()) - self.assertFalse(mock_time.called) + self.assertIs(mock_time.called, False) def test_autohsts_make_permanent_noop(self): self.config.storage.put = mock.MagicMock() self.config.deploy_autohsts(mock.MagicMock()) # Make sure that the execution does not continue when no entries in store - self.assertFalse(self.config.storage.put.called) + self.assertIs(self.config.storage.put.called, False) @mock.patch("certbot_apache._internal.display_ops.select_vhost") def test_autohsts_no_ssl_vhost(self, mock_select): @@ -150,15 +150,13 @@ class AutoHSTSTest(util.ApacheTest): self.assertRaises(errors.PluginError, self.config.enable_autohsts, mock.MagicMock(), "invalid.example.com") - self.assertTrue( - "Certbot was not able to find SSL" in mock_log.call_args[0][0]) + self.assertIn("Certbot was not able to find SSL", mock_log.call_args[0][0]) @mock.patch("certbot_apache._internal.configurator.ApacheConfigurator.restart") @mock.patch("certbot_apache._internal.configurator.ApacheConfigurator.add_vhost_id") def test_autohsts_dont_enhance_twice(self, mock_id, _restart): mock_id.return_value = "1234567" - self.config.enable_autohsts(mock.MagicMock(), - ["ocspvhost.com", "ocspvhost.com"]) + self.config.enable_autohsts(mock.MagicMock(), ["ocspvhost.com", "ocspvhost.com"]) self.assertEqual(mock_id.call_count, 1) def test_autohsts_remove_orphaned(self): @@ -168,7 +166,7 @@ class AutoHSTSTest(util.ApacheTest): self.config._autohsts_save_state() self.config.update_autohsts(mock.MagicMock()) - self.assertFalse("orphan_id" in self.config._autohsts) + self.assertNotIn("orphan_id", self.config._autohsts) # Make sure it's removed from the pluginstorage file as well self.config._autohsts = None self.config._autohsts_fetch_state() @@ -181,9 +179,8 @@ class AutoHSTSTest(util.ApacheTest): self.config._autohsts_save_state() with mock.patch("certbot_apache._internal.configurator.logger.error") as mock_log: self.config.deploy_autohsts(mock.MagicMock()) - self.assertTrue(mock_log.called) - self.assertTrue( - "VirtualHost with id orphan_id was not" in mock_log.call_args[0][0]) + self.assertIs(mock_log.called, True) + self.assertIn("VirtualHost with id orphan_id was not", mock_log.call_args[0][0]) if __name__ == "__main__": diff --git a/certbot-apache/tests/centos6_test.py b/certbot-apache/tests/centos6_test.py index 017e2f09f..85f1333e9 100644 --- a/certbot-apache/tests/centos6_test.py +++ b/certbot-apache/tests/centos6_test.py @@ -48,8 +48,7 @@ class CentOS6Tests(util.ApacheTest): self.temp_dir, "centos6_apache/apache") def test_get_parser(self): - self.assertTrue(isinstance(self.config.parser, - override_centos.CentOSParser)) + self.assertIsInstance(self.config.parser, override_centos.CentOSParser) def test_get_virtual_hosts(self): """Make sure all vhosts are being properly found.""" @@ -72,9 +71,9 @@ class CentOS6Tests(util.ApacheTest): "LoadModule", "ssl_module", exclude=False) self.assertEqual(len(ssl_loadmods), 1) # Make sure the LoadModule ssl_module is in ssl.conf (default) - self.assertTrue("ssl.conf" in ssl_loadmods[0]) + self.assertIn("ssl.conf", ssl_loadmods[0]) # ...and that it's not inside of <IfModule> - self.assertFalse("IfModule" in ssl_loadmods[0]) + self.assertNotIn("IfModule", ssl_loadmods[0]) # Get the example vhost self.config.assoc["test.example.com"] = self.vh_truth[0] @@ -95,7 +94,7 @@ class CentOS6Tests(util.ApacheTest): # ...and both of them should be wrapped in <IfModule !mod_ssl.c> # lm[:-17] strips off /directive/arg[1] from the path. ifmod_args = self.config.parser.get_all_args(lm[:-17]) - self.assertTrue("!mod_ssl.c" in ifmod_args) + self.assertIn("!mod_ssl.c", ifmod_args) @mock.patch("certbot_apache._internal.configurator.display_util.notify") def test_loadmod_multiple(self, unused_mock_notify): @@ -107,7 +106,7 @@ class CentOS6Tests(util.ApacheTest): pre_loadmods = self.config.parser.find_dir( "LoadModule", "ssl_module", exclude=False) # LoadModules are not within IfModule blocks - self.assertFalse(any("ifmodule" in m.lower() for m in pre_loadmods)) + self.assertIs(any("ifmodule" in m.lower() for m in pre_loadmods), False) self.config.assoc["test.example.com"] = self.vh_truth[0] self.config.deploy_cert( "random.demo", "example/cert.pem", "example/key.pem", @@ -116,7 +115,9 @@ class CentOS6Tests(util.ApacheTest): "LoadModule", "ssl_module", exclude=False) for mod in post_loadmods: - self.assertTrue(self.config.parser.not_modssl_ifmodule(mod)) #pylint: disable=no-member + with self.subTest(mod=mod): + # pylint: disable=no-member + self.assertIs(self.config.parser.not_modssl_ifmodule(mod), True) @mock.patch("certbot_apache._internal.configurator.display_util.notify") def test_loadmod_rootconf_exists(self, unused_mock_notify): @@ -207,20 +208,20 @@ class CentOS6Tests(util.ApacheTest): post_loadmods = self.config.parser.find_dir("LoadModule", "ssl_module", exclude=False) - self.assertFalse(post_loadmods) + self.assertEqual(post_loadmods, []) def test_no_ifmod_search_false(self): #pylint: disable=no-member - self.assertFalse(self.config.parser.not_modssl_ifmodule( + self.assertIs(self.config.parser.not_modssl_ifmodule( "/path/does/not/include/ifmod" - )) - self.assertFalse(self.config.parser.not_modssl_ifmodule( + ), False) + self.assertIs(self.config.parser.not_modssl_ifmodule( "" - )) - self.assertFalse(self.config.parser.not_modssl_ifmodule( + ), False) + self.assertIs(self.config.parser.not_modssl_ifmodule( "/path/includes/IfModule/but/no/arguments" - )) + ), False) if __name__ == "__main__": diff --git a/certbot-apache/tests/centos_test.py b/certbot-apache/tests/centos_test.py index a92c37979..c9a820466 100644 --- a/certbot-apache/tests/centos_test.py +++ b/certbot-apache/tests/centos_test.py @@ -34,6 +34,7 @@ def get_vh_truth(temp_dir, config_name): ] return vh_truth + class FedoraRestartTest(util.ApacheTest): """Tests for Fedora specific self-signed certificate override""" @@ -140,8 +141,8 @@ class MultipleVhostsTestCentOS(util.ApacheTest): self.assertEqual(mock_get.call_count, 3) self.assertEqual(len(self.config.parser.modules), 4) self.assertEqual(len(self.config.parser.variables), 2) - self.assertTrue("TEST2" in self.config.parser.variables) - self.assertTrue("mod_another.c" in self.config.parser.modules) + self.assertIn("TEST2", self.config.parser.variables) + self.assertIn("mod_another.c", self.config.parser.modules) def test_get_virtual_hosts(self): """Make sure all vhosts are being properly found.""" @@ -172,11 +173,11 @@ class MultipleVhostsTestCentOS(util.ApacheTest): mock_osi.return_value = ("centos", "7") self.config.parser.update_runtime_variables() - self.assertTrue("mock_define" in self.config.parser.variables) - self.assertTrue("mock_define_too" in self.config.parser.variables) - self.assertTrue("mock_value" in self.config.parser.variables) + self.assertIn("mock_define", self.config.parser.variables) + self.assertIn("mock_define_too", self.config.parser.variables) + self.assertIn("mock_value", self.config.parser.variables) self.assertEqual("TRUE", self.config.parser.variables["mock_value"]) - self.assertTrue("MOCK_NOSEP" in self.config.parser.variables) + self.assertIn("MOCK_NOSEP", self.config.parser.variables) self.assertEqual("NOSEP_VAL", self.config.parser.variables["NOSEP_TWO"]) @mock.patch("certbot_apache._internal.configurator.util.run_script") diff --git a/certbot-apache/tests/complex_parsing_test.py b/certbot-apache/tests/complex_parsing_test.py index e36bd85d1..973af302a 100644 --- a/certbot-apache/tests/complex_parsing_test.py +++ b/certbot-apache/tests/complex_parsing_test.py @@ -11,8 +11,7 @@ class ComplexParserTest(util.ParserTest): """Apache Parser Test.""" def setUp(self): # pylint: disable=arguments-differ - super().setUp( - "complex_parsing", "complex_parsing") + super().setUp("complex_parsing", "complex_parsing") self.setup_variables() # This needs to happen after due to setup_variables not being run @@ -78,12 +77,12 @@ class ComplexParserTest(util.ParserTest): def test_load_modules(self): """If only first is found, there is bad variable parsing.""" - self.assertTrue("status_module" in self.parser.modules) - self.assertTrue("mod_status.c" in self.parser.modules) + self.assertIn("status_module", self.parser.modules) + self.assertIn("mod_status.c", self.parser.modules) # This is in an IfDefine - self.assertTrue("ssl_module" in self.parser.modules) - self.assertTrue("mod_ssl.c" in self.parser.modules) + self.assertIn("ssl_module", self.parser.modules) + self.assertIn("mod_ssl.c", self.parser.modules) def verify_fnmatch(self, arg, hit=True): """Test if Include was correctly parsed.""" diff --git a/certbot-apache/tests/configurator_reverter_test.py b/certbot-apache/tests/configurator_reverter_test.py index d8f5ddd05..72b8fe2bd 100644 --- a/certbot-apache/tests/configurator_reverter_test.py +++ b/certbot-apache/tests/configurator_reverter_test.py @@ -14,15 +14,13 @@ import util class ConfiguratorReverterTest(util.ApacheTest): """Test for ApacheConfigurator reverter methods""" - def setUp(self): # pylint: disable=arguments-differ super().setUp() self.config = util.get_apache_configurator( self.config_path, self.vhost_path, self.config_dir, self.work_dir) - self.vh_truth = util.get_vh_truth( - self.temp_dir, "debian_apache_2_4/multiple_vhosts") + self.vh_truth = util.get_vh_truth(self.temp_dir, "debian_apache_2_4/multiple_vhosts") def tearDown(self): shutil.rmtree(self.config_dir) @@ -30,17 +28,13 @@ class ConfiguratorReverterTest(util.ApacheTest): shutil.rmtree(self.temp_dir) def test_bad_save_checkpoint(self): - self.config.reverter.add_to_checkpoint = mock.Mock( - side_effect=errors.ReverterError) - self.config.parser.add_dir( - self.vh_truth[0].path, "Test", "bad_save_ckpt") + self.config.reverter.add_to_checkpoint = mock.Mock(side_effect=errors.ReverterError) + self.config.parser.add_dir(self.vh_truth[0].path, "Test", "bad_save_ckpt") self.assertRaises(errors.PluginError, self.config.save) def test_bad_save_finalize_checkpoint(self): - self.config.reverter.finalize_checkpoint = mock.Mock( - side_effect=errors.ReverterError) - self.config.parser.add_dir( - self.vh_truth[0].path, "Test", "bad_save_ckpt") + self.config.reverter.finalize_checkpoint = mock.Mock(side_effect=errors.ReverterError) + self.config.parser.add_dir(self.vh_truth[0].path, "Test", "bad_save_ckpt") self.assertRaises(errors.PluginError, self.config.save, "Title") def test_finalize_save(self): @@ -72,8 +66,7 @@ class ConfiguratorReverterTest(util.ApacheTest): self.assertEqual(mock_load.call_count, 1) def test_rollback_error(self): - self.config.reverter.rollback_checkpoints = mock.Mock( - side_effect=errors.ReverterError) + self.config.reverter.rollback_checkpoints = mock.Mock(side_effect=errors.ReverterError) self.assertRaises(errors.PluginError, self.config.rollback_checkpoints) def test_recovery_routine_reload(self): diff --git a/certbot-apache/tests/configurator_test.py b/certbot-apache/tests/configurator_test.py index 84f9e2053..f9d9ac1fe 100644 --- a/certbot-apache/tests/configurator_test.py +++ b/certbot-apache/tests/configurator_test.py @@ -83,8 +83,8 @@ class MultipleVhostsTest(util.ApacheTest): self.config.prepare() except errors.PluginError as err: err_msg = str(err) - self.assertTrue("lock" in err_msg) - self.assertTrue(self.config.conf("server-root") in err_msg) + self.assertIn("lock", err_msg) + self.assertIn(self.config.conf("server-root"), err_msg) else: # pragma: no cover self.fail("Exception wasn't raised!") @@ -116,7 +116,8 @@ class MultipleVhostsTest(util.ApacheTest): # Make sure that all (and only) the expected values exist self.assertEqual(len(mock_add.call_args_list), len(found)) for e in exp: - self.assertTrue(e in found) + with self.subTest(e=e): + self.assertIn(e, found) del os.environ["CERTBOT_DOCS"] @@ -130,11 +131,10 @@ class MultipleVhostsTest(util.ApacheTest): from certbot_apache._internal.configurator import ApacheConfigurator parameters = set(ApacheConfigurator.OS_DEFAULTS.__dict__.keys()) for cls in OVERRIDE_CLASSES.values(): - self.assertTrue(parameters.issubset(set(cls.OS_DEFAULTS.__dict__.keys()))) + self.assertIs(parameters.issubset(set(cls.OS_DEFAULTS.__dict__.keys())), True) def test_constant(self): - self.assertTrue("debian_apache_2_4/multiple_vhosts/apache" in - self.config.options.server_root) + self.assertIn("debian_apache_2_4/multiple_vhosts/apache", self.config.options.server_root) @certbot_util.patch_display_util() def test_get_all_names(self, mock_getutility): @@ -162,9 +162,9 @@ class MultipleVhostsTest(util.ApacheTest): names = self.config.get_all_names() self.assertEqual(len(names), 9) - self.assertTrue("zombo.com" in names) - self.assertTrue("google.com" in names) - self.assertTrue("certbot.demo" in names) + self.assertIn("zombo.com", names) + self.assertIn("google.com", names) + self.assertIn("certbot.demo", names) def test_get_bad_path(self): self.assertEqual(apache_util.get_file_path(None), None) @@ -188,16 +188,14 @@ class MultipleVhostsTest(util.ApacheTest): True, False) # pylint: disable=protected-access self.config._add_servernames(ssl_vh1) - self.assertTrue( - self.config._add_servername_alias("oy_vey", ssl_vh1) is None) + self.assertIsNone(self.config._add_servername_alias("oy_vey", ssl_vh1)) def test_add_servernames_alias(self): self.config.parser.add_dir( self.vh_truth[2].path, "ServerAlias", ["*.le.co"]) # pylint: disable=protected-access self.config._add_servernames(self.vh_truth[2]) - self.assertEqual( - self.vh_truth[2].get_names(), {"*.le.co", "ip-172-30-0-17"}) + self.assertEqual(self.vh_truth[2].get_names(), {"*.le.co", "ip-172-30-0-17"}) def test_get_virtual_hosts(self): """Make sure all vhosts are being properly found.""" @@ -246,8 +244,8 @@ class MultipleVhostsTest(util.ApacheTest): self.vh_truth[0].get_names(), chosen_vhost.get_names()) # Make sure we go from HTTP -> HTTPS - self.assertFalse(self.vh_truth[0].ssl) - self.assertTrue(chosen_vhost.ssl) + self.assertIs(self.vh_truth[0].ssl, False) + self.assertIs(chosen_vhost.ssl, True) @mock.patch("certbot_apache._internal.configurator.ApacheConfigurator._find_best_vhost") @mock.patch("certbot_apache._internal.parser.ApacheParser.add_dir") @@ -256,7 +254,7 @@ class MultipleVhostsTest(util.ApacheTest): ret_vh.enabled = False mock_find.return_value = self.vh_truth[8] self.config.choose_vhost("whatever.com") - self.assertTrue(mock_add.called) + self.assertIs(mock_add.called, True) @mock.patch("certbot_apache._internal.display_ops.select_vhost") def test_choose_vhost_select_vhost_with_temp(self, mock_select): @@ -291,23 +289,17 @@ class MultipleVhostsTest(util.ApacheTest): def test_findbest_continues_on_short_domain(self): # pylint: disable=protected-access - chosen_vhost = self.config._find_best_vhost("purple.com") - self.assertEqual(None, chosen_vhost) + self.assertIsNone(self.config._find_best_vhost("purple.com")) def test_findbest_continues_on_long_domain(self): # pylint: disable=protected-access - chosen_vhost = self.config._find_best_vhost("green.red.purple.com") - self.assertEqual(None, chosen_vhost) + self.assertIsNone(self.config._find_best_vhost("green.red.purple.com")) def test_find_best_vhost(self): # pylint: disable=protected-access - self.assertEqual( - self.vh_truth[3], self.config._find_best_vhost("certbot.demo")) - self.assertEqual( - self.vh_truth[0], - self.config._find_best_vhost("encryption-example.demo")) - self.assertEqual( - self.config._find_best_vhost("does-not-exist.com"), None) + self.assertEqual(self.vh_truth[3], self.config._find_best_vhost("certbot.demo")) + self.assertEqual(self.vh_truth[0], self.config._find_best_vhost("encryption-example.demo")) + self.assertEqual(self.config._find_best_vhost("does-not-exist.com"), None) def test_find_best_vhost_variety(self): # pylint: disable=protected-access @@ -345,11 +337,11 @@ class MultipleVhostsTest(util.ApacheTest): self.config.parser.modules["mod_ssl.c"] = None self.config.parser.modules["socache_shmcb_module"] = None - self.assertFalse(ssl_vhost.enabled) + self.assertIs(ssl_vhost.enabled, False) self.config.deploy_cert( "encryption-example.demo", "example/cert.pem", "example/key.pem", "example/cert_chain.pem", "example/fullchain.pem") - self.assertTrue(ssl_vhost.enabled) + self.assertIs(ssl_vhost.enabled, True) def test_no_duplicate_include(self): def mock_find_dir(directive, argument, _): @@ -366,7 +358,7 @@ class MultipleVhostsTest(util.ApacheTest): if a[0][1] == "Include" and a[0][2] == self.config.mod_ssl_conf: tried_to_add = True # Include should be added, find_dir is not patched, and returns falsy - self.assertTrue(tried_to_add) + self.assertIs(tried_to_add, True) self.config.parser.find_dir = mock_find_dir mock_add.reset_mock() @@ -395,20 +387,16 @@ class MultipleVhostsTest(util.ApacheTest): f_args.append(self.config.parser.get_arg(d)) return f_args # Verify that the dummy directives do not exist - self.assertFalse( - "insert_cert_file_path" in find_args(vhostpath, - "SSLCertificateFile")) - self.assertFalse( - "insert_key_file_path" in find_args(vhostpath, - "SSLCertificateKeyFile")) + self.assertNotIn( + "insert_cert_file_path", find_args(vhostpath, "SSLCertificateFile")) + self.assertNotIn( + "insert_key_file_path", find_args(vhostpath, "SSLCertificateKeyFile")) orig_add_dummy(vhostpath) # Verify that the dummy directives exist - self.assertTrue( - "insert_cert_file_path" in find_args(vhostpath, - "SSLCertificateFile")) - self.assertTrue( - "insert_key_file_path" in find_args(vhostpath, - "SSLCertificateKeyFile")) + self.assertIn( + "insert_cert_file_path", find_args(vhostpath, "SSLCertificateFile")) + self.assertIn( + "insert_key_file_path", find_args(vhostpath, "SSLCertificateKeyFile")) # pylint: disable=protected-access self.config._add_dummy_ssl_directives = mock_add_dummy_ssl @@ -420,8 +408,8 @@ class MultipleVhostsTest(util.ApacheTest): self.config.save() # Verify ssl_module was enabled. - self.assertTrue(self.vh_truth[1].enabled) - self.assertTrue("ssl_module" in self.config.parser.modules) + self.assertIs(self.vh_truth[1].enabled, True) + self.assertIn("ssl_module", self.config.parser.modules) loc_cert = self.config.parser.find_dir( "sslcertificatefile", "example/cert.pem", self.vh_truth[1].path) @@ -457,17 +445,15 @@ class MultipleVhostsTest(util.ApacheTest): def test_is_name_vhost(self): addr = obj.Addr.fromstring("*:80") - self.assertTrue(self.config.is_name_vhost(addr)) + self.assertIs(self.config.is_name_vhost(addr), True) self.config.version = (2, 2) - self.assertFalse(self.config.is_name_vhost(addr)) + self.assertEqual(self.config.is_name_vhost(addr), []) def test_add_name_vhost(self): self.config.add_name_vhost(obj.Addr.fromstring("*:443")) self.config.add_name_vhost(obj.Addr.fromstring("*:80")) - self.assertTrue(self.config.parser.find_dir( - "NameVirtualHost", "*:443", exclude=False)) - self.assertTrue(self.config.parser.find_dir( - "NameVirtualHost", "*:80")) + self.assertTrue(self.config.parser.find_dir("NameVirtualHost", "*:443", exclude=False)) + self.assertTrue(self.config.parser.find_dir("NameVirtualHost", "*:80")) def test_add_listen_80(self): mock_find = mock.Mock() @@ -476,8 +462,8 @@ class MultipleVhostsTest(util.ApacheTest): self.config.parser.find_dir = mock_find self.config.parser.add_dir = mock_add_dir self.config.ensure_listen("80") - self.assertTrue(mock_add_dir.called) - self.assertTrue(mock_find.called) + self.assertIs(mock_add_dir.called, True) + self.assertIs(mock_find.called, True) self.assertEqual(mock_add_dir.call_args[0][1], "Listen") self.assertEqual(mock_add_dir.call_args[0][2], "80") @@ -502,13 +488,13 @@ class MultipleVhostsTest(util.ApacheTest): # Test self.config.ensure_listen("8080") self.assertEqual(mock_add_dir.call_count, 3) - self.assertTrue(mock_add_dir.called) + self.assertIs(mock_add_dir.called, True) self.assertEqual(mock_add_dir.call_args[0][1], "Listen") call_found = False for mock_call in mock_add_dir.mock_calls: if mock_call[1][2] == ['1.2.3.4:8080']: call_found = True - self.assertTrue(call_found) + self.assertIs(call_found, True) @mock.patch("certbot_apache._internal.parser.ApacheParser.reset_modules") def test_prepare_server_https(self, mock_reset): @@ -631,8 +617,8 @@ class MultipleVhostsTest(util.ApacheTest): def test_make_vhost_ssl_nonsymlink(self): ssl_vhost_slink = self.config.make_vhost_ssl(self.vh_truth[8]) - self.assertTrue(ssl_vhost_slink.ssl) - self.assertTrue(ssl_vhost_slink.enabled) + self.assertIs(ssl_vhost_slink.ssl, True) + self.assertIs(ssl_vhost_slink.enabled, True) self.assertEqual(ssl_vhost_slink.name, "nonsym.link") def test_make_vhost_ssl_nonexistent_vhost_path(self): @@ -653,8 +639,8 @@ class MultipleVhostsTest(util.ApacheTest): self.assertEqual(len(ssl_vhost.addrs), 1) self.assertEqual({obj.Addr.fromstring("*:443")}, ssl_vhost.addrs) self.assertEqual(ssl_vhost.name, "encryption-example.demo") - self.assertTrue(ssl_vhost.ssl) - self.assertFalse(ssl_vhost.enabled) + self.assertIs(ssl_vhost.ssl, True) + self.assertIs(ssl_vhost.enabled, False) self.assertEqual(self.config.is_name_vhost(self.vh_truth[0]), self.config.is_name_vhost(ssl_vhost)) @@ -733,15 +719,14 @@ class MultipleVhostsTest(util.ApacheTest): def test_get_ssl_vhost_path(self): # pylint: disable=protected-access - self.assertTrue( - self.config._get_ssl_vhost_path("example_path").endswith(".conf")) + self.assertIs(self.config._get_ssl_vhost_path("example_path").endswith(".conf"), True) def test_add_name_vhost_if_necessary(self): # pylint: disable=protected-access self.config.add_name_vhost = mock.Mock() self.config.version = (2, 2) self.config._add_name_vhost_if_necessary(self.vh_truth[0]) - self.assertTrue(self.config.add_name_vhost.called) + self.assertIs(self.config.add_name_vhost.called, True) new_addrs = set() for addr in self.vh_truth[0].addrs: @@ -780,9 +765,9 @@ class MultipleVhostsTest(util.ApacheTest): for i, achall in enumerate(achalls): self.config.cleanup([achall]) if i == len(achalls) - 1: - self.assertTrue(mock_restart.called) + self.assertIs(mock_restart.called, True) else: - self.assertFalse(mock_restart.called) + self.assertIs(mock_restart.called, False) @mock.patch("certbot_apache._internal.configurator.ApacheConfigurator.restart") @mock.patch("certbot_apache._internal.apache_util._get_runtime_cfg") @@ -795,10 +780,10 @@ class MultipleVhostsTest(util.ApacheTest): self.config._chall_out.add(achall) # pylint: disable=protected-access self.config.cleanup([achalls[-1]]) - self.assertFalse(mock_restart.called) + self.assertIs(mock_restart.called, False) self.config.cleanup(achalls) - self.assertTrue(mock_restart.called) + self.assertIs(mock_restart.called, True) @mock.patch("certbot.util.run_script") def test_get_version(self, mock_script): @@ -847,18 +832,18 @@ class MultipleVhostsTest(util.ApacheTest): self.assertTrue(self.config.more_info()) def test_get_chall_pref(self): - self.assertTrue(isinstance(self.config.get_chall_pref(""), list)) + self.assertIsInstance(self.config.get_chall_pref(""), list) def test_install_ssl_options_conf(self): path = os.path.join(self.work_dir, "test_it") other_path = os.path.join(self.work_dir, "other_test_it") self.config.install_ssl_options_conf(path, other_path) - self.assertTrue(os.path.isfile(path)) - self.assertTrue(os.path.isfile(other_path)) + self.assertIs(os.path.isfile(path), True) + self.assertIs(os.path.isfile(other_path), True) # TEST ENHANCEMENTS def test_supported_enhancements(self): - self.assertTrue(isinstance(self.config.supported_enhancements(), list)) + self.assertIsInstance(self.config.supported_enhancements(), list) def test_find_http_vhost_without_ancestor(self): # pylint: disable=protected-access @@ -897,16 +882,16 @@ class MultipleVhostsTest(util.ApacheTest): self.assertRaises(errors.PluginError, self.config.enhance, "certbot.demo", "redirect") # Check that correct logger.warning was printed - self.assertTrue("not able to find" in mock_log.call_args[0][0]) - self.assertTrue("\"redirect\"" in mock_log.call_args[0][0]) + self.assertIn("not able to find", mock_log.call_args[0][0]) + self.assertIn("\"redirect\"", mock_log.call_args[0][0]) mock_log.reset_mock() self.assertRaises(errors.PluginError, self.config.enhance, "certbot.demo", "ensure-http-header", "Test") # Check that correct logger.warning was printed - self.assertTrue("not able to find" in mock_log.call_args[0][0]) - self.assertTrue("Test" in mock_log.call_args[0][0]) + self.assertIn("not able to find", mock_log.call_args[0][0]) + self.assertIn("Test", mock_log.call_args[0][0]) @mock.patch("certbot.util.exe_exists") def test_ocsp_stapling(self, mock_exe): @@ -984,7 +969,7 @@ class MultipleVhostsTest(util.ApacheTest): # pylint: disable=protected-access http_vh = self.config._get_http_vhost(ssl_vh) - self.assertFalse(http_vh.ssl) + self.assertIs(http_vh.ssl, False) @mock.patch("certbot.util.run_script") @mock.patch("certbot.util.exe_exists") @@ -1039,7 +1024,7 @@ class MultipleVhostsTest(util.ApacheTest): self.config.enhance("certbot.demo", "ensure-http-header", "Upgrade-Insecure-Requests") - self.assertTrue("headers_module" in self.config.parser.modules) + self.assertIn("headers_module", self.config.parser.modules) # Get the ssl vhost for certbot.demo ssl_vhost = self.config.assoc["certbot.demo"] @@ -1091,8 +1076,8 @@ class MultipleVhostsTest(util.ApacheTest): self.assertEqual(len(rw_rule), 3) # [:-3] to remove the vhost index number - self.assertTrue(rw_engine[0].startswith(self.vh_truth[3].path[:-3])) - self.assertTrue(rw_rule[0].startswith(self.vh_truth[3].path[:-3])) + self.assertIs(rw_engine[0].startswith(self.vh_truth[3].path[:-3]), True) + self.assertIs(rw_rule[0].startswith(self.vh_truth[3].path[:-3]), True) def test_rewrite_rule_exists(self): # Skip the enable mod @@ -1101,7 +1086,7 @@ class MultipleVhostsTest(util.ApacheTest): self.config.parser.add_dir( self.vh_truth[3].path, "RewriteRule", ["Unknown"]) # pylint: disable=protected-access - self.assertTrue(self.config._is_rewrite_exists(self.vh_truth[3])) + self.assertIs(self.config._is_rewrite_exists(self.vh_truth[3]), True) def test_rewrite_engine_exists(self): # Skip the enable mod @@ -1141,10 +1126,10 @@ class MultipleVhostsTest(util.ApacheTest): # three args to rw_rule + 1 arg for the pre existing rewrite self.assertEqual(len(rw_rule), 5) # [:-3] to remove the vhost index number - self.assertTrue(rw_engine[0].startswith(self.vh_truth[3].path[:-3])) - self.assertTrue(rw_rule[0].startswith(self.vh_truth[3].path[:-3])) + self.assertIs(rw_engine[0].startswith(self.vh_truth[3].path[:-3]), True) + self.assertIs(rw_rule[0].startswith(self.vh_truth[3].path[:-3]), True) - self.assertTrue("rewrite_module" in self.config.parser.modules) + self.assertIn("rewrite_module", self.config.parser.modules) @mock.patch("certbot.util.run_script") @mock.patch("certbot.util.exe_exists") @@ -1202,7 +1187,7 @@ class MultipleVhostsTest(util.ApacheTest): "ApacheConfigurator._verify_no_certbot_redirect") with mock.patch(verify_no_redirect) as mock_verify: self.config.enhance("green.blue.purple.com", "redirect") - self.assertFalse(mock_verify.called) + self.assertIs(mock_verify.called, False) def test_redirect_from_previous_run(self): # Skip the enable mod @@ -1243,16 +1228,16 @@ class MultipleVhostsTest(util.ApacheTest): def test_sift_rewrite_rule(self): # pylint: disable=protected-access small_quoted_target = "RewriteRule ^ \"http://\"" - self.assertFalse(self.config._sift_rewrite_rule(small_quoted_target)) + self.assertIs(self.config._sift_rewrite_rule(small_quoted_target), False) https_target = "RewriteRule ^ https://satoshi" - self.assertTrue(self.config._sift_rewrite_rule(https_target)) + self.assertIs(self.config._sift_rewrite_rule(https_target), True) normal_target = "RewriteRule ^/(.*) http://www.a.com:1234/$1 [L,R]" - self.assertFalse(self.config._sift_rewrite_rule(normal_target)) + self.assertIs(self.config._sift_rewrite_rule(normal_target), False) not_rewriterule = "NotRewriteRule ^ ..." - self.assertFalse(self.config._sift_rewrite_rule(not_rewriterule)) + self.assertIs(self.config._sift_rewrite_rule(not_rewriterule), False) def get_key_and_achalls(self): """Return testing achallenges.""" @@ -1281,15 +1266,13 @@ class MultipleVhostsTest(util.ApacheTest): vhost = self.vh_truth[0] vhost.enabled = False vhost.filep = inc_path - self.assertFalse(self.config.parser.find_dir("Include", inc_path)) - self.assertFalse( - os.path.dirname(inc_path) in self.config.parser.existing_paths) + self.assertEqual(self.config.parser.find_dir("Include", inc_path), []) + self.assertNotIn(os.path.dirname(inc_path), self.config.parser.existing_paths) self.config.enable_site(vhost) - self.assertTrue(self.config.parser.find_dir("Include", inc_path)) - self.assertTrue( - os.path.dirname(inc_path) in self.config.parser.existing_paths) - self.assertTrue( - os.path.basename(inc_path) in self.config.parser.existing_paths[ + self.assertGreaterEqual(len(self.config.parser.find_dir("Include", inc_path)), 1) + self.assertIn(os.path.dirname(inc_path), self.config.parser.existing_paths) + self.assertIn( + os.path.basename(inc_path), self.config.parser.existing_paths[ os.path.dirname(inc_path)]) @mock.patch('certbot_apache._internal.configurator.display_util.notify') @@ -1312,7 +1295,7 @@ class MultipleVhostsTest(util.ApacheTest): "example/cert.pem", "example/key.pem", "example/cert_chain.pem") # Test that we actually called add_include - self.assertTrue(mock_add.called) + self.assertIs(mock_add.called, True) shutil.rmtree(tmp_path) def test_deploy_cert_no_mod_ssl(self): @@ -1331,7 +1314,7 @@ class MultipleVhostsTest(util.ApacheTest): ret_vh.enabled = True self.config.enable_site(ret_vh) # Make sure that we return early - self.assertFalse(mock_parsed.called) + self.assertIs(mock_parsed.called, False) def test_enable_mod_unsupported(self): self.assertRaises(errors.MisconfigurationError, @@ -1352,7 +1335,7 @@ class MultipleVhostsTest(util.ApacheTest): # And the actual returned values self.assertEqual(len(vhs), 1) self.assertEqual(vhs[0].name, "certbot.demo") - self.assertTrue(vhs[0].ssl) + self.assertIs(vhs[0].ssl, True) self.assertNotEqual(vhs[0], self.vh_truth[3]) @@ -1364,7 +1347,7 @@ class MultipleVhostsTest(util.ApacheTest): mock_select_vhs.return_value = [self.vh_truth[1]] vhs = self.config._choose_vhosts_wildcard("*.certbot.demo", create_ssl=False) - self.assertFalse(mock_makessl.called) + self.assertIs(mock_makessl.called, False) self.assertEqual(vhs[0], self.vh_truth[1]) @mock.patch("certbot_apache._internal.configurator.ApacheConfigurator._vhosts_for_wildcard") @@ -1381,14 +1364,13 @@ class MultipleVhostsTest(util.ApacheTest): self.assertEqual(mock_select_vhs.call_args[0][0][0], self.vh_truth[7]) self.assertEqual(len(mock_select_vhs.call_args_list), 1) # Ensure that make_vhost_ssl was not called, vhost.ssl == true - self.assertFalse(mock_makessl.called) + self.assertIs(mock_makessl.called, False) # And the actual returned values self.assertEqual(len(vhs), 1) - self.assertTrue(vhs[0].ssl) + self.assertIs(vhs[0].ssl, True) self.assertEqual(vhs[0], self.vh_truth[7]) - @mock.patch('certbot_apache._internal.configurator.display_util.notify') def test_deploy_cert_wildcard(self, unused_mock_notify): # pylint: disable=protected-access @@ -1399,7 +1381,7 @@ class MultipleVhostsTest(util.ApacheTest): with mock.patch(mock_d) as mock_dep: self.config.deploy_cert("*.wildcard.example.org", "/tmp/path", "/tmp/path", "/tmp/path", "/tmp/path") - self.assertTrue(mock_dep.called) + self.assertIs(mock_dep.called, True) self.assertEqual(len(mock_dep.call_args_list), 1) self.assertEqual(self.vh_truth[7], mock_dep.call_args_list[0][0][0]) @@ -1421,7 +1403,7 @@ class MultipleVhostsTest(util.ApacheTest): self.config._wildcard_vhosts["*.certbot.demo"] = [self.vh_truth[3]] self.config.enhance("*.certbot.demo", "ensure-http-header", "Upgrade-Insecure-Requests") - self.assertFalse(mock_choose.called) + self.assertIs(mock_choose.called, False) @mock.patch("certbot_apache._internal.configurator.ApacheConfigurator._choose_vhosts_wildcard") def test_enhance_wildcard_no_install(self, mock_choose): @@ -1431,7 +1413,7 @@ class MultipleVhostsTest(util.ApacheTest): self.config.parser.modules["headers_module"] = None self.config.enhance("*.certbot.demo", "ensure-http-header", "Upgrade-Insecure-Requests") - self.assertTrue(mock_choose.called) + self.assertIs(mock_choose.called, True) def test_add_vhost_id(self): for vh in [self.vh_truth[0], self.vh_truth[1], self.vh_truth[2]]: @@ -1510,7 +1492,8 @@ class AugeasVhostsTest(util.ApacheTest): names = ( "an.example.net", "another.example.net", "an.other.example.net") for name in names: - self.assertFalse(name in self.config.choose_vhost(name).aliases) + with self.subTest(name=name): + self.assertNotIn(name, self.config.choose_vhost(name).aliases) @mock.patch("certbot_apache._internal.obj.VirtualHost.conflicts") def test_choose_vhost_without_matching_wildcard(self, mock_conflicts): @@ -1518,7 +1501,7 @@ class AugeasVhostsTest(util.ApacheTest): mock_path = "certbot_apache._internal.display_ops.select_vhost" with mock.patch(mock_path, lambda _, vhosts: vhosts[0]): for name in ("a.example.net", "other.example.net"): - self.assertTrue(name in self.config.choose_vhost(name).aliases) + self.assertIn(name, self.config.choose_vhost(name).aliases) @mock.patch("certbot_apache._internal.obj.VirtualHost.conflicts") def test_choose_vhost_wildcard_not_found(self, mock_conflicts): @@ -1551,6 +1534,7 @@ class AugeasVhostsTest(util.ApacheTest): self.assertRaises(errors.PluginError, self.config.make_vhost_ssl, broken_vhost) + class MultiVhostsTest(util.ApacheTest): """Test configuration with multiple virtualhosts in a single file.""" # pylint: disable=protected-access @@ -1559,9 +1543,7 @@ class MultiVhostsTest(util.ApacheTest): td = "debian_apache_2_4/multi_vhosts" cr = "debian_apache_2_4/multi_vhosts/apache2" vr = "debian_apache_2_4/multi_vhosts/apache2/sites-available" - super().setUp(test_dir=td, - config_root=cr, - vhost_root=vr) + super().setUp(test_dir=td, config_root=cr, vhost_root=vr) self.config = util.get_apache_configurator( self.config_path, self.vhost_path, @@ -1582,9 +1564,8 @@ class MultiVhostsTest(util.ApacheTest): self.assertEqual(len(ssl_vhost.addrs), 1) self.assertEqual({obj.Addr.fromstring("*:443")}, ssl_vhost.addrs) self.assertEqual(ssl_vhost.name, "banana.vomit.com") - self.assertTrue(ssl_vhost.ssl) - self.assertFalse(ssl_vhost.enabled) - + self.assertIs(ssl_vhost.ssl, True) + self.assertIs(ssl_vhost.enabled, False) self.assertEqual(self.config.is_name_vhost(self.vh_truth[1]), self.config.is_name_vhost(ssl_vhost)) @@ -1616,8 +1597,7 @@ class MultiVhostsTest(util.ApacheTest): ssl_vhost = self.config.make_vhost_ssl(self.vh_truth[4]) - self.assertTrue(self.config.parser.find_dir( - "RewriteEngine", "on", ssl_vhost.path, False)) + self.assertTrue(self.config.parser.find_dir("RewriteEngine", "on", ssl_vhost.path, False)) with open(ssl_vhost.filep) as the_file: conf_text = the_file.read() @@ -1625,8 +1605,8 @@ class MultiVhostsTest(util.ApacheTest): "\"https://new.example.com/docs/$1\" [R,L]") uncommented_rewrite_rule = ("RewriteRule \"^/docs/(.+)\" " "\"http://new.example.com/docs/$1\" [R,L]") - self.assertTrue(commented_rewrite_rule in conf_text) - self.assertTrue(uncommented_rewrite_rule in conf_text) + self.assertIn(commented_rewrite_rule, conf_text) + self.assertIn(uncommented_rewrite_rule, conf_text) self.assertEqual(mock_notify.call_count, 1) self.assertIn("Some rewrite rules", mock_notify.call_args[0][0]) @@ -1650,12 +1630,12 @@ class MultiVhostsTest(util.ApacheTest): "https://%{SERVER_NAME}%{REQUEST_URI} " "[L,NE,R=permanent]") - self.assertTrue(not_commented_cond1 in conf_line_set) - self.assertTrue(not_commented_rewrite_rule in conf_line_set) + self.assertIn(not_commented_cond1, conf_line_set) + self.assertIn(not_commented_rewrite_rule, conf_line_set) - self.assertTrue(commented_cond1 in conf_line_set) - self.assertTrue(commented_cond2 in conf_line_set) - self.assertTrue(commented_rewrite_rule in conf_line_set) + self.assertIn(commented_cond1, conf_line_set) + self.assertIn(commented_cond2, conf_line_set) + self.assertIn(commented_rewrite_rule, conf_line_set) self.assertEqual(mock_notify.call_count, 1) self.assertIn("Some rewrite rules", mock_notify.call_args[0][0]) @@ -1677,7 +1657,7 @@ class InstallSslOptionsConfTest(util.ApacheTest): return crypto_util.sha256sum(self.config.pick_apache_config()) def _assert_current_file(self): - self.assertTrue(os.path.isfile(self.config.mod_ssl_conf)) + self.assertIs(os.path.isfile(self.config.mod_ssl_conf), True) self.assertEqual(crypto_util.sha256sum(self.config.mod_ssl_conf), self._current_ssl_options_hash()) @@ -1685,7 +1665,7 @@ class InstallSslOptionsConfTest(util.ApacheTest): # prepare should have placed a file there self._assert_current_file() os.remove(self.config.mod_ssl_conf) - self.assertFalse(os.path.isfile(self.config.mod_ssl_conf)) + self.assertIs(os.path.isfile(self.config.mod_ssl_conf), False) self._call() self._assert_current_file() @@ -1707,8 +1687,8 @@ class InstallSslOptionsConfTest(util.ApacheTest): mod_ssl_conf.write("a new line for the wrong hash\n") with mock.patch("certbot.plugins.common.logger") as mock_logger: self._call() - self.assertFalse(mock_logger.warning.called) - self.assertTrue(os.path.isfile(self.config.mod_ssl_conf)) + self.assertIs(mock_logger.warning.called, False) + self.assertIs(os.path.isfile(self.config.mod_ssl_conf), True) self.assertEqual(crypto_util.sha256sum( self.config.pick_apache_config()), self._current_ssl_options_hash()) @@ -1731,7 +1711,7 @@ class InstallSslOptionsConfTest(util.ApacheTest): # only print warning once with mock.patch("certbot.plugins.common.logger") as mock_logger: self._call() - self.assertFalse(mock_logger.warning.called) + self.assertIs(mock_logger.warning.called, False) def test_ssl_config_files_hash_in_all_hashes(self): """ @@ -1747,12 +1727,14 @@ class InstallSslOptionsConfTest(util.ApacheTest): "certbot_apache", os.path.join("_internal", "tls_configs")) all_files = [os.path.join(tls_configs_dir, name) for name in os.listdir(tls_configs_dir) if name.endswith('options-ssl-apache.conf')] - self.assertTrue(all_files) + self.assertGreaterEqual(len(all_files), 1) for one_file in all_files: file_hash = crypto_util.sha256sum(one_file) - self.assertTrue(file_hash in ALL_SSL_OPTIONS_HASHES, - "Constants.ALL_SSL_OPTIONS_HASHES must be appended with the sha256 " - "hash of {0} when it is updated.".format(one_file)) + self.assertIn( + file_hash, ALL_SSL_OPTIONS_HASHES, + f"Constants.ALL_SSL_OPTIONS_HASHES must be appended with the sha256 " + f"hash of {one_file} when it is updated." + ) def test_openssl_version(self): self.config._openssl_version = None @@ -1786,14 +1768,14 @@ class InstallSslOptionsConfTest(util.ApacheTest): def test_current_version(self): self.config.version = (2, 4, 10) self.config._openssl_version = '1.0.2m' - self.assertTrue('old' in self.config.pick_apache_config()) + self.assertIn('old', self.config.pick_apache_config()) self.config.version = (2, 4, 11) self.config._openssl_version = '1.0.2m' - self.assertTrue('current' in self.config.pick_apache_config()) + self.assertIn('current', self.config.pick_apache_config()) self.config._openssl_version = '1.0.2a' - self.assertTrue('old' in self.config.pick_apache_config()) + self.assertIn('old', self.config.pick_apache_config()) def test_openssl_version_warns(self): self.config._openssl_version = '1.0.2a' @@ -1802,14 +1784,14 @@ class InstallSslOptionsConfTest(util.ApacheTest): self.config._openssl_version = None with mock.patch("certbot_apache._internal.configurator.logger.warning") as mock_log: self.assertEqual(self.config.openssl_version(), None) - self.assertTrue("Could not find ssl_module" in mock_log.call_args[0][0]) + self.assertIn("Could not find ssl_module", mock_log.call_args[0][0]) # When no ssl_module is present at all self.config._openssl_version = None - self.assertTrue("ssl_module" not in self.config.parser.modules) + self.assertNotIn("ssl_module", self.config.parser.modules) with mock.patch("certbot_apache._internal.configurator.logger.warning") as mock_log: self.assertEqual(self.config.openssl_version(), None) - self.assertTrue("Could not find ssl_module" in mock_log.call_args[0][0]) + self.assertIn("Could not find ssl_module", mock_log.call_args[0][0]) # When ssl_module is statically linked but --apache-bin not provided self.config._openssl_version = None @@ -1817,13 +1799,13 @@ class InstallSslOptionsConfTest(util.ApacheTest): self.config.parser.modules['ssl_module'] = None with mock.patch("certbot_apache._internal.configurator.logger.warning") as mock_log: self.assertEqual(self.config.openssl_version(), None) - self.assertTrue("ssl_module is statically linked but" in mock_log.call_args[0][0]) + self.assertIn("ssl_module is statically linked but", mock_log.call_args[0][0]) self.config.parser.modules['ssl_module'] = "/fake/path" 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) - self.assertTrue("Unable to read" in mock_log.call_args[0][0]) + self.assertIn("Unable to read", mock_log.call_args[0][0]) contents_missing_openssl = b"these contents won't match the regex" with mock.patch("certbot_apache._internal.configurator." @@ -1832,7 +1814,7 @@ class InstallSslOptionsConfTest(util.ApacheTest): 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) - self.assertTrue("Could not find OpenSSL" in mock_log.call_args[0][0]) + self.assertIn("Could not find OpenSSL", mock_log.call_args[0][0]) def test_open_module_file(self): mock_open = mock.mock_open(read_data="testing 12 3") diff --git a/certbot-apache/tests/debian_test.py b/certbot-apache/tests/debian_test.py index 35425223b..2bbf40312 100644 --- a/certbot-apache/tests/debian_test.py +++ b/certbot-apache/tests/debian_test.py @@ -45,8 +45,7 @@ class MultipleVhostsTestDebian(util.ApacheTest): def test_enable_mod_unsupported_dirs(self): shutil.rmtree(os.path.join(self.config.parser.root, "mods-enabled")) - self.assertRaises( - errors.NotSupportedError, self.config.enable_mod, "ssl") + self.assertRaises(errors.NotSupportedError, self.config.enable_mod, "ssl") @mock.patch("certbot.util.run_script") @mock.patch("certbot.util.exe_exists") @@ -58,29 +57,29 @@ class MultipleVhostsTestDebian(util.ApacheTest): mock_exe_exists.return_value = True self.config.enable_mod("ssl") - self.assertTrue("ssl_module" in self.config.parser.modules) - self.assertTrue("mod_ssl.c" in self.config.parser.modules) + self.assertIn("ssl_module", self.config.parser.modules) + self.assertIn("mod_ssl.c", self.config.parser.modules) - self.assertTrue(mock_run_script.called) + self.assertIs(mock_run_script.called, True) def test_deploy_cert_enable_new_vhost(self): # Create ssl_vhost = self.config.make_vhost_ssl(self.vh_truth[0]) self.config.parser.modules["ssl_module"] = None self.config.parser.modules["mod_ssl.c"] = None - self.assertFalse(ssl_vhost.enabled) + self.assertIs(ssl_vhost.enabled, False) with certbot_util.patch_display_util(): self.config.deploy_cert( "encryption-example.demo", "example/cert.pem", "example/key.pem", "example/cert_chain.pem", "example/fullchain.pem") - self.assertTrue(ssl_vhost.enabled) + self.assertIs(ssl_vhost.enabled, True) # Make sure that we don't error out if symlink already exists ssl_vhost.enabled = False - self.assertFalse(ssl_vhost.enabled) + self.assertIs(ssl_vhost.enabled, False) self.config.deploy_cert( "encryption-example.demo", "example/cert.pem", "example/key.pem", "example/cert_chain.pem", "example/fullchain.pem") - self.assertTrue(ssl_vhost.enabled) + self.assertIs(ssl_vhost.enabled, True) def test_enable_site_failure(self): self.config.parser.root = "/tmp/nonexistent" @@ -110,8 +109,8 @@ class MultipleVhostsTestDebian(util.ApacheTest): self.config.save() # Verify ssl_module was enabled. - self.assertTrue(self.vh_truth[1].enabled) - self.assertTrue("ssl_module" in self.config.parser.modules) + self.assertIs(self.vh_truth[1].enabled, True) + self.assertIn("ssl_module", self.config.parser.modules) loc_cert = self.config.parser.find_dir( "sslcertificatefile", "example/fullchain.pem", @@ -170,7 +169,7 @@ class MultipleVhostsTestDebian(util.ApacheTest): # This will create an ssl vhost for certbot.demo self.config.choose_vhost("certbot.demo") self.config.enhance("certbot.demo", "staple-ocsp") - self.assertTrue("socache_shmcb_module" in self.config.parser.modules) + self.assertIn("socache_shmcb_module", self.config.parser.modules) @mock.patch("certbot.util.run_script") @mock.patch("certbot.util.exe_exists") @@ -183,7 +182,7 @@ class MultipleVhostsTestDebian(util.ApacheTest): self.config.choose_vhost("certbot.demo") self.config.enhance("certbot.demo", "ensure-http-header", "Strict-Transport-Security") - self.assertTrue("headers_module" in self.config.parser.modules) + self.assertIn("headers_module", self.config.parser.modules) @mock.patch("certbot.util.run_script") @mock.patch("certbot.util.exe_exists") @@ -194,10 +193,10 @@ class MultipleVhostsTestDebian(util.ApacheTest): # This will create an ssl vhost for certbot.demo self.config.choose_vhost("certbot.demo") self.config.enhance("certbot.demo", "redirect") - self.assertTrue("rewrite_module" in self.config.parser.modules) + self.assertIn("rewrite_module", self.config.parser.modules) def test_enable_site_already_enabled(self): - self.assertTrue(self.vh_truth[1].enabled) + self.assertIs(self.vh_truth[1].enabled, True) self.config.enable_site(self.vh_truth[1]) def test_enable_site_call_parent(self): @@ -207,7 +206,7 @@ class MultipleVhostsTestDebian(util.ApacheTest): vh = self.vh_truth[0] vh.enabled = False self.config.enable_site(vh) - self.assertTrue(e_s.called) + self.assertIs(e_s.called, True) @mock.patch("certbot.util.exe_exists") def test_enable_mod_no_disable(self, mock_exe_exists): diff --git a/certbot-apache/tests/display_ops_test.py b/certbot-apache/tests/display_ops_test.py index fc3ab821d..50ab6bfc7 100644 --- a/certbot-apache/tests/display_ops_test.py +++ b/certbot-apache/tests/display_ops_test.py @@ -23,7 +23,7 @@ class SelectVhostMultiTest(unittest.TestCase): self.base_dir, "debian_apache_2_4/multiple_vhosts") def test_select_no_input(self): - self.assertFalse(select_vhost_multiple([])) + self.assertEqual(len(select_vhost_multiple([])), 0) @certbot_util.patch_display_util() def test_select_correct(self, mock_util): @@ -33,15 +33,15 @@ class SelectVhostMultiTest(unittest.TestCase): vhs = select_vhost_multiple([self.vhosts[3], self.vhosts[2], self.vhosts[1]]) - self.assertTrue(self.vhosts[2] in vhs) - self.assertTrue(self.vhosts[3] in vhs) - self.assertFalse(self.vhosts[1] in vhs) + self.assertIn(self.vhosts[2], vhs) + self.assertIn(self.vhosts[3], vhs) + self.assertNotIn(self.vhosts[1], vhs) @certbot_util.patch_display_util() def test_select_cancel(self, mock_util): mock_util().checklist.return_value = (display_util.CANCEL, "whatever") vhs = select_vhost_multiple([self.vhosts[2], self.vhosts[3]]) - self.assertFalse(vhs) + self.assertEqual(vhs, []) class SelectVhostTest(unittest.TestCase): @@ -68,7 +68,7 @@ class SelectVhostTest(unittest.TestCase): try: self._call(self.vhosts) except errors.MissingCommandlineFlag as e: - self.assertTrue("vhost ambiguity" in str(e)) + self.assertIn("vhost ambiguity", str(e)) @certbot_util.patch_display_util() def test_more_info_cancel(self, mock_util): @@ -76,10 +76,10 @@ class SelectVhostTest(unittest.TestCase): (display_util.CANCEL, -1), ] - self.assertEqual(None, self._call(self.vhosts)) + self.assertIsNone(self._call(self.vhosts)) def test_no_vhosts(self): - self.assertEqual(self._call([]), None) + self.assertIsNone(self._call([])) @mock.patch("certbot_apache._internal.display_ops.display_util") @mock.patch("certbot_apache._internal.display_ops.logger") diff --git a/certbot-apache/tests/dualnode_test.py b/certbot-apache/tests/dualnode_test.py index ef7f8b2d8..83a5729a5 100644 --- a/certbot-apache/tests/dualnode_test.py +++ b/certbot-apache/tests/dualnode_test.py @@ -53,20 +53,20 @@ class DualParserNodeTest(unittest.TestCase): # pylint: disable=too-many-public- primary=self.block.secondary, secondary=self.block.primary) # Switched around - self.assertTrue(cnode.primary is self.comment.secondary) - self.assertTrue(cnode.secondary is self.comment.primary) - self.assertTrue(dnode.primary is self.directive.secondary) - self.assertTrue(dnode.secondary is self.directive.primary) - self.assertTrue(bnode.primary is self.block.secondary) - self.assertTrue(bnode.secondary is self.block.primary) + self.assertEqual(cnode.primary, self.comment.secondary) + self.assertEqual(cnode.secondary, self.comment.primary) + self.assertEqual(dnode.primary, self.directive.secondary) + self.assertEqual(dnode.secondary, self.directive.primary) + self.assertEqual(bnode.primary, self.block.secondary) + self.assertEqual(bnode.secondary, self.block.primary) def test_set_params(self): params = ("first", "second") self.directive.primary.set_parameters = mock.Mock() self.directive.secondary.set_parameters = mock.Mock() self.directive.set_parameters(params) - self.assertTrue(self.directive.primary.set_parameters.called) - self.assertTrue(self.directive.secondary.set_parameters.called) + self.assertIs(self.directive.primary.set_parameters.called, True) + self.assertIs(self.directive.secondary.set_parameters.called, True) def test_set_parameters(self): pparams = mock.MagicMock() @@ -76,8 +76,8 @@ class DualParserNodeTest(unittest.TestCase): # pylint: disable=too-many-public- self.directive.primary.set_parameters = pparams self.directive.secondary.set_parameters = sparams self.directive.set_parameters(("param", "seq")) - self.assertTrue(pparams.called) - self.assertTrue(sparams.called) + self.assertIs(pparams.called, True) + self.assertIs(sparams.called, True) def test_delete_child(self): pdel = mock.MagicMock() @@ -85,8 +85,8 @@ class DualParserNodeTest(unittest.TestCase): # pylint: disable=too-many-public- self.block.primary.delete_child = pdel self.block.secondary.delete_child = sdel self.block.delete_child(self.comment) - self.assertTrue(pdel.called) - self.assertTrue(sdel.called) + self.assertIs(pdel.called, True) + self.assertIs(sdel.called, True) def test_unsaved_files(self): puns = mock.MagicMock() @@ -96,8 +96,8 @@ class DualParserNodeTest(unittest.TestCase): # pylint: disable=too-many-public- self.block.primary.unsaved_files = puns self.block.secondary.unsaved_files = suns self.block.unsaved_files() - self.assertTrue(puns.called) - self.assertTrue(suns.called) + self.assertIs(puns.called, True) + self.assertIs(suns.called, True) def test_getattr_equality(self): self.directive.primary.variableexception = "value" @@ -140,8 +140,8 @@ class DualParserNodeTest(unittest.TestCase): # pylint: disable=too-many-public- self.block.primary.add_child_block = mock_first self.block.secondary.add_child_block = mock_second self.block.add_child_block("Block") - self.assertTrue(mock_first.called) - self.assertTrue(mock_second.called) + self.assertIs(mock_first.called, True) + self.assertIs(mock_second.called, True) def test_add_child_directive(self): mock_first = mock.MagicMock(return_value=self.directive.primary) @@ -149,8 +149,8 @@ class DualParserNodeTest(unittest.TestCase): # pylint: disable=too-many-public- self.block.primary.add_child_directive = mock_first self.block.secondary.add_child_directive = mock_second self.block.add_child_directive("Directive") - self.assertTrue(mock_first.called) - self.assertTrue(mock_second.called) + self.assertIs(mock_first.called, True) + self.assertIs(mock_second.called, True) def test_add_child_comment(self): mock_first = mock.MagicMock(return_value=self.comment.primary) @@ -158,8 +158,8 @@ class DualParserNodeTest(unittest.TestCase): # pylint: disable=too-many-public- self.block.primary.add_child_comment = mock_first self.block.secondary.add_child_comment = mock_second self.block.add_child_comment("Comment") - self.assertTrue(mock_first.called) - self.assertTrue(mock_second.called) + self.assertIs(mock_first.called, True) + self.assertIs(mock_second.called, True) def test_find_comments(self): pri_comments = [augeasparser.AugeasCommentNode(comment="some comment", @@ -183,9 +183,9 @@ class DualParserNodeTest(unittest.TestCase): # pylint: disable=too-many-public- # Check that every comment response is represented in the list of # DualParserNode instances. for p in p_dcoms: - self.assertTrue(p in p_coms) + self.assertIn(p, p_coms) for s in s_dcoms: - self.assertTrue(s in s_coms) + self.assertIn(s, s_coms) def test_find_blocks_first_passing(self): youshallnotpass = [augeasparser.AugeasBlockNode(name="notpassing", @@ -207,8 +207,8 @@ class DualParserNodeTest(unittest.TestCase): # pylint: disable=too-many-public- assertions.assertEqual(block.primary, block.secondary) except AssertionError: # pragma: no cover self.fail("Assertion should have passed") - self.assertTrue(assertions.isPassDirective(block.primary)) - self.assertFalse(assertions.isPassDirective(block.secondary)) + self.assertIs(assertions.isPassDirective(block.primary), True) + self.assertIs(assertions.isPassDirective(block.secondary), False) def test_find_blocks_second_passing(self): youshallnotpass = [augeasparser.AugeasBlockNode(name="notpassing", @@ -230,8 +230,8 @@ class DualParserNodeTest(unittest.TestCase): # pylint: disable=too-many-public- assertions.assertEqual(block.primary, block.secondary) except AssertionError: # pragma: no cover self.fail("Assertion should have passed") - self.assertFalse(assertions.isPassDirective(block.primary)) - self.assertTrue(assertions.isPassDirective(block.secondary)) + self.assertIs(assertions.isPassDirective(block.primary), False) + self.assertIs(assertions.isPassDirective(block.secondary), True) def test_find_dirs_first_passing(self): notpassing = [augeasparser.AugeasDirectiveNode(name="notpassing", @@ -253,8 +253,8 @@ class DualParserNodeTest(unittest.TestCase): # pylint: disable=too-many-public- assertions.assertEqual(directive.primary, directive.secondary) except AssertionError: # pragma: no cover self.fail("Assertion should have passed") - self.assertTrue(assertions.isPassDirective(directive.primary)) - self.assertFalse(assertions.isPassDirective(directive.secondary)) + self.assertIs(assertions.isPassDirective(directive.primary), True) + self.assertIs(assertions.isPassDirective(directive.secondary), False) def test_find_dirs_second_passing(self): notpassing = [augeasparser.AugeasDirectiveNode(name="notpassing", @@ -276,8 +276,8 @@ class DualParserNodeTest(unittest.TestCase): # pylint: disable=too-many-public- assertions.assertEqual(directive.primary, directive.secondary) except AssertionError: # pragma: no cover self.fail("Assertion should have passed") - self.assertFalse(assertions.isPassDirective(directive.primary)) - self.assertTrue(assertions.isPassDirective(directive.secondary)) + self.assertIs(assertions.isPassDirective(directive.primary), False) + self.assertIs(assertions.isPassDirective(directive.secondary), True) def test_find_coms_first_passing(self): notpassing = [augeasparser.AugeasCommentNode(comment="notpassing", @@ -299,8 +299,8 @@ class DualParserNodeTest(unittest.TestCase): # pylint: disable=too-many-public- assertions.assertEqual(comment.primary, comment.secondary) except AssertionError: # pragma: no cover self.fail("Assertion should have passed") - self.assertTrue(assertions.isPassComment(comment.primary)) - self.assertFalse(assertions.isPassComment(comment.secondary)) + self.assertIs(assertions.isPassComment(comment.primary), True) + self.assertIs(assertions.isPassComment(comment.secondary), False) def test_find_coms_second_passing(self): notpassing = [augeasparser.AugeasCommentNode(comment="notpassing", @@ -322,8 +322,8 @@ class DualParserNodeTest(unittest.TestCase): # pylint: disable=too-many-public- assertions.assertEqual(comment.primary, comment.secondary) except AssertionError: # pragma: no cover self.fail("Assertion should have passed") - self.assertFalse(assertions.isPassComment(comment.primary)) - self.assertTrue(assertions.isPassComment(comment.secondary)) + self.assertIs(assertions.isPassComment(comment.primary), False) + self.assertIs(assertions.isPassComment(comment.secondary), True) def test_find_blocks_no_pass_equal(self): notpassing1 = [augeasparser.AugeasBlockNode(name="notpassing", @@ -341,8 +341,9 @@ class DualParserNodeTest(unittest.TestCase): # pylint: disable=too-many-public- blocks = self.block.find_blocks("anything") for block in blocks: - self.assertEqual(block.primary, block.secondary) - self.assertTrue(block.primary is not block.secondary) + with self.subTest(block=block): + self.assertEqual(block.primary, block.secondary) + self.assertIsNot(block.primary, block.secondary) def test_find_dirs_no_pass_equal(self): notpassing1 = [augeasparser.AugeasDirectiveNode(name="notpassing", @@ -360,8 +361,9 @@ class DualParserNodeTest(unittest.TestCase): # pylint: disable=too-many-public- directives = self.block.find_directives("anything") for directive in directives: - self.assertEqual(directive.primary, directive.secondary) - self.assertTrue(directive.primary is not directive.secondary) + with self.subTest(directive=directive): + self.assertEqual(directive.primary, directive.secondary) + self.assertIsNot(directive.primary, directive.secondary) def test_find_comments_no_pass_equal(self): notpassing1 = [augeasparser.AugeasCommentNode(comment="notpassing", @@ -379,8 +381,9 @@ class DualParserNodeTest(unittest.TestCase): # pylint: disable=too-many-public- comments = self.block.find_comments("anything") for comment in comments: - self.assertEqual(comment.primary, comment.secondary) - self.assertTrue(comment.primary is not comment.secondary) + with self.subTest(comment=comment): + self.assertEqual(comment.primary, comment.secondary) + self.assertIsNot(comment.primary, comment.secondary) def test_find_blocks_no_pass_notequal(self): notpassing1 = [augeasparser.AugeasBlockNode(name="notpassing", @@ -424,8 +427,8 @@ class DualParserNodeTest(unittest.TestCase): # pylint: disable=too-many-public- self.block.primary.parsed_paths = mock_p self.block.secondary.parsed_paths = mock_s self.block.parsed_paths() - self.assertTrue(mock_p.called) - self.assertTrue(mock_s.called) + self.assertIs(mock_p.called, True) + self.assertIs(mock_s.called, True) def test_parsed_paths_error(self): mock_p = mock.MagicMock(return_value=['/path/file.conf']) @@ -441,5 +444,5 @@ class DualParserNodeTest(unittest.TestCase): # pylint: disable=too-many-public- self.block.primary.find_ancestors = primarymock self.block.secondary.find_ancestors = secondarymock self.block.find_ancestors("anything") - self.assertTrue(primarymock.called) - self.assertTrue(secondarymock.called) + self.assertIs(primarymock.called, True) + self.assertIs(secondarymock.called, True) diff --git a/certbot-apache/tests/fedora_test.py b/certbot-apache/tests/fedora_test.py index d48559cee..fca3c4ba4 100644 --- a/certbot-apache/tests/fedora_test.py +++ b/certbot-apache/tests/fedora_test.py @@ -134,8 +134,8 @@ class MultipleVhostsTestFedora(util.ApacheTest): self.assertEqual(mock_get.call_count, 3) self.assertEqual(len(self.config.parser.modules), 4) self.assertEqual(len(self.config.parser.variables), 2) - self.assertTrue("TEST2" in self.config.parser.variables) - self.assertTrue("mod_another.c" in self.config.parser.modules) + self.assertIn("TEST2", self.config.parser.variables) + self.assertIn("mod_another.c", self.config.parser.modules) @mock.patch("certbot_apache._internal.configurator.util.run_script") def test_get_version(self, mock_run_script): @@ -172,11 +172,11 @@ class MultipleVhostsTestFedora(util.ApacheTest): mock_osi.return_value = ("fedora", "29") self.config.parser.update_runtime_variables() - self.assertTrue("mock_define" in self.config.parser.variables) - self.assertTrue("mock_define_too" in self.config.parser.variables) - self.assertTrue("mock_value" in self.config.parser.variables) + self.assertIn("mock_define", self.config.parser.variables) + self.assertIn("mock_define_too", self.config.parser.variables) + self.assertIn("mock_value", self.config.parser.variables) self.assertEqual("TRUE", self.config.parser.variables["mock_value"]) - self.assertTrue("MOCK_NOSEP" in self.config.parser.variables) + self.assertIn("MOCK_NOSEP", self.config.parser.variables) self.assertEqual("NOSEP_VAL", self.config.parser.variables["NOSEP_TWO"]) @mock.patch("certbot_apache._internal.configurator.util.run_script") diff --git a/certbot-apache/tests/gentoo_test.py b/certbot-apache/tests/gentoo_test.py index cf39ff5cb..25f9e929b 100644 --- a/certbot-apache/tests/gentoo_test.py +++ b/certbot-apache/tests/gentoo_test.py @@ -63,8 +63,7 @@ class MultipleVhostsTestGentoo(util.ApacheTest): self.temp_dir, "gentoo_apache/apache") def test_get_parser(self): - self.assertTrue(isinstance(self.config.parser, - override_gentoo.GentooParser)) + self.assertIsInstance(self.config.parser, override_gentoo.GentooParser) def test_get_virtual_hosts(self): """Make sure all vhosts are being properly found.""" @@ -91,7 +90,7 @@ class MultipleVhostsTestGentoo(util.ApacheTest): with mock.patch("certbot_apache._internal.override_gentoo.GentooParser.update_modules"): self.config.parser.update_runtime_variables() for define in defines: - self.assertTrue(define in self.config.parser.variables) + self.assertIn(define, self.config.parser.variables) @mock.patch("certbot_apache._internal.apache_util.parse_from_subprocess") def test_no_binary_configdump(self, mock_subprocess): @@ -101,11 +100,11 @@ class MultipleVhostsTestGentoo(util.ApacheTest): with mock.patch("certbot_apache._internal.override_gentoo.GentooParser.update_modules"): self.config.parser.update_runtime_variables() self.config.parser.reset_modules() - self.assertFalse(mock_subprocess.called) + self.assertIs(mock_subprocess.called, False) self.config.parser.update_runtime_variables() self.config.parser.reset_modules() - self.assertTrue(mock_subprocess.called) + self.assertIs(mock_subprocess.called, True) @mock.patch("certbot_apache._internal.apache_util._get_runtime_cfg") def test_opportunistic_httpd_runtime_parsing(self, mock_get): @@ -129,7 +128,7 @@ class MultipleVhostsTestGentoo(util.ApacheTest): self.assertEqual(mock_get.call_count, 1) self.assertEqual(len(self.config.parser.modules), 4) - self.assertTrue("mod_another.c" in self.config.parser.modules) + self.assertIn("mod_another.c", self.config.parser.modules) @mock.patch("certbot_apache._internal.configurator.util.run_script") def test_alt_restart_works(self, mock_run_script): diff --git a/certbot-apache/tests/http_01_test.py b/certbot-apache/tests/http_01_test.py index 1ce47ed1a..9085f68dc 100644 --- a/certbot-apache/tests/http_01_test.py +++ b/certbot-apache/tests/http_01_test.py @@ -51,7 +51,7 @@ class ApacheHttp01Test(util.ApacheTest): self.http = ApacheHttp01(self.config) def test_empty_perform(self): - self.assertFalse(self.http.perform()) + self.assertEqual(len(self.http.perform()), 0) @mock.patch("certbot_apache._internal.configurator.ApacheConfigurator.enable_mod") def test_enable_modules_apache_2_2(self, mock_enmod): @@ -77,7 +77,7 @@ class ApacheHttp01Test(util.ApacheTest): self.http.prepare_http01_modules() - self.assertTrue(mock_enmod.called) + self.assertIs(mock_enmod.called, True) calls = mock_enmod.call_args_list other_calls = [] for call in calls: @@ -186,7 +186,7 @@ class ApacheHttp01Test(util.ApacheTest): def common_perform_test(self, achalls, vhosts): """Tests perform with the given achalls.""" challenge_dir = self.http.challenge_dir - self.assertFalse(os.path.exists(challenge_dir)) + self.assertIs(os.path.exists(challenge_dir), False) for achall in achalls: self.http.add_chall(achall) @@ -194,8 +194,8 @@ class ApacheHttp01Test(util.ApacheTest): achall.response(self.account_key) for achall in achalls] self.assertEqual(self.http.perform(), expected_response) - self.assertTrue(os.path.isdir(self.http.challenge_dir)) - self.assertTrue(filesystem.has_min_permissions(self.http.challenge_dir, 0o755)) + self.assertIs(os.path.isdir(self.http.challenge_dir), True) + self.assertIs(filesystem.has_min_permissions(self.http.challenge_dir, 0o755), True) self._test_challenge_conf() for achall in achalls: @@ -211,7 +211,7 @@ class ApacheHttp01Test(util.ApacheTest): vhost.path) self.assertEqual(len(matches), 1) - self.assertTrue(os.path.exists(challenge_dir)) + self.assertIs(os.path.exists(challenge_dir), True) @mock.patch("certbot_apache._internal.http_01.filesystem.makedirs") def test_failed_makedirs(self, mock_makedirs): @@ -226,20 +226,20 @@ class ApacheHttp01Test(util.ApacheTest): with open(self.http.challenge_conf_post) as f: post_conf_contents = f.read() - self.assertTrue("RewriteEngine on" in pre_conf_contents) - self.assertTrue("RewriteRule" in pre_conf_contents) + self.assertIn("RewriteEngine on", pre_conf_contents) + self.assertIn("RewriteRule", pre_conf_contents) - self.assertTrue(self.http.challenge_dir in post_conf_contents) + self.assertIn(self.http.challenge_dir, post_conf_contents) if self.config.version < (2, 4): - self.assertTrue("Allow from all" in post_conf_contents) + self.assertIn("Allow from all", post_conf_contents) else: - self.assertTrue("Require all granted" in post_conf_contents) + self.assertIn("Require all granted", post_conf_contents) def _test_challenge_file(self, achall): name = os.path.join(self.http.challenge_dir, achall.chall.encode("token")) validation = achall.validation(self.account_key) - self.assertTrue(filesystem.has_min_permissions(name, 0o644)) + self.assertIs(filesystem.has_min_permissions(name, 0o644), True) with open(name, 'rb') as f: self.assertEqual(f.read(), validation.encode()) diff --git a/certbot-apache/tests/obj_test.py b/certbot-apache/tests/obj_test.py index 8aae3ad45..411ec21e9 100644 --- a/certbot-apache/tests/obj_test.py +++ b/certbot-apache/tests/obj_test.py @@ -44,15 +44,14 @@ class VirtualHostTest(unittest.TestCase): "fp", "vhp", {Addr.fromstring("*:443"), Addr.fromstring("1.2.3.4:443")}, False, False) - self.assertTrue(complex_vh.conflicts([self.addr1])) - self.assertTrue(complex_vh.conflicts([self.addr2])) - self.assertFalse(complex_vh.conflicts([self.addr_default])) + self.assertIs(complex_vh.conflicts([self.addr1]), True) + self.assertIs(complex_vh.conflicts([self.addr2]), True) + self.assertIs(complex_vh.conflicts([self.addr_default]), False) - self.assertTrue(self.vhost1.conflicts([self.addr2])) - self.assertFalse(self.vhost1.conflicts([self.addr_default])) + self.assertIs(self.vhost1.conflicts([self.addr2]), True) + self.assertIs(self.vhost1.conflicts([self.addr_default]), False) - self.assertFalse(self.vhost2.conflicts([self.addr1, - self.addr_default])) + self.assertIs(self.vhost2.conflicts([self.addr1, self.addr_default]), False) def test_same_server(self): from certbot_apache._internal.obj import VirtualHost @@ -67,12 +66,12 @@ class VirtualHostTest(unittest.TestCase): "fp", "vhp", {self.addr2, self.addr_default}, False, False, None) - self.assertTrue(self.vhost1.same_server(self.vhost2)) - self.assertTrue(no_name1.same_server(no_name2)) + self.assertIs(self.vhost1.same_server(self.vhost2), True) + self.assertIs(no_name1.same_server(no_name2), True) - self.assertFalse(self.vhost1.same_server(no_name1)) - self.assertFalse(no_name1.same_server(no_name3)) - self.assertFalse(no_name1.same_server(no_name4)) + self.assertIs(self.vhost1.same_server(no_name1), False) + self.assertIs(no_name1.same_server(no_name3), False) + self.assertIs(no_name1.same_server(no_name4), False) class AddrTest(unittest.TestCase): @@ -88,9 +87,9 @@ class AddrTest(unittest.TestCase): self.addr_default = Addr.fromstring("_default_:443") def test_wildcard(self): - self.assertFalse(self.addr.is_wildcard()) - self.assertTrue(self.addr1.is_wildcard()) - self.assertTrue(self.addr2.is_wildcard()) + self.assertIs(self.addr.is_wildcard(), False) + self.assertIs(self.addr1.is_wildcard(), True) + self.assertIs(self.addr2.is_wildcard(), True) def test_get_sni_addr(self): from certbot_apache._internal.obj import Addr @@ -103,29 +102,29 @@ class AddrTest(unittest.TestCase): def test_conflicts(self): # Note: Defined IP is more important than defined port in match - self.assertTrue(self.addr.conflicts(self.addr1)) - self.assertTrue(self.addr.conflicts(self.addr2)) - self.assertTrue(self.addr.conflicts(self.addr_defined)) - self.assertFalse(self.addr.conflicts(self.addr_default)) + self.assertIs(self.addr.conflicts(self.addr1), True) + self.assertIs(self.addr.conflicts(self.addr2), True) + self.assertIs(self.addr.conflicts(self.addr_defined), True) + self.assertIs(self.addr.conflicts(self.addr_default), False) - self.assertFalse(self.addr1.conflicts(self.addr)) - self.assertTrue(self.addr1.conflicts(self.addr_defined)) - self.assertFalse(self.addr1.conflicts(self.addr_default)) + self.assertIs(self.addr1.conflicts(self.addr), False) + self.assertIs(self.addr1.conflicts(self.addr_defined), True) + self.assertIs(self.addr1.conflicts(self.addr_default), False) - self.assertFalse(self.addr_defined.conflicts(self.addr1)) - self.assertFalse(self.addr_defined.conflicts(self.addr2)) - self.assertFalse(self.addr_defined.conflicts(self.addr)) - self.assertFalse(self.addr_defined.conflicts(self.addr_default)) + self.assertIs(self.addr_defined.conflicts(self.addr1), False) + self.assertIs(self.addr_defined.conflicts(self.addr2), False) + self.assertIs(self.addr_defined.conflicts(self.addr), False) + self.assertIs(self.addr_defined.conflicts(self.addr_default), False) - self.assertTrue(self.addr_default.conflicts(self.addr)) - self.assertTrue(self.addr_default.conflicts(self.addr1)) - self.assertTrue(self.addr_default.conflicts(self.addr_defined)) + self.assertIs(self.addr_default.conflicts(self.addr), True) + self.assertIs(self.addr_default.conflicts(self.addr1), True) + self.assertIs(self.addr_default.conflicts(self.addr_defined), True) # Self test - self.assertTrue(self.addr.conflicts(self.addr)) - self.assertTrue(self.addr1.conflicts(self.addr1)) + self.assertIs(self.addr.conflicts(self.addr), True) + self.assertIs(self.addr1.conflicts(self.addr1), True) # This is a tricky one... - self.assertTrue(self.addr1.conflicts(self.addr2)) + self.assertIs(self.addr1.conflicts(self.addr2), True) def test_equal(self): self.assertEqual(self.addr1, self.addr2) diff --git a/certbot-apache/tests/parser_test.py b/certbot-apache/tests/parser_test.py index 61855fdb7..5166d9e0e 100644 --- a/certbot-apache/tests/parser_test.py +++ b/certbot-apache/tests/parser_test.py @@ -42,7 +42,7 @@ class BasicParserTest(util.ParserTest): self.assertEqual(self.parser.check_aug_version(), ["something"]) self.parser.aug.match.side_effect = RuntimeError - self.assertFalse(self.parser.check_aug_version()) + self.assertIs(self.parser.check_aug_version(), False) def test_find_config_root_no_root(self): # pylint: disable=protected-access @@ -80,8 +80,7 @@ class BasicParserTest(util.ParserTest): aug_default = "/files" + self.parser.loc["default"] self.parser.add_dir(aug_default, "AddDirective", "test") - self.assertTrue( - self.parser.find_dir("AddDirective", "test", aug_default)) + self.assertTrue(self.parser.find_dir("AddDirective", "test", aug_default)) self.parser.add_dir(aug_default, "AddList", ["1", "2", "3", "4"]) matches = self.parser.find_dir("AddList", None, aug_default) @@ -94,12 +93,9 @@ class BasicParserTest(util.ParserTest): "AddDirectiveBeginning", "testBegin") - self.assertTrue( - self.parser.find_dir("AddDirectiveBeginning", "testBegin", aug_default)) + self.assertTrue(self.parser.find_dir("AddDirectiveBeginning", "testBegin", aug_default)) - self.assertEqual( - self.parser.aug.get(aug_default+"/directive[1]"), - "AddDirectiveBeginning") + self.assertEqual(self.parser.aug.get(aug_default+"/directive[1]"), "AddDirectiveBeginning") self.parser.add_dir_beginning(aug_default, "AddList", ["1", "2", "3", "4"]) matches = self.parser.find_dir("AddList", None, aug_default) for i, match in enumerate(matches): @@ -108,11 +104,13 @@ class BasicParserTest(util.ParserTest): for name in ("empty.conf", "no-directives.conf"): conf = "/files" + os.path.join(self.parser.root, "sites-available", name) self.parser.add_dir_beginning(conf, "AddDirectiveBeginning", "testBegin") - self.assertTrue(self.parser.find_dir("AddDirectiveBeginning", "testBegin", conf)) + self.assertGreater( + len(self.parser.find_dir("AddDirectiveBeginning", "testBegin", conf)), + 0 + ) def test_empty_arg(self): - self.assertEqual(None, - self.parser.get_arg("/files/whatever/nonexistent")) + self.assertIsNone(self.parser.get_arg("/files/whatever/nonexistent")) def test_add_dir_to_ifmodssl(self): """test add_dir_to_ifmodssl. @@ -131,7 +129,7 @@ class BasicParserTest(util.ParserTest): matches = self.parser.find_dir("FakeDirective", "123") self.assertEqual(len(matches), 1) - self.assertTrue("IfModule" in matches[0]) + self.assertIn("IfModule", matches[0]) def test_add_dir_to_ifmodssl_multiple(self): from certbot_apache._internal.parser import get_aug_path @@ -145,7 +143,7 @@ class BasicParserTest(util.ParserTest): matches = self.parser.find_dir("FakeDirective") self.assertEqual(len(matches), 3) - self.assertTrue("IfModule" in matches[0]) + self.assertIn("IfModule", matches[0]) def test_get_aug_path(self): from certbot_apache._internal.parser import get_aug_path @@ -170,7 +168,7 @@ class BasicParserTest(util.ParserTest): with mock.patch("certbot_apache._internal.parser.logger") as mock_logger: self.parser.parse_modules() # Make sure that we got None return value and logged the file - self.assertTrue(mock_logger.debug.called) + self.assertIs(mock_logger.debug.called, True) @mock.patch("certbot_apache._internal.parser.ApacheParser.find_dir") @mock.patch("certbot_apache._internal.apache_util._get_runtime_cfg") @@ -328,7 +326,7 @@ class BasicParserTest(util.ParserTest): self.parser.add_comment(get_aug_path(self.parser.loc["name"]), "123456") comm = self.parser.find_comments("123456") self.assertEqual(len(comm), 1) - self.assertTrue(self.parser.loc["name"] in comm[0]) + self.assertIn(self.parser.loc["name"], comm[0]) class ParserInitTest(util.ApacheTest): diff --git a/certbot-apache/tests/parsernode_configurator_test.py b/certbot-apache/tests/parsernode_configurator_test.py index 411871a43..ebeda3c37 100644 --- a/certbot-apache/tests/parsernode_configurator_test.py +++ b/certbot-apache/tests/parsernode_configurator_test.py @@ -32,7 +32,7 @@ class ConfiguratorParserNodeTest(util.ApacheTest): # pylint: disable=too-many-p self.config.USE_PARSERNODE = True vhosts = self.config.get_virtual_hosts() # Legacy get_virtual_hosts() do not set the node - self.assertTrue(vhosts[0].node is not None) + self.assertIsNotNone(vhosts[0].node) def test_parsernode_get_vhosts_mismatch(self): vhosts = self.config.get_virtual_hosts_v2() diff --git a/certbot-apache/tests/util.py b/certbot-apache/tests/util.py index b9e7d2ea0..f0c76e693 100644 --- a/certbot-apache/tests/util.py +++ b/certbot-apache/tests/util.py @@ -1,6 +1,5 @@ """Common utilities for certbot_apache.""" import shutil -import sys import unittest import augeas @@ -14,7 +13,6 @@ except ImportError: # pragma: no cover from certbot.compat import os from certbot.plugins import common from certbot.tests import util as test_util -from certbot.display import util as display_util from certbot_apache._internal import configurator from certbot_apache._internal import entrypoint from certbot_apache._internal import obj |