Avoid deprecated TestCase functions in unit tests. (#76678)

* Avoid deprecated TestCase functions in unit tests.
* Add assertRaisesRegex for Python 2.7.
* Fix indentation.
pull/76679/head
Matt Clay 3 years ago committed by GitHub
parent ace04087e7
commit 97104f1221
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -70,18 +70,18 @@ class TestVaultCli(unittest.TestCase):
mock_setup_vault_secrets.return_value = [] mock_setup_vault_secrets.return_value = []
cli = VaultCLI(args=['ansible-vault', 'view', '/dev/null/foo']) cli = VaultCLI(args=['ansible-vault', 'view', '/dev/null/foo'])
cli.parse() cli.parse()
self.assertRaisesRegexp(errors.AnsibleOptionsError, self.assertRaisesRegex(errors.AnsibleOptionsError,
"A vault password is required to use Ansible's Vault", "A vault password is required to use Ansible's Vault",
cli.run) cli.run)
@patch('ansible.cli.vault.VaultCLI.setup_vault_secrets') @patch('ansible.cli.vault.VaultCLI.setup_vault_secrets')
def test_encrypt_missing_file_no_secret(self, mock_setup_vault_secrets): def test_encrypt_missing_file_no_secret(self, mock_setup_vault_secrets):
mock_setup_vault_secrets.return_value = [] mock_setup_vault_secrets.return_value = []
cli = VaultCLI(args=['ansible-vault', 'encrypt', '/dev/null/foo']) cli = VaultCLI(args=['ansible-vault', 'encrypt', '/dev/null/foo'])
cli.parse() cli.parse()
self.assertRaisesRegexp(errors.AnsibleOptionsError, self.assertRaisesRegex(errors.AnsibleOptionsError,
"A vault password is required to use Ansible's Vault", "A vault password is required to use Ansible's Vault",
cli.run) cli.run)
@patch('ansible.cli.vault.VaultCLI.setup_vault_secrets') @patch('ansible.cli.vault.VaultCLI.setup_vault_secrets')
@patch('ansible.cli.vault.VaultEditor') @patch('ansible.cli.vault.VaultEditor')

@ -36,3 +36,7 @@ if sys.version_info < (2, 7):
print('You need unittest2 installed on python2.6.x to run tests') print('You need unittest2 installed on python2.6.x to run tests')
else: else:
from unittest import * from unittest import *
if not hasattr(TestCase, 'assertRaisesRegex'):
# added in Python 3.2
TestCase.assertRaisesRegex = TestCase.assertRaisesRegexp

@ -265,12 +265,12 @@ class TestGetCollectorNames(unittest.TestCase):
valid_subsets = frozenset(['my_fact', 'something_else']) valid_subsets = frozenset(['my_fact', 'something_else'])
minimal_gather_subset = frozenset(['my_fact']) minimal_gather_subset = frozenset(['my_fact'])
self.assertRaisesRegexp(TypeError, self.assertRaisesRegex(TypeError,
r'Bad subset .* given to Ansible.*allowed\:.*all,.*my_fact.*', r'Bad subset .* given to Ansible.*allowed\:.*all,.*my_fact.*',
collector.get_collector_names, collector.get_collector_names,
valid_subsets=valid_subsets, valid_subsets=valid_subsets,
minimal_gather_subset=minimal_gather_subset, minimal_gather_subset=minimal_gather_subset,
gather_subset=['my_fact', 'not_a_valid_gather_subset']) gather_subset=['my_fact', 'not_a_valid_gather_subset'])
class TestFindUnresolvedRequires(unittest.TestCase): class TestFindUnresolvedRequires(unittest.TestCase):
@ -349,10 +349,10 @@ class TestResolveRequires(unittest.TestCase):
all_fact_subsets = {'env': [default_collectors.EnvFactCollector], all_fact_subsets = {'env': [default_collectors.EnvFactCollector],
'network': [default_collectors.LinuxNetworkCollector], 'network': [default_collectors.LinuxNetworkCollector],
'virtual': [default_collectors.LinuxVirtualCollector]} 'virtual': [default_collectors.LinuxVirtualCollector]}
self.assertRaisesRegexp(collector.UnresolvedFactDep, self.assertRaisesRegex(collector.UnresolvedFactDep,
'unresolved fact dep.*required_thing2', 'unresolved fact dep.*required_thing2',
collector.resolve_requires, collector.resolve_requires,
unresolved, all_fact_subsets) unresolved, all_fact_subsets)
def test(self): def test(self):
unresolved = ['env', 'network'] unresolved = ['env', 'network']
@ -556,8 +556,8 @@ class TestCollectorClassesFromGatherSubset(unittest.TestCase):
def test_unknown_collector(self): def test_unknown_collector(self):
# something claims 'unknown_collector' is a valid gather_subset, but there is # something claims 'unknown_collector' is a valid gather_subset, but there is
# no FactCollector mapped to 'unknown_collector' # no FactCollector mapped to 'unknown_collector'
self.assertRaisesRegexp(TypeError, self.assertRaisesRegex(TypeError,
r'Bad subset.*unknown_collector.*given to Ansible.*allowed\:.*all,.*env.*', r'Bad subset.*unknown_collector.*given to Ansible.*allowed\:.*all,.*env.*',
self._classes, self._classes,
all_collector_classes=default_collectors.collectors, all_collector_classes=default_collectors.collectors,
gather_subset=['env', 'unknown_collector']) gather_subset=['env', 'unknown_collector'])

@ -138,8 +138,8 @@ class TestDataLoader(unittest.TestCase):
self.assertTrue(self._loader.is_directory(os.path.dirname(__file__))) self.assertTrue(self._loader.is_directory(os.path.dirname(__file__)))
def test_get_file_contents_none_path(self): def test_get_file_contents_none_path(self):
self.assertRaisesRegexp(AnsibleParserError, 'Invalid filename', self.assertRaisesRegex(AnsibleParserError, 'Invalid filename',
self._loader._get_file_contents, None) self._loader._get_file_contents, None)
def test_get_file_contents_non_existent_path(self): def test_get_file_contents_non_existent_path(self):
self.assertRaises(AnsibleFileNotFound, self._loader._get_file_contents, '/non_existent_file') self.assertRaises(AnsibleFileNotFound, self._loader._get_file_contents, '/non_existent_file')
@ -169,7 +169,7 @@ class TestPathDwimRelativeStackDataLoader(unittest.TestCase):
self._loader = DataLoader() self._loader = DataLoader()
def test_none(self): def test_none(self):
self.assertRaisesRegexp(AnsibleFileNotFound, 'on the Ansible Controller', self._loader.path_dwim_relative_stack, None, None, None) self.assertRaisesRegex(AnsibleFileNotFound, 'on the Ansible Controller', self._loader.path_dwim_relative_stack, None, None, None)
def test_empty_strings(self): def test_empty_strings(self):
self.assertEqual(self._loader.path_dwim_relative_stack('', '', ''), './') self.assertEqual(self._loader.path_dwim_relative_stack('', '', ''), './')
@ -218,7 +218,7 @@ class TestDataLoaderWithVault(unittest.TestCase):
self.assertRaises(AnsibleVaultError, self._loader.get_real_file, self.test_vault_data_path) self.assertRaises(AnsibleVaultError, self._loader.get_real_file, self.test_vault_data_path)
def test_get_real_file_not_a_path(self): def test_get_real_file_not_a_path(self):
self.assertRaisesRegexp(AnsibleParserError, 'Invalid filename', self._loader.get_real_file, None) self.assertRaisesRegex(AnsibleParserError, 'Invalid filename', self._loader.get_real_file, None)
@patch.multiple(DataLoader, path_exists=lambda s, x: True, is_file=lambda s, x: True) @patch.multiple(DataLoader, path_exists=lambda s, x: True, is_file=lambda s, x: True)
def test_parse_from_vault_1_1_file(self): def test_parse_from_vault_1_1_file(self):

@ -51,18 +51,18 @@ class TestUnhexlify(unittest.TestCase):
def test_odd_length(self): def test_odd_length(self):
b_data = b'123456789abcdefghijklmnopqrstuvwxyz' b_data = b'123456789abcdefghijklmnopqrstuvwxyz'
self.assertRaisesRegexp(vault.AnsibleVaultFormatError, self.assertRaisesRegex(vault.AnsibleVaultFormatError,
'.*Vault format unhexlify error.*', '.*Vault format unhexlify error.*',
vault._unhexlify, vault._unhexlify,
b_data) b_data)
def test_nonhex(self): def test_nonhex(self):
b_data = b'6z36316566653264333665333637623064303639353237620a636366633565663263336335656532' b_data = b'6z36316566653264333665333637623064303639353237620a636366633565663263336335656532'
self.assertRaisesRegexp(vault.AnsibleVaultFormatError, self.assertRaisesRegex(vault.AnsibleVaultFormatError,
'.*Vault format unhexlify error.*Non-hexadecimal digit found', '.*Vault format unhexlify error.*Non-hexadecimal digit found',
vault._unhexlify, vault._unhexlify,
b_data) b_data)
class TestParseVaulttext(unittest.TestCase): class TestParseVaulttext(unittest.TestCase):
@ -91,10 +91,10 @@ class TestParseVaulttext(unittest.TestCase):
b_vaulttext_envelope = to_bytes(vaulttext_envelope, errors='strict', encoding='utf-8') b_vaulttext_envelope = to_bytes(vaulttext_envelope, errors='strict', encoding='utf-8')
b_vaulttext, b_version, cipher_name, vault_id = vault.parse_vaulttext_envelope(b_vaulttext_envelope) b_vaulttext, b_version, cipher_name, vault_id = vault.parse_vaulttext_envelope(b_vaulttext_envelope)
self.assertRaisesRegexp(vault.AnsibleVaultFormatError, self.assertRaisesRegex(vault.AnsibleVaultFormatError,
'.*Vault format unhexlify error.*Non-hexadecimal digit found', '.*Vault format unhexlify error.*Non-hexadecimal digit found',
vault.parse_vaulttext, vault.parse_vaulttext,
b_vaulttext_envelope) b_vaulttext_envelope)
class TestVaultSecret(unittest.TestCase): class TestVaultSecret(unittest.TestCase):
@ -133,18 +133,18 @@ class TestPromptVaultSecret(unittest.TestCase):
@patch('ansible.parsing.vault.display.prompt', side_effect=EOFError) @patch('ansible.parsing.vault.display.prompt', side_effect=EOFError)
def test_prompt_eoferror(self, mock_display_prompt): def test_prompt_eoferror(self, mock_display_prompt):
secret = vault.PromptVaultSecret(vault_id='test_id') secret = vault.PromptVaultSecret(vault_id='test_id')
self.assertRaisesRegexp(vault.AnsibleVaultError, self.assertRaisesRegex(vault.AnsibleVaultError,
'EOFError.*test_id', 'EOFError.*test_id',
secret.load) secret.load)
@patch('ansible.parsing.vault.display.prompt', side_effect=['first_password', 'second_password']) @patch('ansible.parsing.vault.display.prompt', side_effect=['first_password', 'second_password'])
def test_prompt_passwords_dont_match(self, mock_display_prompt): def test_prompt_passwords_dont_match(self, mock_display_prompt):
secret = vault.PromptVaultSecret(vault_id='test_id', secret = vault.PromptVaultSecret(vault_id='test_id',
prompt_formats=['Vault password: ', prompt_formats=['Vault password: ',
'Confirm Vault password: ']) 'Confirm Vault password: '])
self.assertRaisesRegexp(errors.AnsibleError, self.assertRaisesRegex(errors.AnsibleError,
'Passwords do not match', 'Passwords do not match',
secret.load) secret.load)
class TestFileVaultSecret(unittest.TestCase): class TestFileVaultSecret(unittest.TestCase):
@ -200,9 +200,9 @@ class TestFileVaultSecret(unittest.TestCase):
fake_loader = DictDataLoader({tmp_file.name: ''}) fake_loader = DictDataLoader({tmp_file.name: ''})
secret = vault.FileVaultSecret(loader=fake_loader, filename=tmp_file.name) secret = vault.FileVaultSecret(loader=fake_loader, filename=tmp_file.name)
self.assertRaisesRegexp(vault.AnsibleVaultPasswordError, self.assertRaisesRegex(vault.AnsibleVaultPasswordError,
'Invalid vault password was provided from file.*%s' % tmp_file.name, 'Invalid vault password was provided from file.*%s' % tmp_file.name,
secret.load) secret.load)
os.unlink(tmp_file.name) os.unlink(tmp_file.name)
@ -241,9 +241,9 @@ class TestFileVaultSecret(unittest.TestCase):
fake_loader = DictDataLoader({filename: 'sdfadf'}) fake_loader = DictDataLoader({filename: 'sdfadf'})
secret = vault.FileVaultSecret(loader=fake_loader, filename=filename) secret = vault.FileVaultSecret(loader=fake_loader, filename=filename)
self.assertRaisesRegexp(errors.AnsibleError, self.assertRaisesRegex(errors.AnsibleError,
'.*Could not read vault password file.*/dev/null/foobar.*Not a directory', '.*Could not read vault password file.*/dev/null/foobar.*Not a directory',
secret.load) secret.load)
def test_file_not_found(self): def test_file_not_found(self):
tmp_file = tempfile.NamedTemporaryFile() tmp_file = tempfile.NamedTemporaryFile()
@ -253,9 +253,9 @@ class TestFileVaultSecret(unittest.TestCase):
fake_loader = DictDataLoader({filename: 'sdfadf'}) fake_loader = DictDataLoader({filename: 'sdfadf'})
secret = vault.FileVaultSecret(loader=fake_loader, filename=filename) secret = vault.FileVaultSecret(loader=fake_loader, filename=filename)
self.assertRaisesRegexp(errors.AnsibleError, self.assertRaisesRegex(errors.AnsibleError,
'.*Could not read vault password file.*%s.*' % filename, '.*Could not read vault password file.*%s.*' % filename,
secret.load) secret.load)
class TestScriptVaultSecret(unittest.TestCase): class TestScriptVaultSecret(unittest.TestCase):
@ -285,9 +285,9 @@ class TestScriptVaultSecret(unittest.TestCase):
secret = vault.ScriptVaultSecret() secret = vault.ScriptVaultSecret()
with patch.object(secret, 'loader') as mock_loader: with patch.object(secret, 'loader') as mock_loader:
mock_loader.is_executable = MagicMock(return_value=True) mock_loader.is_executable = MagicMock(return_value=True)
self.assertRaisesRegexp(vault.AnsibleVaultPasswordError, self.assertRaisesRegex(vault.AnsibleVaultPasswordError,
'Invalid vault password was provided from script', 'Invalid vault password was provided from script',
secret.load) secret.load)
@patch('ansible.parsing.vault.subprocess.Popen') @patch('ansible.parsing.vault.subprocess.Popen')
def test_read_file_os_error(self, mock_popen): def test_read_file_os_error(self, mock_popen):
@ -296,9 +296,9 @@ class TestScriptVaultSecret(unittest.TestCase):
secret = vault.ScriptVaultSecret() secret = vault.ScriptVaultSecret()
with patch.object(secret, 'loader') as mock_loader: with patch.object(secret, 'loader') as mock_loader:
mock_loader.is_executable = MagicMock(return_value=True) mock_loader.is_executable = MagicMock(return_value=True)
self.assertRaisesRegexp(errors.AnsibleError, self.assertRaisesRegex(errors.AnsibleError,
'Problem running vault password script.*', 'Problem running vault password script.*',
secret.load) secret.load)
@patch('ansible.parsing.vault.subprocess.Popen') @patch('ansible.parsing.vault.subprocess.Popen')
def test_read_file_not_executable(self, mock_popen): def test_read_file_not_executable(self, mock_popen):
@ -306,9 +306,9 @@ class TestScriptVaultSecret(unittest.TestCase):
secret = vault.ScriptVaultSecret() secret = vault.ScriptVaultSecret()
with patch.object(secret, 'loader') as mock_loader: with patch.object(secret, 'loader') as mock_loader:
mock_loader.is_executable = MagicMock(return_value=False) mock_loader.is_executable = MagicMock(return_value=False)
self.assertRaisesRegexp(vault.AnsibleVaultError, self.assertRaisesRegex(vault.AnsibleVaultError,
'The vault password script .* was not executable', 'The vault password script .* was not executable',
secret.load) secret.load)
@patch('ansible.parsing.vault.subprocess.Popen') @patch('ansible.parsing.vault.subprocess.Popen')
def test_read_file_non_zero_return_code(self, mock_popen): def test_read_file_non_zero_return_code(self, mock_popen):
@ -319,9 +319,9 @@ class TestScriptVaultSecret(unittest.TestCase):
secret = vault.ScriptVaultSecret(filename='/dev/null/some_vault_secret') secret = vault.ScriptVaultSecret(filename='/dev/null/some_vault_secret')
with patch.object(secret, 'loader') as mock_loader: with patch.object(secret, 'loader') as mock_loader:
mock_loader.is_executable = MagicMock(return_value=True) mock_loader.is_executable = MagicMock(return_value=True)
self.assertRaisesRegexp(errors.AnsibleError, self.assertRaisesRegex(errors.AnsibleError,
r'Vault password script.*returned non-zero \(%s\): %s' % (rc, stderr), r'Vault password script.*returned non-zero \(%s\): %s' % (rc, stderr),
secret.load) secret.load)
class TestScriptIsClient(unittest.TestCase): class TestScriptIsClient(unittest.TestCase):
@ -382,11 +382,11 @@ class TestGetFileVaultSecret(unittest.TestCase):
filename = '/dev/null/foobar' filename = '/dev/null/foobar'
fake_loader = DictDataLoader({filename: 'sdfadf'}) fake_loader = DictDataLoader({filename: 'sdfadf'})
self.assertRaisesRegexp(errors.AnsibleError, self.assertRaisesRegex(errors.AnsibleError,
'.*The vault password file %s was not found.*' % filename, '.*The vault password file %s was not found.*' % filename,
vault.get_file_vault_secret, vault.get_file_vault_secret,
filename=filename, filename=filename,
loader=fake_loader) loader=fake_loader)
def test_file_not_found(self): def test_file_not_found(self):
tmp_file = tempfile.NamedTemporaryFile() tmp_file = tempfile.NamedTemporaryFile()
@ -395,11 +395,11 @@ class TestGetFileVaultSecret(unittest.TestCase):
fake_loader = DictDataLoader({filename: 'sdfadf'}) fake_loader = DictDataLoader({filename: 'sdfadf'})
self.assertRaisesRegexp(errors.AnsibleError, self.assertRaisesRegex(errors.AnsibleError,
'.*The vault password file %s was not found.*' % filename, '.*The vault password file %s was not found.*' % filename,
vault.get_file_vault_secret, vault.get_file_vault_secret,
filename=filename, filename=filename,
loader=fake_loader) loader=fake_loader)
class TestVaultIsEncrypted(unittest.TestCase): class TestVaultIsEncrypted(unittest.TestCase):
@ -645,10 +645,10 @@ class TestVaultLib(unittest.TestCase):
v = vault.VaultLib(vault_secrets) v = vault.VaultLib(vault_secrets)
plaintext = u'Some text to encrypt in a café' plaintext = u'Some text to encrypt in a café'
self.assertRaisesRegexp(vault.AnsibleVaultError, self.assertRaisesRegex(vault.AnsibleVaultError,
'.*A vault password must be specified to encrypt data.*', '.*A vault password must be specified to encrypt data.*',
v.encrypt, v.encrypt,
plaintext) plaintext)
def test_format_vaulttext_envelope(self): def test_format_vaulttext_envelope(self):
cipher_name = "TEST" cipher_name = "TEST"
@ -712,10 +712,10 @@ class TestVaultLib(unittest.TestCase):
v_none = vault.VaultLib(None) v_none = vault.VaultLib(None)
# so set secrets None explicitly # so set secrets None explicitly
v_none.secrets = None v_none.secrets = None
self.assertRaisesRegexp(vault.AnsibleVaultError, self.assertRaisesRegex(vault.AnsibleVaultError,
'.*A vault password must be specified to decrypt data.*', '.*A vault password must be specified to decrypt data.*',
v_none.decrypt, v_none.decrypt,
b_vaulttext) b_vaulttext)
def test_encrypt_decrypt_aes256_empty_secrets(self): def test_encrypt_decrypt_aes256_empty_secrets(self):
vault_secrets = self._vault_secrets_from_password('default', 'ansible') vault_secrets = self._vault_secrets_from_password('default', 'ansible')
@ -727,10 +727,10 @@ class TestVaultLib(unittest.TestCase):
vault_secrets_empty = [] vault_secrets_empty = []
v_none = vault.VaultLib(vault_secrets_empty) v_none = vault.VaultLib(vault_secrets_empty)
self.assertRaisesRegexp(vault.AnsibleVaultError, self.assertRaisesRegex(vault.AnsibleVaultError,
'.*Attempting to decrypt but no vault secrets found.*', '.*Attempting to decrypt but no vault secrets found.*',
v_none.decrypt, v_none.decrypt,
b_vaulttext) b_vaulttext)
def test_encrypt_decrypt_aes256_multiple_secrets_all_wrong(self): def test_encrypt_decrypt_aes256_multiple_secrets_all_wrong(self):
plaintext = u'Some text to encrypt in a café' plaintext = u'Some text to encrypt in a café'
@ -740,11 +740,11 @@ class TestVaultLib(unittest.TestCase):
('wrong-password', TextVaultSecret('wrong-password'))] ('wrong-password', TextVaultSecret('wrong-password'))]
v_multi = vault.VaultLib(vault_secrets) v_multi = vault.VaultLib(vault_secrets)
self.assertRaisesRegexp(errors.AnsibleError, self.assertRaisesRegex(errors.AnsibleError,
'.*Decryption failed.*', '.*Decryption failed.*',
v_multi.decrypt, v_multi.decrypt,
b_vaulttext, b_vaulttext,
filename='/dev/null/fake/filename') filename='/dev/null/fake/filename')
def test_encrypt_decrypt_aes256_multiple_secrets_one_valid(self): def test_encrypt_decrypt_aes256_multiple_secrets_one_valid(self):
plaintext = u'Some text to encrypt in a café' plaintext = u'Some text to encrypt in a café'

@ -142,11 +142,11 @@ class TestVaultEditor(unittest.TestCase):
ve = self._vault_editor() ve = self._vault_editor()
self.assertRaisesRegexp(errors.AnsibleError, self.assertRaisesRegex(errors.AnsibleError,
error_txt, error_txt,
ve._edit_file_helper, ve._edit_file_helper,
src_file_path, src_file_path,
self.vault_secret) self.vault_secret)
@patch('ansible.parsing.vault.subprocess.call') @patch('ansible.parsing.vault.subprocess.call')
def test_edit_file_helper_symlink_target(self, mock_sp_call): def test_edit_file_helper_symlink_target(self, mock_sp_call):
@ -249,11 +249,11 @@ class TestVaultEditor(unittest.TestCase):
ve = self._vault_editor() ve = self._vault_editor()
ve.encrypt_file(src_file_path, self.vault_secret) ve.encrypt_file(src_file_path, self.vault_secret)
self.assertRaisesRegexp(errors.AnsibleError, self.assertRaisesRegex(errors.AnsibleError,
'The value for the new_password to rekey', 'The value for the new_password to rekey',
ve.rekey_file, ve.rekey_file,
src_file_path, src_file_path,
None) None)
def test_rekey_file_not_encrypted(self): def test_rekey_file_not_encrypted(self):
self._test_dir = self._create_test_dir() self._test_dir = self._create_test_dir()
@ -264,10 +264,10 @@ class TestVaultEditor(unittest.TestCase):
ve = self._vault_editor() ve = self._vault_editor()
new_password = 'password2:electricbugaloo' new_password = 'password2:electricbugaloo'
self.assertRaisesRegexp(errors.AnsibleError, self.assertRaisesRegex(errors.AnsibleError,
'input is not vault encrypted data', 'input is not vault encrypted data',
ve.rekey_file, ve.rekey_file,
src_file_path, new_password) src_file_path, new_password)
def test_plaintext(self): def test_plaintext(self):
self._test_dir = self._create_test_dir() self._test_dir = self._create_test_dir()
@ -288,10 +288,10 @@ class TestVaultEditor(unittest.TestCase):
src_file_path = self._create_file(self._test_dir, 'src_file', content=src_file_contents) src_file_path = self._create_file(self._test_dir, 'src_file', content=src_file_contents)
ve = self._vault_editor() ve = self._vault_editor()
self.assertRaisesRegexp(errors.AnsibleError, self.assertRaisesRegex(errors.AnsibleError,
'input is not vault encrypted data', 'input is not vault encrypted data',
ve.plaintext, ve.plaintext,
src_file_path) src_file_path)
def test_encrypt_file(self): def test_encrypt_file(self):
self._test_dir = self._create_test_dir() self._test_dir = self._create_test_dir()
@ -426,10 +426,10 @@ class TestVaultEditor(unittest.TestCase):
mock_sp_call.side_effect = faux_editor mock_sp_call.side_effect = faux_editor
ve = self._vault_editor() ve = self._vault_editor()
self.assertRaisesRegexp(errors.AnsibleError, self.assertRaisesRegex(errors.AnsibleError,
'input is not vault encrypted data', 'input is not vault encrypted data',
ve.edit_file, ve.edit_file,
src_file_path) src_file_path)
def test_create_file_exists(self): def test_create_file_exists(self):
self._test_dir = self._create_test_dir() self._test_dir = self._create_test_dir()
@ -437,11 +437,11 @@ class TestVaultEditor(unittest.TestCase):
src_file_path = self._create_file(self._test_dir, 'src_file', content=src_contents) src_file_path = self._create_file(self._test_dir, 'src_file', content=src_contents)
ve = self._vault_editor() ve = self._vault_editor()
self.assertRaisesRegexp(errors.AnsibleError, self.assertRaisesRegex(errors.AnsibleError,
'please use .edit. instead', 'please use .edit. instead',
ve.create_file, ve.create_file,
src_file_path, src_file_path,
self.vault_secret) self.vault_secret)
def test_decrypt_file_exception(self): def test_decrypt_file_exception(self):
self._test_dir = self._create_test_dir() self._test_dir = self._create_test_dir()
@ -449,10 +449,10 @@ class TestVaultEditor(unittest.TestCase):
src_file_path = self._create_file(self._test_dir, 'src_file', content=src_contents) src_file_path = self._create_file(self._test_dir, 'src_file', content=src_contents)
ve = self._vault_editor() ve = self._vault_editor()
self.assertRaisesRegexp(errors.AnsibleError, self.assertRaisesRegex(errors.AnsibleError,
'input is not vault encrypted data', 'input is not vault encrypted data',
ve.decrypt_file, ve.decrypt_file,
src_file_path) src_file_path)
@patch.object(vault.VaultEditor, '_editor_shell_command') @patch.object(vault.VaultEditor, '_editor_shell_command')
def test_create_file(self, mock_editor_shell_command): def test_create_file(self, mock_editor_shell_command):

@ -284,11 +284,11 @@ class TestAnsibleLoaderVault(unittest.TestCase, YamlTestUtils):
different_vault_string = data_from_yaml['different_secret'] different_vault_string = data_from_yaml['different_secret']
self.assertEqual(vault_string, another_vault_string) self.assertEqual(vault_string, another_vault_string)
self.assertNotEquals(vault_string, different_vault_string) self.assertNotEqual(vault_string, different_vault_string)
# More testing of __eq__/__ne__ # More testing of __eq__/__ne__
self.assertTrue('some string' != vault_string) self.assertTrue('some string' != vault_string)
self.assertNotEquals('some string', vault_string) self.assertNotEqual('some string', vault_string)
# Note this is a compare of the str/unicode of these, they are different types # Note this is a compare of the str/unicode of these, they are different types
# so we want to test self == other, and other == self etc # so we want to test self == other, and other == self etc

@ -52,7 +52,7 @@ class TestAnsibleVaultUnicodeNoVault(unittest.TestCase, YamlTestUtils):
self.assertIsInstance(avu, objects.AnsibleVaultEncryptedUnicode) self.assertIsInstance(avu, objects.AnsibleVaultEncryptedUnicode)
self.assertTrue(avu.vault is None) self.assertTrue(avu.vault is None)
# AnsibleVaultEncryptedUnicode without a vault should never == any string # AnsibleVaultEncryptedUnicode without a vault should never == any string
self.assertNotEquals(avu, seq) self.assertNotEqual(avu, seq)
def assert_values(self, seq): def assert_values(self, seq):
avu = objects.AnsibleVaultEncryptedUnicode(seq) avu = objects.AnsibleVaultEncryptedUnicode(seq)

@ -480,7 +480,7 @@ class TestBaseSubClass(TestBase):
def test_attr_dict_string(self): def test_attr_dict_string(self):
test_value = 'just_some_random_string' test_value = 'just_some_random_string'
ds = {'test_attr_dict': test_value} ds = {'test_attr_dict': test_value}
self.assertRaisesRegexp(AnsibleParserError, 'is not a dictionary', self._base_validate, ds) self.assertRaisesRegex(AnsibleParserError, 'is not a dictionary', self._base_validate, ds)
def test_attr_class(self): def test_attr_class(self):
esc = ExampleSubClass() esc = ExampleSubClass()
@ -503,14 +503,14 @@ class TestBaseSubClass(TestBase):
def test_attr_class_post_validate_class_not_instance(self): def test_attr_class_post_validate_class_not_instance(self):
not_a_esc = ExampleSubClass not_a_esc = ExampleSubClass
ds = {'test_attr_class_post_validate': not_a_esc} ds = {'test_attr_class_post_validate': not_a_esc}
self.assertRaisesRegexp(AnsibleParserError, 'is not a valid.*got a.*Meta.*instead', self.assertRaisesRegex(AnsibleParserError, 'is not a valid.*got a.*Meta.*instead',
self._base_validate, ds) self._base_validate, ds)
def test_attr_class_post_validate_wrong_class(self): def test_attr_class_post_validate_wrong_class(self):
not_a_esc = 37 not_a_esc = 37
ds = {'test_attr_class_post_validate': not_a_esc} ds = {'test_attr_class_post_validate': not_a_esc}
self.assertRaisesRegexp(AnsibleParserError, 'is not a valid.*got a.*int.*instead', self.assertRaisesRegex(AnsibleParserError, 'is not a valid.*got a.*int.*instead',
self._base_validate, ds) self._base_validate, ds)
def test_attr_remote_user(self): def test_attr_remote_user(self):
ds = {'remote_user': 'testuser'} ds = {'remote_user': 'testuser'}
@ -599,8 +599,8 @@ class TestBaseSubClass(TestBase):
bsc.load_data(ds) bsc.load_data(ds)
fake_loader = DictDataLoader({}) fake_loader = DictDataLoader({})
templar = Templar(loader=fake_loader) templar = Templar(loader=fake_loader)
self.assertRaisesRegexp(AnsibleParserError, 'cannot have empty values', self.assertRaisesRegex(AnsibleParserError, 'cannot have empty values',
bsc.post_validate, templar) bsc.post_validate, templar)
def test_attr_unknown(self): def test_attr_unknown(self):
a_list = ['some string'] a_list = ['some string']

@ -50,8 +50,8 @@ class TestConditional(unittest.TestCase):
def test_undefined(self): def test_undefined(self):
when = [u"{{ some_undefined_thing }}"] when = [u"{{ some_undefined_thing }}"]
self.assertRaisesRegexp(errors.AnsibleError, "The conditional check '{{ some_undefined_thing }}' failed", self.assertRaisesRegex(errors.AnsibleError, "The conditional check '{{ some_undefined_thing }}' failed",
self._eval_con, when, {}) self._eval_con, when, {})
def test_defined(self): def test_defined(self):
variables = {'some_defined_thing': True} variables = {'some_defined_thing': True}
@ -100,12 +100,12 @@ class TestConditional(unittest.TestCase):
when = [u"some_dict.some_dict_key1 == hostvars['host3']"] when = [u"some_dict.some_dict_key1 == hostvars['host3']"]
# self._eval_con(when, variables) # self._eval_con(when, variables)
self.assertRaisesRegexp(errors.AnsibleError, self.assertRaisesRegex(errors.AnsibleError,
r"The conditional check 'some_dict.some_dict_key1 == hostvars\['host3'\]' failed", r"The conditional check 'some_dict.some_dict_key1 == hostvars\['host3'\]' failed",
# "The conditional check 'some_dict.some_dict_key1 == hostvars['host3']' failed", # "The conditional check 'some_dict.some_dict_key1 == hostvars['host3']' failed",
# "The conditional check 'some_dict.some_dict_key1 == hostvars['host3']' failed.", # "The conditional check 'some_dict.some_dict_key1 == hostvars['host3']' failed.",
self._eval_con, self._eval_con,
when, variables) when, variables)
def test_dict_undefined_values_bare(self): def test_dict_undefined_values_bare(self):
variables = {'dict_value': 1, variables = {'dict_value': 1,
@ -116,10 +116,10 @@ class TestConditional(unittest.TestCase):
# raises an exception when a non-string conditional is passed to extract_defined_undefined() # raises an exception when a non-string conditional is passed to extract_defined_undefined()
when = [u"some_defined_dict_with_undefined_values"] when = [u"some_defined_dict_with_undefined_values"]
self.assertRaisesRegexp(errors.AnsibleError, self.assertRaisesRegex(errors.AnsibleError,
"The conditional check 'some_defined_dict_with_undefined_values' failed.", "The conditional check 'some_defined_dict_with_undefined_values' failed.",
self._eval_con, self._eval_con,
when, variables) when, variables)
def test_dict_undefined_values_is_defined(self): def test_dict_undefined_values_is_defined(self):
variables = {'dict_value': 1, variables = {'dict_value': 1,
@ -129,10 +129,10 @@ class TestConditional(unittest.TestCase):
}} }}
when = [u"some_defined_dict_with_undefined_values is defined"] when = [u"some_defined_dict_with_undefined_values is defined"]
self.assertRaisesRegexp(errors.AnsibleError, self.assertRaisesRegex(errors.AnsibleError,
"The conditional check 'some_defined_dict_with_undefined_values is defined' failed.", "The conditional check 'some_defined_dict_with_undefined_values is defined' failed.",
self._eval_con, self._eval_con,
when, variables) when, variables)
def test_is_defined(self): def test_is_defined(self):
variables = {'some_defined_thing': True} variables = {'some_defined_thing': True}
@ -195,10 +195,10 @@ class TestConditional(unittest.TestCase):
u'hostvars["some_host"] is defined', u'hostvars["some_host"] is defined',
u"{{ compare_targets.triple }} is defined", u"{{ compare_targets.triple }} is defined",
u"{{ compare_targets.quadruple }} is defined"] u"{{ compare_targets.quadruple }} is defined"]
self.assertRaisesRegexp(errors.AnsibleError, self.assertRaisesRegex(errors.AnsibleError,
"The conditional check '{{ compare_targets.triple }} is defined' failed", "The conditional check '{{ compare_targets.triple }} is defined' failed",
self._eval_con, self._eval_con,
when, variables) when, variables)
def test_is_hostvars_host_is_defined(self): def test_is_hostvars_host_is_defined(self):
variables = {'hostvars': {'some_host': {}, }} variables = {'hostvars': {'some_host': {}, }}

@ -107,30 +107,30 @@ class TestLoadListOfTasks(unittest.TestCase, MixinForMocks):
def test_empty_task(self): def test_empty_task(self):
ds = [{}] ds = [{}]
self.assertRaisesRegexp(errors.AnsibleParserError, self.assertRaisesRegex(errors.AnsibleParserError,
"no module/action detected in task", "no module/action detected in task",
helpers.load_list_of_tasks, helpers.load_list_of_tasks,
ds, play=self.mock_play, ds, play=self.mock_play,
variable_manager=self.mock_variable_manager, loader=self.fake_loader) variable_manager=self.mock_variable_manager, loader=self.fake_loader)
def test_empty_task_use_handlers(self): def test_empty_task_use_handlers(self):
ds = [{}] ds = [{}]
self.assertRaisesRegexp(errors.AnsibleParserError, self.assertRaisesRegex(errors.AnsibleParserError,
"no module/action detected in task.", "no module/action detected in task.",
helpers.load_list_of_tasks, helpers.load_list_of_tasks,
ds, ds,
use_handlers=True, use_handlers=True,
play=self.mock_play, play=self.mock_play,
variable_manager=self.mock_variable_manager, variable_manager=self.mock_variable_manager,
loader=self.fake_loader) loader=self.fake_loader)
def test_one_bogus_block(self): def test_one_bogus_block(self):
ds = [{'block': None}] ds = [{'block': None}]
self.assertRaisesRegexp(errors.AnsibleParserError, self.assertRaisesRegex(errors.AnsibleParserError,
"A malformed block was encountered", "A malformed block was encountered",
helpers.load_list_of_tasks, helpers.load_list_of_tasks,
ds, play=self.mock_play, ds, play=self.mock_play,
variable_manager=self.mock_variable_manager, loader=self.fake_loader) variable_manager=self.mock_variable_manager, loader=self.fake_loader)
def test_unknown_action(self): def test_unknown_action(self):
action_name = 'foo_test_unknown_action' action_name = 'foo_test_unknown_action'
@ -172,11 +172,11 @@ class TestLoadListOfTasks(unittest.TestCase, MixinForMocks):
def test_one_bogus_block_use_handlers(self): def test_one_bogus_block_use_handlers(self):
ds = [{'block': True}] ds = [{'block': True}]
self.assertRaisesRegexp(errors.AnsibleParserError, self.assertRaisesRegex(errors.AnsibleParserError,
"A malformed block was encountered", "A malformed block was encountered",
helpers.load_list_of_tasks, helpers.load_list_of_tasks,
ds, play=self.mock_play, use_handlers=True, ds, play=self.mock_play, use_handlers=True,
variable_manager=self.mock_variable_manager, loader=self.fake_loader) variable_manager=self.mock_variable_manager, loader=self.fake_loader)
def test_one_bogus_include(self): def test_one_bogus_include(self):
ds = [{'include': 'somefile.yml'}] ds = [{'include': 'somefile.yml'}]
@ -320,11 +320,11 @@ class TestLoadListOfRoles(unittest.TestCase, MixinForMocks):
def test_empty_role(self): def test_empty_role(self):
ds = [{}] ds = [{}]
self.assertRaisesRegexp(errors.AnsibleError, self.assertRaisesRegex(errors.AnsibleError,
"role definitions must contain a role name", "role definitions must contain a role name",
helpers.load_list_of_roles, helpers.load_list_of_roles,
ds, self.mock_play, ds, self.mock_play,
variable_manager=self.mock_variable_manager, loader=self.fake_role_loader) variable_manager=self.mock_variable_manager, loader=self.fake_role_loader)
def test_empty_role_just_name(self): def test_empty_role_just_name(self):
ds = [{'name': 'bogus_role'}] ds = [{'name': 'bogus_role'}]
@ -359,16 +359,16 @@ class TestLoadListOfBlocks(unittest.TestCase, MixinForMocks):
def test_empty_block(self): def test_empty_block(self):
ds = [{}] ds = [{}]
mock_play = MagicMock(name='MockPlay') mock_play = MagicMock(name='MockPlay')
self.assertRaisesRegexp(errors.AnsibleParserError, self.assertRaisesRegex(errors.AnsibleParserError,
"no module/action detected in task", "no module/action detected in task",
helpers.load_list_of_blocks, helpers.load_list_of_blocks,
ds, mock_play, ds, mock_play,
parent_block=None, parent_block=None,
role=None, role=None,
task_include=None, task_include=None,
use_handlers=False, use_handlers=False,
variable_manager=None, variable_manager=None,
loader=None) loader=None)
def test_block_unknown_action(self): def test_block_unknown_action(self):
ds = [{'action': 'foo', 'collections': []}] ds = [{'action': 'foo', 'collections': []}]

@ -346,7 +346,7 @@ class TestActionBase(unittest.TestCase):
self.assertEqual(runWithNoExpectation(execute), remote_paths) self.assertEqual(runWithNoExpectation(execute), remote_paths)
def assertThrowRegex(regex, execute=False): def assertThrowRegex(regex, execute=False):
self.assertRaisesRegexp( self.assertRaisesRegex(
AnsibleError, AnsibleError,
regex, regex,
action_base._fixup_perms2, action_base._fixup_perms2,

@ -185,9 +185,9 @@ class TestFactCache(unittest.TestCase):
# See https://github.com/ansible/ansible/issues/18751 # See https://github.com/ansible/ansible/issues/18751
# Note no fact_connection config set, so this will fail # Note no fact_connection config set, so this will fail
with mock.patch('ansible.constants.CACHE_PLUGIN', 'json'): with mock.patch('ansible.constants.CACHE_PLUGIN', 'json'):
self.assertRaisesRegexp(AnsibleError, self.assertRaisesRegex(AnsibleError,
"Unable to load the facts cache plugin.*json.*", "Unable to load the facts cache plugin.*json.*",
FactCache) FactCache)
def test_update(self): def test_update(self):
self.cache.update({'cache_key': {'key2': 'updatedvalue'}}) self.cache.update({'cache_key': {'key2': 'updatedvalue'}})

@ -56,7 +56,7 @@ class TestCallback(unittest.TestCase):
def test_host_label(self): def test_host_label(self):
result = TaskResult(host=Host('host1'), task=mock_task, return_data={}) result = TaskResult(host=Host('host1'), task=mock_task, return_data={})
self.assertEquals(CallbackBase.host_label(result), 'host1') self.assertEqual(CallbackBase.host_label(result), 'host1')
def test_host_label_delegated(self): def test_host_label_delegated(self):
mock_task.delegate_to = 'host2' mock_task.delegate_to = 'host2'
@ -65,7 +65,7 @@ class TestCallback(unittest.TestCase):
task=mock_task, task=mock_task,
return_data={'_ansible_delegated_vars': {'ansible_host': 'host2'}}, return_data={'_ansible_delegated_vars': {'ansible_host': 'host2'}},
) )
self.assertEquals(CallbackBase.host_label(result), 'host1 -> host2') self.assertEqual(CallbackBase.host_label(result), 'host1 -> host2')
# TODO: import callback module so we can patch callback.cli/callback.C # TODO: import callback module so we can patch callback.cli/callback.C

@ -219,10 +219,10 @@ class TestTemplarTemplate(BaseTemplar, unittest.TestCase):
def test_weird(self): def test_weird(self):
data = u'''1 2 #}huh{# %}ddfg{% }}dfdfg{{ {%what%} {{#foo#}} {%{bar}%} {#%blip%#} {{asdfsd%} 3 4 {{foo}} 5 6 7''' data = u'''1 2 #}huh{# %}ddfg{% }}dfdfg{{ {%what%} {{#foo#}} {%{bar}%} {#%blip%#} {{asdfsd%} 3 4 {{foo}} 5 6 7'''
self.assertRaisesRegexp(AnsibleError, self.assertRaisesRegex(AnsibleError,
'template error while templating string', 'template error while templating string',
self.templar.template, self.templar.template,
data) data)
def test_template_with_error(self): def test_template_with_error(self):
"""Check that AnsibleError is raised, fail if an unhandled exception is raised""" """Check that AnsibleError is raised, fail if an unhandled exception is raised"""
@ -297,21 +297,21 @@ class TestTemplarMisc(BaseTemplar, unittest.TestCase):
class TestTemplarLookup(BaseTemplar, unittest.TestCase): class TestTemplarLookup(BaseTemplar, unittest.TestCase):
def test_lookup_missing_plugin(self): def test_lookup_missing_plugin(self):
self.assertRaisesRegexp(AnsibleError, self.assertRaisesRegex(AnsibleError,
r'lookup plugin \(not_a_real_lookup_plugin\) not found', r'lookup plugin \(not_a_real_lookup_plugin\) not found',
self.templar._lookup, self.templar._lookup,
'not_a_real_lookup_plugin', 'not_a_real_lookup_plugin',
'an_arg', a_keyword_arg='a_keyword_arg_value') 'an_arg', a_keyword_arg='a_keyword_arg_value')
def test_lookup_list(self): def test_lookup_list(self):
res = self.templar._lookup('list', 'an_arg', 'another_arg') res = self.templar._lookup('list', 'an_arg', 'another_arg')
self.assertEqual(res, 'an_arg,another_arg') self.assertEqual(res, 'an_arg,another_arg')
def test_lookup_jinja_undefined(self): def test_lookup_jinja_undefined(self):
self.assertRaisesRegexp(AnsibleUndefinedVariable, self.assertRaisesRegex(AnsibleUndefinedVariable,
"'an_undefined_jinja_var' is undefined", "'an_undefined_jinja_var' is undefined",
self.templar._lookup, self.templar._lookup,
'list', '{{ an_undefined_jinja_var }}') 'list', '{{ an_undefined_jinja_var }}')
def test_lookup_jinja_defined(self): def test_lookup_jinja_defined(self):
res = self.templar._lookup('list', '{{ some_var }}') res = self.templar._lookup('list', '{{ some_var }}')
@ -319,18 +319,18 @@ class TestTemplarLookup(BaseTemplar, unittest.TestCase):
# self.assertIsInstance(res, AnsibleUnsafe) # self.assertIsInstance(res, AnsibleUnsafe)
def test_lookup_jinja_dict_string_passed(self): def test_lookup_jinja_dict_string_passed(self):
self.assertRaisesRegexp(AnsibleError, self.assertRaisesRegex(AnsibleError,
"with_dict expects a dict", "with_dict expects a dict",
self.templar._lookup, self.templar._lookup,
'dict', 'dict',
'{{ some_var }}') '{{ some_var }}')
def test_lookup_jinja_dict_list_passed(self): def test_lookup_jinja_dict_list_passed(self):
self.assertRaisesRegexp(AnsibleError, self.assertRaisesRegex(AnsibleError,
"with_dict expects a dict", "with_dict expects a dict",
self.templar._lookup, self.templar._lookup,
'dict', 'dict',
['foo', 'bar']) ['foo', 'bar'])
def test_lookup_jinja_kwargs(self): def test_lookup_jinja_kwargs(self):
res = self.templar._lookup('list', 'blip', random_keyword='12345') res = self.templar._lookup('list', 'blip', random_keyword='12345')
@ -342,12 +342,12 @@ class TestTemplarLookup(BaseTemplar, unittest.TestCase):
self.assertEqual(res, ["blip"]) self.assertEqual(res, ["blip"])
def test_lookup_jinja_list_wantlist_undefined(self): def test_lookup_jinja_list_wantlist_undefined(self):
self.assertRaisesRegexp(AnsibleUndefinedVariable, self.assertRaisesRegex(AnsibleUndefinedVariable,
"'some_undefined_var' is undefined", "'some_undefined_var' is undefined",
self.templar._lookup, self.templar._lookup,
'list', 'list',
'{{ some_undefined_var }}', '{{ some_undefined_var }}',
wantlist=True) wantlist=True)
def test_lookup_jinja_list_wantlist_unsafe(self): def test_lookup_jinja_list_wantlist_unsafe(self):
res = self.templar._lookup('list', '{{ some_unsafe_var }}', wantlist=True) res = self.templar._lookup('list', '{{ some_unsafe_var }}', wantlist=True)

Loading…
Cancel
Save