Improve assertions in nginx and DNS plugin tests. (#9157)

* Improve assertions in nginx and DNS plugin tests.

* Use assertIs for asserting is True/False.
This commit is contained in:
Mads Jensen
2022-01-04 23:59:58 +01:00
committed by GitHub
parent 97a09dee19
commit ed7964b424
10 changed files with 82 additions and 66 deletions
+8 -7
View File
@@ -184,9 +184,9 @@ class GoogleClientTest(unittest.TestCase):
with mock.patch(mock_get_rrs) as mock_rrs: with mock.patch(mock_get_rrs) as mock_rrs:
mock_rrs.return_value = {"rrdatas": ["sample-txt-contents"], "ttl": self.record_ttl} mock_rrs.return_value = {"rrdatas": ["sample-txt-contents"], "ttl": self.record_ttl}
client.add_txt_record(DOMAIN, self.record_name, self.record_content, self.record_ttl) client.add_txt_record(DOMAIN, self.record_name, self.record_content, self.record_ttl)
self.assertTrue(changes.create.called) self.assertIs(changes.create.called, True)
deletions = changes.create.call_args_list[0][1]["body"]["deletions"][0] deletions = changes.create.call_args_list[0][1]["body"]["deletions"][0]
self.assertTrue("sample-txt-contents" in deletions["rrdatas"]) self.assertIn("sample-txt-contents", deletions["rrdatas"])
self.assertEqual(self.record_ttl, deletions["ttl"]) self.assertEqual(self.record_ttl, deletions["ttl"])
@mock.patch('oauth2client.service_account.ServiceAccountCredentials.from_json_keyfile_name') @mock.patch('oauth2client.service_account.ServiceAccountCredentials.from_json_keyfile_name')
@@ -201,9 +201,9 @@ class GoogleClientTest(unittest.TestCase):
custom_ttl = 300 custom_ttl = 300
mock_rrs.return_value = {"rrdatas": ["sample-txt-contents"], "ttl": custom_ttl} mock_rrs.return_value = {"rrdatas": ["sample-txt-contents"], "ttl": custom_ttl}
client.add_txt_record(DOMAIN, self.record_name, self.record_content, self.record_ttl) client.add_txt_record(DOMAIN, self.record_name, self.record_content, self.record_ttl)
self.assertTrue(changes.create.called) self.assertIs(changes.create.called, True)
deletions = changes.create.call_args_list[0][1]["body"]["deletions"][0] deletions = changes.create.call_args_list[0][1]["body"]["deletions"][0]
self.assertTrue("sample-txt-contents" in deletions["rrdatas"]) self.assertIn("sample-txt-contents", deletions["rrdatas"])
self.assertEqual(custom_ttl, deletions["ttl"]) #otherwise HTTP 412 self.assertEqual(custom_ttl, deletions["ttl"]) #otherwise HTTP 412
@mock.patch('oauth2client.service_account.ServiceAccountCredentials.from_json_keyfile_name') @mock.patch('oauth2client.service_account.ServiceAccountCredentials.from_json_keyfile_name')
@@ -214,7 +214,7 @@ class GoogleClientTest(unittest.TestCase):
[{'managedZones': [{'id': self.zone}]}]) [{'managedZones': [{'id': self.zone}]}])
client.add_txt_record(DOMAIN, "_acme-challenge.example.org", client.add_txt_record(DOMAIN, "_acme-challenge.example.org",
"example-txt-contents", self.record_ttl) "example-txt-contents", self.record_ttl)
self.assertFalse(changes.create.called) self.assertIs(changes.create.called, False)
@mock.patch('oauth2client.service_account.ServiceAccountCredentials.from_json_keyfile_name') @mock.patch('oauth2client.service_account.ServiceAccountCredentials.from_json_keyfile_name')
@mock.patch('certbot_dns_google._internal.dns_google.open', @mock.patch('certbot_dns_google._internal.dns_google.open',
@@ -357,7 +357,7 @@ class GoogleClientTest(unittest.TestCase):
client, unused_changes = self._setUp_client_with_mock( client, unused_changes = self._setUp_client_with_mock(
[{'managedZones': [{'id': self.zone}]}]) [{'managedZones': [{'id': self.zone}]}])
not_found = client.get_existing_txt_rrset(self.zone, "nonexistent.tld") not_found = client.get_existing_txt_rrset(self.zone, "nonexistent.tld")
self.assertEqual(not_found, None) self.assertIsNone(not_found)
@mock.patch('oauth2client.service_account.ServiceAccountCredentials.from_json_keyfile_name') @mock.patch('oauth2client.service_account.ServiceAccountCredentials.from_json_keyfile_name')
@mock.patch('certbot_dns_google._internal.dns_google.open', @mock.patch('certbot_dns_google._internal.dns_google.open',
@@ -367,7 +367,7 @@ class GoogleClientTest(unittest.TestCase):
[{'managedZones': [{'id': self.zone}]}], API_ERROR) [{'managedZones': [{'id': self.zone}]}], API_ERROR)
# Record name mocked in setUp # Record name mocked in setUp
found = client.get_existing_txt_rrset(self.zone, "_acme-challenge.example.org") found = client.get_existing_txt_rrset(self.zone, "_acme-challenge.example.org")
self.assertEqual(found, None) self.assertIsNone(found)
@mock.patch('oauth2client.service_account.ServiceAccountCredentials.from_json_keyfile_name') @mock.patch('oauth2client.service_account.ServiceAccountCredentials.from_json_keyfile_name')
@mock.patch('certbot_dns_google._internal.dns_google.open', @mock.patch('certbot_dns_google._internal.dns_google.open',
@@ -411,5 +411,6 @@ class DummyResponse:
def __init__(self): def __init__(self):
self.status = 200 self.status = 200
if __name__ == "__main__": if __name__ == "__main__":
unittest.main() # pragma: no cover unittest.main() # pragma: no cover
@@ -18,6 +18,7 @@ TOKEN = 'a-token'
TOKEN_V3 = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ64' TOKEN_V3 = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ64'
TOKEN_V4 = '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef' TOKEN_V4 = '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef'
class AuthenticatorTest(test_util.TempDirTestCase, class AuthenticatorTest(test_util.TempDirTestCase,
dns_test_common_lexicon.BaseLexiconAuthenticatorTest): dns_test_common_lexicon.BaseLexiconAuthenticatorTest):
@@ -119,6 +120,7 @@ class AuthenticatorTest(test_util.TempDirTestCase,
auth._setup_credentials() auth._setup_credentials()
self.assertRaises(errors.PluginError, auth._get_linode_client) self.assertRaises(errors.PluginError, auth._get_linode_client)
class LinodeLexiconClientTest(unittest.TestCase, dns_test_common_lexicon.BaseLexiconClientTest): class LinodeLexiconClientTest(unittest.TestCase, dns_test_common_lexicon.BaseLexiconClientTest):
DOMAIN_NOT_FOUND = Exception('Domain not found') DOMAIN_NOT_FOUND = Exception('Domain not found')
@@ -131,6 +133,7 @@ class LinodeLexiconClientTest(unittest.TestCase, dns_test_common_lexicon.BaseLex
self.provider_mock = mock.MagicMock() self.provider_mock = mock.MagicMock()
self.client.provider = self.provider_mock self.client.provider = self.provider_mock
class Linode4LexiconClientTest(unittest.TestCase, dns_test_common_lexicon.BaseLexiconClientTest): class Linode4LexiconClientTest(unittest.TestCase, dns_test_common_lexicon.BaseLexiconClientTest):
DOMAIN_NOT_FOUND = Exception('Domain not found') DOMAIN_NOT_FOUND = Exception('Domain not found')
@@ -143,5 +146,6 @@ class Linode4LexiconClientTest(unittest.TestCase, dns_test_common_lexicon.BaseLe
self.provider_mock = mock.MagicMock() self.provider_mock = mock.MagicMock()
self.client.provider = self.provider_mock self.client.provider = self.provider_mock
if __name__ == "__main__": if __name__ == "__main__":
unittest.main() # pragma: no cover unittest.main() # pragma: no cover
@@ -23,6 +23,7 @@ SECRET = 'SSB3b25kZXIgd2hvIHdpbGwgYm90aGVyIHRvIGRlY29kZSB0aGlzIHRleHQK'
VALID_CONFIG = {"rfc2136_server": SERVER, "rfc2136_name": NAME, "rfc2136_secret": SECRET} VALID_CONFIG = {"rfc2136_server": SERVER, "rfc2136_name": NAME, "rfc2136_secret": SECRET}
TIMEOUT = 45 TIMEOUT = 45
class AuthenticatorTest(test_util.TempDirTestCase, dns_test_common.BaseAuthenticatorTest): class AuthenticatorTest(test_util.TempDirTestCase, dns_test_common.BaseAuthenticatorTest):
def setUp(self): def setUp(self):
@@ -113,7 +114,7 @@ class RFC2136ClientTest(unittest.TestCase):
self.rfc2136_client.add_txt_record("bar", "baz", 42) self.rfc2136_client.add_txt_record("bar", "baz", 42)
query_mock.assert_called_with(mock.ANY, SERVER, TIMEOUT, PORT) query_mock.assert_called_with(mock.ANY, SERVER, TIMEOUT, PORT)
self.assertTrue("bar. 42 IN TXT \"baz\"" in str(query_mock.call_args[0][0])) self.assertIn('bar. 42 IN TXT "baz"', str(query_mock.call_args[0][0]))
@mock.patch("dns.query.tcp") @mock.patch("dns.query.tcp")
def test_add_txt_record_wraps_errors(self, query_mock): def test_add_txt_record_wraps_errors(self, query_mock):
@@ -146,7 +147,7 @@ class RFC2136ClientTest(unittest.TestCase):
self.rfc2136_client.del_txt_record("bar", "baz") self.rfc2136_client.del_txt_record("bar", "baz")
query_mock.assert_called_with(mock.ANY, SERVER, TIMEOUT, PORT) query_mock.assert_called_with(mock.ANY, SERVER, TIMEOUT, PORT)
self.assertTrue("bar. 0 NONE TXT \"baz\"" in str(query_mock.call_args[0][0])) self.assertIn('bar. 0 NONE TXT "baz"', str(query_mock.call_args[0][0]))
@mock.patch("dns.query.tcp") @mock.patch("dns.query.tcp")
def test_del_txt_record_wraps_errors(self, query_mock): def test_del_txt_record_wraps_errors(self, query_mock):
+25 -21
View File
@@ -24,7 +24,6 @@ import test_util as util
class NginxConfiguratorTest(util.NginxTest): class NginxConfiguratorTest(util.NginxTest):
"""Test a semi complex vhost configuration.""" """Test a semi complex vhost configuration."""
def setUp(self): def setUp(self):
super().setUp() super().setUp()
@@ -79,8 +78,8 @@ class NginxConfiguratorTest(util.NginxTest):
self.config.prepare() self.config.prepare()
except errors.PluginError as err: except errors.PluginError as err:
err_msg = str(err) err_msg = str(err)
self.assertTrue("lock" in err_msg) self.assertIn("lock", err_msg)
self.assertTrue(self.config.conf("server-root") in err_msg) self.assertIn(self.config.conf("server-root"), err_msg)
else: # pragma: no cover else: # pragma: no cover
self.fail("Exception wasn't raised!") self.fail("Exception wasn't raised!")
@@ -192,8 +191,9 @@ class NginxConfiguratorTest(util.NginxTest):
'69.255.225.155'] '69.255.225.155']
for name in bad_results: for name in bad_results:
self.assertRaises(errors.MisconfigurationError, with self.subTest(name=name):
self.config.choose_vhosts, name) self.assertRaises(errors.MisconfigurationError,
self.config.choose_vhosts, name)
def test_ipv6only(self): def test_ipv6only(self):
# ipv6_info: (ipv6_active, ipv6only_present) # ipv6_info: (ipv6_active, ipv6only_present)
@@ -215,7 +215,7 @@ class NginxConfiguratorTest(util.NginxTest):
self.assertFalse(addr.ipv6only) self.assertFalse(addr.ipv6only)
def test_more_info(self): def test_more_info(self):
self.assertTrue('nginx.conf' in self.config.more_info()) self.assertIn('nginx.conf', self.config.more_info())
def test_deploy_cert_requires_fullchain_path(self): def test_deploy_cert_requires_fullchain_path(self):
self.config.version = (1, 3, 1) self.config.version = (1, 3, 1)
@@ -547,7 +547,7 @@ class NginxConfiguratorTest(util.NginxTest):
self.config.enhance("www.example.com", "redirect") self.config.enhance("www.example.com", "redirect")
generated_conf = self.config.parser.parsed[example_conf] generated_conf = self.config.parser.parsed[example_conf]
self.assertTrue(util.contains_at_depth(generated_conf, expected, 2)) self.assertIs(util.contains_at_depth(generated_conf, expected, 2), True)
# Test that we successfully add a redirect when there is # Test that we successfully add a redirect when there is
# no listen directive # no listen directive
@@ -557,7 +557,7 @@ class NginxConfiguratorTest(util.NginxTest):
expected = UnspacedList(_redirect_block_for_domain("migration.com"))[0] expected = UnspacedList(_redirect_block_for_domain("migration.com"))[0]
generated_conf = self.config.parser.parsed[migration_conf] generated_conf = self.config.parser.parsed[migration_conf]
self.assertTrue(util.contains_at_depth(generated_conf, expected, 2)) self.assertIs(util.contains_at_depth(generated_conf, expected, 2), True)
def test_split_for_redirect(self): def test_split_for_redirect(self):
example_conf = self.config.parser.abs_path('sites-enabled/example.com') example_conf = self.config.parser.abs_path('sites-enabled/example.com')
@@ -627,7 +627,7 @@ class NginxConfiguratorTest(util.NginxTest):
"Strict-Transport-Security") "Strict-Transport-Security")
expected = ['add_header', 'Strict-Transport-Security', '"max-age=31536000"', 'always'] expected = ['add_header', 'Strict-Transport-Security', '"max-age=31536000"', 'always']
generated_conf = self.config.parser.parsed[example_conf] generated_conf = self.config.parser.parsed[example_conf]
self.assertTrue(util.contains_at_depth(generated_conf, expected, 2)) self.assertIs(util.contains_at_depth(generated_conf, expected, 2), True)
def test_multiple_headers_hsts(self): def test_multiple_headers_hsts(self):
headers_conf = self.config.parser.abs_path('sites-enabled/headers.com') headers_conf = self.config.parser.abs_path('sites-enabled/headers.com')
@@ -635,7 +635,7 @@ class NginxConfiguratorTest(util.NginxTest):
"Strict-Transport-Security") "Strict-Transport-Security")
expected = ['add_header', 'Strict-Transport-Security', '"max-age=31536000"', 'always'] expected = ['add_header', 'Strict-Transport-Security', '"max-age=31536000"', 'always']
generated_conf = self.config.parser.parsed[headers_conf] generated_conf = self.config.parser.parsed[headers_conf]
self.assertTrue(util.contains_at_depth(generated_conf, expected, 2)) self.assertIs(util.contains_at_depth(generated_conf, expected, 2), True)
def test_http_header_hsts_twice(self): def test_http_header_hsts_twice(self):
self.config.enhance("www.example.com", "ensure-http-header", self.config.enhance("www.example.com", "ensure-http-header",
@@ -645,7 +645,6 @@ class NginxConfiguratorTest(util.NginxTest):
self.config.enhance, "www.example.com", self.config.enhance, "www.example.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_nginx._internal.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
@@ -867,7 +866,7 @@ class NginxConfiguratorTest(util.NginxTest):
vhs = self.config._choose_vhosts_wildcard("*.com", vhs = self.config._choose_vhosts_wildcard("*.com",
prefer_ssl=True) prefer_ssl=True)
# Check that the dialog was called with migration.com # Check that the dialog was called with migration.com
self.assertTrue(vhost in mock_select_vhs.call_args[0][0]) self.assertIn(vhost, mock_select_vhs.call_args[0][0])
# And the actual returned values # And the actual returned values
self.assertEqual(len(vhs), 1) self.assertEqual(len(vhs), 1)
@@ -883,7 +882,7 @@ class NginxConfiguratorTest(util.NginxTest):
vhs = self.config._choose_vhosts_wildcard("*.com", vhs = self.config._choose_vhosts_wildcard("*.com",
prefer_ssl=False) prefer_ssl=False)
# Check that the dialog was called with migration.com # Check that the dialog was called with migration.com
self.assertTrue(vhost in mock_select_vhs.call_args[0][0]) self.assertIn(vhost, mock_select_vhs.call_args[0][0])
# And the actual returned values # And the actual returned values
self.assertEqual(len(vhs), 1) self.assertEqual(len(vhs), 1)
@@ -928,7 +927,7 @@ class NginxConfiguratorTest(util.NginxTest):
if 'summer.com' in x.names][0] if 'summer.com' in x.names][0]
mock_dialog.return_value = [vhost] mock_dialog.return_value = [vhost]
self.config.enhance("*.com", "staple-ocsp", "example/chain.pem") self.config.enhance("*.com", "staple-ocsp", "example/chain.pem")
self.assertTrue(mock_dialog.called) self.assertIs(mock_dialog.called, True)
@mock.patch("certbot_nginx._internal.display_ops.select_vhost_multiple") @mock.patch("certbot_nginx._internal.display_ops.select_vhost_multiple")
def test_enhance_wildcard_double_redirect(self, mock_dialog): def test_enhance_wildcard_double_redirect(self, mock_dialog):
@@ -1042,7 +1041,8 @@ class InstallSslOptionsConfTest(util.NginxTest):
f.write("hashofanoldversion") f.write("hashofanoldversion")
with mock.patch("certbot.plugins.common.logger") as mock_logger: with mock.patch("certbot.plugins.common.logger") as mock_logger:
self._call() self._call()
self.assertEqual(mock_logger.warning.call_args[0][0], self.assertEqual(
mock_logger.warning.call_args[0][0],
"%s has been manually modified; updated file " "%s has been manually modified; updated file "
"saved to %s. We recommend updating %s for security purposes.") "saved to %s. We recommend updating %s for security purposes.")
self.assertEqual(crypto_util.sha256sum(self.config.mod_ssl_conf_src), self.assertEqual(crypto_util.sha256sum(self.config.mod_ssl_conf_src),
@@ -1054,9 +1054,11 @@ class InstallSslOptionsConfTest(util.NginxTest):
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_nginx._internal.constants import ALL_SSL_OPTIONS_HASHES
self.assertTrue(self._current_ssl_options_hash() in ALL_SSL_OPTIONS_HASHES, self.assertIn(
self._current_ssl_options_hash(), 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."
)
def test_ssl_config_files_hash_in_all_hashes(self): def test_ssl_config_files_hash_in_all_hashes(self):
""" """
@@ -1077,9 +1079,11 @@ class InstallSslOptionsConfTest(util.NginxTest):
self.assertTrue(all_files) self.assertTrue(all_files)
for one_file in all_files: for one_file in all_files:
file_hash = crypto_util.sha256sum(one_file) file_hash = crypto_util.sha256sum(one_file)
self.assertTrue(file_hash in ALL_SSL_OPTIONS_HASHES, self.assertIn(
"Constants.ALL_SSL_OPTIONS_HASHES must be appended with the sha256 " file_hash, ALL_SSL_OPTIONS_HASHES,
"hash of {0} when it is updated.".format(one_file)) f"Constants.ALL_SSL_OPTIONS_HASHES must be appended with the sha256 "
f"hash of {one_file} when it is updated."
)
def test_nginx_version_uses_correct_config(self): def test_nginx_version_uses_correct_config(self):
self.config.version = (1, 5, 8) self.config.version = (1, 5, 8)
@@ -1127,7 +1131,7 @@ class DetermineDefaultServerRootTest(certbot_test_util.ConfigTestCase):
self.assertIn("/usr/local/etc/nginx", server_root) self.assertIn("/usr/local/etc/nginx", server_root)
self.assertIn("/etc/nginx", server_root) self.assertIn("/etc/nginx", server_root)
else: else:
self.assertTrue(server_root in ("/etc/nginx", "/usr/local/etc/nginx")) self.assertIn(server_root, ("/etc/nginx", "/usr/local/etc/nginx"))
if __name__ == "__main__": if __name__ == "__main__":
+5 -4
View File
@@ -27,15 +27,16 @@ class SelectVhostMultiTest(util.NginxTest):
vhs = select_vhost_multiple([self.vhosts[3], vhs = select_vhost_multiple([self.vhosts[3],
self.vhosts[2], self.vhosts[2],
self.vhosts[1]]) self.vhosts[1]])
self.assertTrue(self.vhosts[2] in vhs) self.assertIn(self.vhosts[2], vhs)
self.assertTrue(self.vhosts[3] in vhs) self.assertIn(self.vhosts[3], vhs)
self.assertFalse(self.vhosts[1] in vhs) self.assertNotIn(self.vhosts[1], vhs)
@certbot_util.patch_display_util() @certbot_util.patch_display_util()
def test_select_cancel(self, mock_util): def test_select_cancel(self, mock_util):
mock_util().checklist.return_value = (display_util.CANCEL, "whatever") mock_util().checklist.return_value = (display_util.CANCEL, "whatever")
vhs = select_vhost_multiple([self.vhosts[2], self.vhosts[3]]) vhs = select_vhost_multiple([self.vhosts[2], self.vhosts[3]])
self.assertFalse(vhs) self.assertEqual(len(vhs), 0)
self.assertEqual(vhs, [])
if __name__ == "__main__": if __name__ == "__main__":
+5 -5
View File
@@ -432,15 +432,15 @@ class TestUnspacedList(unittest.TestCase):
self.assertEqual(ul3, ["some", "things", "why", "did", "whether"]) self.assertEqual(ul3, ["some", "things", "why", "did", "whether"])
def test_is_dirty(self): def test_is_dirty(self):
self.assertEqual(False, self.ul2.is_dirty()) self.assertIs(self.ul2.is_dirty(), False)
ul3 = UnspacedList([]) ul3 = UnspacedList([])
ul3.append(self.ul) ul3.append(self.ul)
self.assertEqual(False, self.ul.is_dirty()) self.assertIs(self.ul.is_dirty(), False)
self.assertEqual(True, ul3.is_dirty()) self.assertIs(ul3.is_dirty(), True)
ul4 = UnspacedList([[1], [2, 3, 4]]) ul4 = UnspacedList([[1], [2, 3, 4]])
self.assertEqual(False, ul4.is_dirty()) self.assertIs(ul4.is_dirty(), False)
ul4[1][2] = 5 ul4[1][2] = 5
self.assertEqual(True, ul4.is_dirty()) self.assertIs(ul4.is_dirty(), True)
if __name__ == '__main__': if __name__ == '__main__':
+19 -18
View File
@@ -19,37 +19,37 @@ class AddrTest(unittest.TestCase):
def test_fromstring(self): def test_fromstring(self):
self.assertEqual(self.addr1.get_addr(), "192.168.1.1") self.assertEqual(self.addr1.get_addr(), "192.168.1.1")
self.assertEqual(self.addr1.get_port(), "") self.assertEqual(self.addr1.get_port(), "")
self.assertFalse(self.addr1.ssl) self.assertIs(self.addr1.ssl, False)
self.assertFalse(self.addr1.default) self.assertIs(self.addr1.default, False)
self.assertEqual(self.addr2.get_addr(), "192.168.1.1") self.assertEqual(self.addr2.get_addr(), "192.168.1.1")
self.assertEqual(self.addr2.get_port(), "*") self.assertEqual(self.addr2.get_port(), "*")
self.assertTrue(self.addr2.ssl) self.assertIs(self.addr2.ssl, True)
self.assertFalse(self.addr2.default) self.assertIs(self.addr2.default, False)
self.assertEqual(self.addr3.get_addr(), "192.168.1.1") self.assertEqual(self.addr3.get_addr(), "192.168.1.1")
self.assertEqual(self.addr3.get_port(), "80") self.assertEqual(self.addr3.get_port(), "80")
self.assertFalse(self.addr3.ssl) self.assertIs(self.addr3.ssl, False)
self.assertFalse(self.addr3.default) self.assertIs(self.addr3.default, False)
self.assertEqual(self.addr4.get_addr(), "*") self.assertEqual(self.addr4.get_addr(), "*")
self.assertEqual(self.addr4.get_port(), "80") self.assertEqual(self.addr4.get_port(), "80")
self.assertTrue(self.addr4.ssl) self.assertIs(self.addr4.ssl, True)
self.assertTrue(self.addr4.default) self.assertIs(self.addr4.default, True)
self.assertEqual(self.addr5.get_addr(), "myhost") self.assertEqual(self.addr5.get_addr(), "myhost")
self.assertEqual(self.addr5.get_port(), "") self.assertEqual(self.addr5.get_port(), "")
self.assertFalse(self.addr5.ssl) self.assertIs(self.addr5.ssl, False)
self.assertFalse(self.addr5.default) self.assertIs(self.addr5.default, False)
self.assertEqual(self.addr6.get_addr(), "") self.assertEqual(self.addr6.get_addr(), "")
self.assertEqual(self.addr6.get_port(), "80") self.assertEqual(self.addr6.get_port(), "80")
self.assertFalse(self.addr6.ssl) self.assertIs(self.addr6.ssl, False)
self.assertTrue(self.addr6.default) self.assertIs(self.addr6.default, True)
self.assertTrue(self.addr8.default) self.assertIs(self.addr8.default, True)
self.assertEqual(None, self.addr7) self.assertIsNone(self.addr7)
def test_str(self): def test_str(self):
self.assertEqual(str(self.addr1), "192.168.1.1") self.assertEqual(str(self.addr1), "192.168.1.1")
@@ -177,10 +177,10 @@ class VirtualHostTest(unittest.TestCase):
self.assertEqual(stringified, str(self.vhost1)) self.assertEqual(stringified, str(self.vhost1))
def test_has_header(self): def test_has_header(self):
self.assertTrue(self.vhost_has_hsts.has_header('Strict-Transport-Security')) self.assertIs(self.vhost_has_hsts.has_header('Strict-Transport-Security'), True)
self.assertFalse(self.vhost_has_hsts.has_header('Bogus-Header')) self.assertIs(self.vhost_has_hsts.has_header('Bogus-Header'), False)
self.assertFalse(self.vhost1.has_header('Strict-Transport-Security')) self.assertIs(self.vhost1.has_header('Strict-Transport-Security'), False)
self.assertFalse(self.vhost1.has_header('Bogus-Header')) self.assertIs(self.vhost1.has_header('Bogus-Header'), False)
def test_contains_list(self): def test_contains_list(self):
from certbot_nginx._internal.obj import VirtualHost from certbot_nginx._internal.obj import VirtualHost
@@ -224,5 +224,6 @@ class VirtualHostTest(unittest.TestCase):
self.assertTrue(vhost_haystack.contains_list(test_needle)) self.assertTrue(vhost_haystack.contains_list(test_needle))
self.assertFalse(vhost_bad_haystack.contains_list(test_needle)) self.assertFalse(vhost_bad_haystack.contains_list(test_needle))
if __name__ == "__main__": if __name__ == "__main__":
unittest.main() # pragma: no cover unittest.main() # pragma: no cover
+7 -4
View File
@@ -35,8 +35,8 @@ class CommentHelpersTest(unittest.TestCase):
self.assertTrue(_is_certbot_comment(comment)) self.assertTrue(_is_certbot_comment(comment))
self.assertEqual(comment.dump(), COMMENT_BLOCK) self.assertEqual(comment.dump(), COMMENT_BLOCK)
self.assertEqual(comment.dump(True), [' '] + COMMENT_BLOCK) self.assertEqual(comment.dump(True), [' '] + COMMENT_BLOCK)
self.assertEqual(_certbot_comment(None, 2).dump(True), self.assertEqual(_certbot_comment(None, 2).dump(True), [' '] + COMMENT_BLOCK)
[' '] + COMMENT_BLOCK)
class ParsingHooksTest(unittest.TestCase): class ParsingHooksTest(unittest.TestCase):
def test_is_sentence(self): def test_is_sentence(self):
@@ -94,6 +94,7 @@ class ParsingHooksTest(unittest.TestCase):
parse_raw([], add_spaces=True) parse_raw([], add_spaces=True)
fake_parser1.parse.called_with([None, True]) fake_parser1.parse.called_with([None, True])
class SentenceTest(unittest.TestCase): class SentenceTest(unittest.TestCase):
def setUp(self): def setUp(self):
from certbot_nginx._internal.parser_obj import Sentence from certbot_nginx._internal.parser_obj import Sentence
@@ -140,6 +141,7 @@ class SentenceTest(unittest.TestCase):
self.sentence.parse(['\n\t \n', 'tabs']) self.sentence.parse(['\n\t \n', 'tabs'])
self.assertEqual(self.sentence.get_tabs(), '') self.assertEqual(self.sentence.get_tabs(), '')
class BlockTest(unittest.TestCase): class BlockTest(unittest.TestCase):
def setUp(self): def setUp(self):
from certbot_nginx._internal.parser_obj import Block from certbot_nginx._internal.parser_obj import Block
@@ -244,8 +246,8 @@ class StatementsTest(unittest.TestCase):
def test_parse_hides_trailing_whitespace(self): def test_parse_hides_trailing_whitespace(self):
self.statements.parse(self.raw + ['\n\n ']) self.statements.parse(self.raw + ['\n\n '])
self.assertTrue(isinstance(self.statements.dump()[-1], list)) self.assertIsInstance(self.statements.dump()[-1], list)
self.assertTrue(self.statements.dump(True)[-1].isspace()) self.assertIs(self.statements.dump(True)[-1].isspace(), True)
self.assertEqual(self.statements.dump(True)[-1], '\n\n ') self.assertEqual(self.statements.dump(True)[-1], '\n\n ')
def test_iterate(self): def test_iterate(self):
@@ -254,5 +256,6 @@ class StatementsTest(unittest.TestCase):
for i, elem in enumerate(self.statements.iterate(match=lambda x: 'sentence' in x)): for i, elem in enumerate(self.statements.iterate(match=lambda x: 'sentence' in x)):
self.assertEqual(expected[i], elem.dump()) self.assertEqual(expected[i], elem.dump())
if __name__ == "__main__": if __name__ == "__main__":
unittest.main() # pragma: no cover unittest.main() # pragma: no cover
+4 -4
View File
@@ -203,8 +203,7 @@ class NginxParserTest(util.NginxTest):
mock_vhost.raw = [['listen', '80'], mock_vhost.raw = [['listen', '80'],
['ssl', 'on'], ['ssl', 'on'],
['server_name', '*.www.foo.com', '*.www.example.com']] ['server_name', '*.www.foo.com', '*.www.example.com']]
self.assertTrue(nparser.has_ssl_on_directive(mock_vhost)) self.assertIs(nparser.has_ssl_on_directive(mock_vhost), True)
def test_remove_server_directives(self): def test_remove_server_directives(self):
nparser = parser.NginxParser(self.config_path) nparser = parser.NginxParser(self.config_path)
@@ -452,7 +451,7 @@ class NginxParserTest(util.NginxTest):
nparser.filedump(ext='') nparser.filedump(ext='')
# check properties of new vhost # check properties of new vhost
self.assertFalse(next(iter(new_vhost.addrs)).default) self.assertIs(next(iter(new_vhost.addrs)).default, False)
self.assertNotEqual(new_vhost.path, default.path) self.assertNotEqual(new_vhost.path, default.path)
# check that things are written to file correctly # check that things are written to file correctly
@@ -461,7 +460,7 @@ class NginxParserTest(util.NginxTest):
new_defaults = [x for x in new_vhosts if 'default' in x.filep] new_defaults = [x for x in new_vhosts if 'default' in x.filep]
self.assertEqual(len(new_defaults), 2) self.assertEqual(len(new_defaults), 2)
new_vhost_parsed = new_defaults[1] new_vhost_parsed = new_defaults[1]
self.assertFalse(next(iter(new_vhost_parsed.addrs)).default) self.assertIs(next(iter(new_vhost_parsed.addrs)).default, False)
self.assertEqual(next(iter(default.names)), next(iter(new_vhost_parsed.names))) self.assertEqual(next(iter(default.names)), next(iter(new_vhost_parsed.names)))
self.assertEqual(len(default.raw), len(new_vhost_parsed.raw)) self.assertEqual(len(default.raw), len(new_vhost_parsed.raw))
self.assertTrue(next(iter(default.addrs)).super_eq(next(iter(new_vhost_parsed.addrs)))) self.assertTrue(next(iter(default.addrs)).super_eq(next(iter(new_vhost_parsed.addrs))))
@@ -533,5 +532,6 @@ class NginxParserTest(util.NginxTest):
for output in log.output for output in log.output
)) ))
if __name__ == "__main__": if __name__ == "__main__":
unittest.main() # pragma: no cover unittest.main() # pragma: no cover
+2 -1
View File
@@ -293,7 +293,8 @@ class NoninteractiveDisplayTest(unittest.TestCase):
self.displayer.notification("message2", pause=False) self.displayer.notification("message2", pause=False)
string = self.mock_stdout.write.call_args[0][0] string = self.mock_stdout.write.call_args[0][0]
self.assertTrue("- - - " in string and ("message2" + os.linesep) in string) self.assertIn("- - - ", string)
self.assertIn("message2" + os.linesep, string)
def test_input(self): def test_input(self):
d = "an incomputable value" d = "an incomputable value"