Remove Python 2 compat (via six) from unit tests

pull/82112/head
Matt Clay 1 year ago
parent 18e8401edd
commit 5b1b0ce762

@ -10,7 +10,6 @@ import pytest
from ansible.config.manager import ConfigManager, ensure_type, resolve_path, get_config_type
from ansible.errors import AnsibleOptionsError, AnsibleError
from ansible.module_utils.six import integer_types, string_types
from ansible.parsing.yaml.objects import AnsibleVaultEncryptedUnicode
curdir = os.path.dirname(__file__)
@ -39,28 +38,28 @@ ensure_test_data = [
(0, 'bool', bool),
(0.0, 'bool', bool),
(False, 'bool', bool),
('10', 'int', integer_types),
(20, 'int', integer_types),
('10', 'int', int),
(20, 'int', int),
('0.10', 'float', float),
(0.2, 'float', float),
('/tmp/test.yml', 'pathspec', list),
('/tmp/test.yml,/home/test2.yml', 'pathlist', list),
('a', 'str', string_types),
('a', 'string', string_types),
('Café', 'string', string_types),
('', 'string', string_types),
('29', 'str', string_types),
('13.37', 'str', string_types),
('123j', 'string', string_types),
('0x123', 'string', string_types),
('true', 'string', string_types),
('True', 'string', string_types),
(0, 'str', string_types),
(29, 'str', string_types),
(13.37, 'str', string_types),
(123j, 'string', string_types),
(0x123, 'string', string_types),
(True, 'string', string_types),
('a', 'str', str),
('a', 'string', str),
('Café', 'string', str),
('', 'string', str),
('29', 'str', str),
('13.37', 'str', str),
('123j', 'string', str),
('0x123', 'string', str),
('true', 'string', str),
('True', 'string', str),
(0, 'str', str),
(29, 'str', str),
(13.37, 'str', str),
(123j, 'string', str),
(0x123, 'string', str),
(True, 'string', str),
('None', 'none', type(None))
]

@ -26,7 +26,6 @@ from ansible.executor.task_executor import TaskExecutor, remove_omit
from ansible.plugins.loader import action_loader, lookup_loader
from ansible.parsing.yaml.objects import AnsibleUnicode
from ansible.utils.unsafe_proxy import AnsibleUnsafeText, AnsibleUnsafeBytes
from ansible.module_utils.six import text_type
from collections import namedtuple
from units.mock.loader import DictDataLoader
@ -119,8 +118,8 @@ class TestTaskExecutor(unittest.TestCase):
data = res['results'][0]
self.assertIsInstance(data['unsafe_bytes'], AnsibleUnsafeText)
self.assertIsInstance(data['unsafe_text'], AnsibleUnsafeText)
self.assertIsInstance(data['bytes'], text_type)
self.assertIsInstance(data['text'], text_type)
self.assertIsInstance(data['bytes'], str)
self.assertIsInstance(data['text'], str)
self.assertIsInstance(data['int'], int)
def test_task_executor_get_loop_items(self):

@ -23,7 +23,7 @@ from ansible.galaxy import api as galaxy_api
from ansible.galaxy.api import CollectionVersionMetadata, GalaxyAPI, GalaxyError
from ansible.galaxy.token import BasicAuthToken, GalaxyToken, KeycloakToken
from ansible.module_utils.common.text.converters import to_native, to_text
from ansible.module_utils.six.moves.urllib import error as urllib_error
import urllib.error
from ansible.utils import context_objects as co
from ansible.utils.display import Display
@ -324,8 +324,8 @@ def test_initialise_automation_hub(monkeypatch):
def test_initialise_unknown(monkeypatch):
mock_open = MagicMock()
mock_open.side_effect = [
urllib_error.HTTPError('https://galaxy.ansible.com/api/', 500, 'msg', {}, StringIO(u'{"msg":"raw error"}')),
urllib_error.HTTPError('https://galaxy.ansible.com/api/api/', 500, 'msg', {}, StringIO(u'{"msg":"raw error"}')),
urllib.error.HTTPError('https://galaxy.ansible.com/api/', 500, 'msg', {}, StringIO(u'{"msg":"raw error"}')),
urllib.error.HTTPError('https://galaxy.ansible.com/api/api/', 500, 'msg', {}, StringIO(u'{"msg":"raw error"}')),
]
monkeypatch.setattr(galaxy_api, 'open_url', mock_open)
@ -442,7 +442,7 @@ def test_publish_failure(api_version, collection_url, response, expected, collec
expected_url = '%s/api/%s/%s' % (api.api_server, api_version, collection_url)
mock_open = MagicMock()
mock_open.side_effect = urllib_error.HTTPError(expected_url, 500, 'msg', {},
mock_open.side_effect = urllib.error.HTTPError(expected_url, 500, 'msg', {},
StringIO(to_text(json.dumps(response))))
monkeypatch.setattr(galaxy_api, 'open_url', mock_open)
@ -1234,7 +1234,7 @@ def test_cache_flaky_pagination(cache_dir, monkeypatch):
side_effect=[
StringIO(to_text(json.dumps(responses[0]))),
StringIO(to_text(json.dumps(responses[1]))),
urllib_error.HTTPError(responses[1]['next'], 500, 'Error', {}, StringIO()),
urllib.error.HTTPError(responses[1]['next'], 500, 'Error', {}, StringIO()),
StringIO(to_text(json.dumps(responses[3]))),
]
)

@ -23,7 +23,7 @@ from ansible.cli.galaxy import GalaxyCLI
from ansible.errors import AnsibleError
from ansible.galaxy import api, collection, token
from ansible.module_utils.common.text.converters import to_bytes, to_native, to_text
from ansible.module_utils.six.moves import builtins
import builtins
from ansible.utils import context_objects as co
from ansible.utils.display import Display
from ansible.utils.hashing import secure_hash_s

@ -17,7 +17,7 @@ import yaml
from io import BytesIO, StringIO
from unittest.mock import MagicMock, patch
import ansible.module_utils.six.moves.urllib.error as urllib_error
import urllib.error
from ansible import context
from ansible.cli.galaxy import GalaxyCLI
@ -549,7 +549,7 @@ def test_build_requirement_from_name_missing(galaxy_server, monkeypatch, tmp_pat
def test_build_requirement_from_name_401_unauthorized(galaxy_server, monkeypatch, tmp_path_factory):
mock_open = MagicMock()
mock_open.side_effect = api.GalaxyError(urllib_error.HTTPError('https://galaxy.server.com', 401, 'msg', {},
mock_open.side_effect = api.GalaxyError(urllib.error.HTTPError('https://galaxy.server.com', 401, 'msg', {},
StringIO()), "error")
monkeypatch.setattr(galaxy_server, 'get_collection_versions', mock_open)

@ -25,7 +25,6 @@ import unittest
from ansible.inventory.group import Group
from ansible.inventory.host import Host
from ansible.module_utils.six import string_types
class TestHost(unittest.TestCase):
@ -50,7 +49,7 @@ class TestHost(unittest.TestCase):
def test_repr(self):
host_repr = repr(self.hostA)
self.assertIsInstance(host_repr, string_types)
self.assertIsInstance(host_repr, str)
def test_add_group(self):
group = Group('some_group')

@ -24,7 +24,6 @@ import json
from contextlib import contextmanager
from io import BytesIO, StringIO
import unittest
from ansible.module_utils.six import PY3
from ansible.module_utils.common.text.converters import to_bytes
@ -36,11 +35,8 @@ def swap_stdin_and_argv(stdin_data='', argv_data=tuple()):
real_stdin = sys.stdin
real_argv = sys.argv
if PY3:
fake_stream = StringIO(stdin_data)
fake_stream.buffer = BytesIO(to_bytes(stdin_data))
else:
fake_stream = BytesIO(to_bytes(stdin_data))
try:
sys.stdin = fake_stream

@ -16,8 +16,7 @@ from ansible.module_utils import basic
from ansible.module_utils.api import basic_auth_argument_spec, rate_limit_argument_spec, retry_argument_spec
from ansible.module_utils.common import warnings
from ansible.module_utils.common.warnings import get_deprecation_messages, get_warning_messages
from ansible.module_utils.six import integer_types, string_types
from ansible.module_utils.six.moves import builtins
import builtins
MOCK_VALIDATOR_FAIL = MagicMock(side_effect=TypeError("bad conversion"))
@ -216,7 +215,7 @@ def test_validator_basic_types(argspec, expected, stdin):
if 'type' in argspec['arg']:
if argspec['arg']['type'] == 'int':
type_ = integer_types
type_ = int
else:
type_ = getattr(builtins, argspec['arg']['type'])
else:
@ -233,7 +232,7 @@ def test_validator_function(mocker, stdin):
argspec = {'arg': {'type': MOCK_VALIDATOR_SUCCESS}}
am = basic.AnsibleModule(argspec)
assert isinstance(am.params['arg'], integer_types)
assert isinstance(am.params['arg'], int)
assert am.params['arg'] == 27
@ -243,9 +242,9 @@ def test_validate_basic_auth_arg(mocker, stdin):
argument_spec=basic_auth_argument_spec()
)
am = basic.AnsibleModule(**kwargs)
assert isinstance(am.params['api_username'], string_types)
assert isinstance(am.params['api_password'], string_types)
assert isinstance(am.params['api_url'], string_types)
assert isinstance(am.params['api_username'], str)
assert isinstance(am.params['api_password'], str)
assert isinstance(am.params['api_url'], str)
assert isinstance(am.params['validate_certs'], bool)
@ -255,8 +254,8 @@ def test_validate_rate_limit_argument_spec(mocker, stdin):
argument_spec=rate_limit_argument_spec()
)
am = basic.AnsibleModule(**kwargs)
assert isinstance(am.params['rate'], integer_types)
assert isinstance(am.params['rate_limit'], integer_types)
assert isinstance(am.params['rate'], int)
assert isinstance(am.params['rate_limit'], int)
@pytest.mark.parametrize('stdin', RETRY_VALID_ARGS, indirect=['stdin'])
@ -265,7 +264,7 @@ def test_validate_retry_argument_spec(mocker, stdin):
argument_spec=retry_argument_spec()
)
am = basic.AnsibleModule(**kwargs)
assert isinstance(am.params['retries'], integer_types)
assert isinstance(am.params['retries'], int)
assert isinstance(am.params['retry_pause'], float)
@ -275,7 +274,7 @@ def test_validator_string_type(mocker, stdin):
argspec = {'arg': {'type': str}}
am = basic.AnsibleModule(argspec)
assert isinstance(am.params['arg'], string_types)
assert isinstance(am.params['arg'], str)
assert am.params['arg'] == '123'
@ -416,8 +415,8 @@ class TestComplexArgSpecs:
"""Test choices with list"""
am = basic.AnsibleModule(**complex_argspec)
assert isinstance(am.params['bar_str'], list)
assert isinstance(am.params['bar_str'][0], string_types)
assert isinstance(am.params['bar_str'][1], string_types)
assert isinstance(am.params['bar_str'][0], str)
assert isinstance(am.params['bar_str'][1], str)
assert am.params['bar_str'][0] == '867'
assert am.params['bar_str'][1] == '5309'

@ -8,7 +8,7 @@ from __future__ import annotations
from units.mock.procenv import ModuleTestCase
from ansible.module_utils.six.moves import builtins
import builtins
realimport = builtins.__import__

@ -9,7 +9,7 @@ from __future__ import annotations
from units.mock.procenv import ModuleTestCase
from unittest.mock import patch, MagicMock
from ansible.module_utils.six.moves import builtins
import builtins
realimport = builtins.__import__

@ -9,7 +9,7 @@ from __future__ import annotations
from units.mock.procenv import ModuleTestCase
from unittest.mock import patch
from ansible.module_utils.six.moves import builtins
import builtins
realimport = builtins.__import__

@ -11,7 +11,7 @@ import sys
from units.mock.procenv import ModuleTestCase
from unittest.mock import patch
from ansible.module_utils.six.moves import builtins
import builtins
realimport = builtins.__import__

@ -11,7 +11,6 @@ from itertools import product
import pytest
import ansible.module_utils.basic
from ansible.module_utils.six import PY3
class TestAnsibleModuleLogSmokeTest:
@ -54,15 +53,7 @@ class TestAnsibleModuleLogSmokeTest:
class TestAnsibleModuleLogSyslog:
"""Test the AnsibleModule Log Method"""
PY2_OUTPUT_DATA = [
(u'Text string', b'Text string'),
(u'Toshio くらとみ non-ascii test', u'Toshio くらとみ non-ascii test'.encode('utf-8')),
(b'Byte string', b'Byte string'),
(u'Toshio くらとみ non-ascii test'.encode('utf-8'), u'Toshio くらとみ non-ascii test'.encode('utf-8')),
(b'non-utf8 :\xff: test', b'non-utf8 :\xff: test'.decode('utf-8', 'replace').encode('utf-8')),
]
PY3_OUTPUT_DATA = [
OUTPUT_DATA = [
(u'Text string', u'Text string'),
(u'Toshio くらとみ non-ascii test', u'Toshio くらとみ non-ascii test'),
(b'Byte string', u'Byte string'),
@ -70,8 +61,6 @@ class TestAnsibleModuleLogSyslog:
(b'non-utf8 :\xff: test', b'non-utf8 :\xff: test'.decode('utf-8', 'replace')),
]
OUTPUT_DATA = PY3_OUTPUT_DATA if PY3 else PY2_OUTPUT_DATA
@pytest.mark.parametrize('no_log, stdin', (product((True, False), [{}])), indirect=['stdin'])
def test_no_log(self, am, mocker, no_log):
"""Test that when no_log is set, logging does not occur"""

@ -10,7 +10,7 @@ import pytest
from unittest.mock import patch
from ansible.module_utils.six.moves import builtins
import builtins
# Functions being tested
from ansible.module_utils.basic import get_platform

@ -12,7 +12,6 @@ from io import BytesIO
import pytest
from ansible.module_utils.common.text.converters import to_native
from ansible.module_utils.six import PY2
class OpenBytesIO(BytesIO):
@ -267,10 +266,5 @@ def test_run_command_fds(mocker, rc_am):
except SystemExit:
pass
if PY2:
assert subprocess_mock.Popen.call_args[1]['close_fds'] is False
assert 'pass_fds' not in subprocess_mock.Popen.call_args[1]
else:
assert subprocess_mock.Popen.call_args[1]['pass_fds'] == (101, 42)
assert subprocess_mock.Popen.call_args[1]['close_fds'] is True

@ -14,7 +14,7 @@ from unittest.mock import mock_open, patch
from ansible.module_utils import basic
from ansible.module_utils.common.text.converters import to_bytes
from ansible.module_utils.six.moves import builtins
import builtins
@pytest.fixture

@ -8,7 +8,6 @@ import pytest
from ansible.module_utils.common.arg_spec import ArgumentSpecValidator, ValidationResult
from ansible.module_utils.errors import AnsibleValidationErrorMultiple
from ansible.module_utils.six import PY2
# Each item is id, argument_spec, parameters, expected, unsupported parameters, error test string
@ -123,9 +122,6 @@ def test_invalid_spec(arg_spec, parameters, expected, unsupported, error):
with pytest.raises(AnsibleValidationErrorMultiple) as exc_info:
raise result.errors
if PY2:
error = error.replace('class', 'type')
assert isinstance(result, ValidationResult)
assert error in exc_info.value.msg
assert error in result.error_messages[0]

@ -7,7 +7,7 @@ from __future__ import annotations
import pytest
from ansible.module_utils.six.moves.collections_abc import Sequence
from collections.abc import Sequence
from ansible.module_utils.common.collections import ImmutableDict, is_iterable, is_sequence

@ -10,7 +10,7 @@ import pytest
from unittest.mock import patch
from ansible.module_utils.six.moves import builtins
import builtins
# Functions being tested
from ansible.module_utils.common.sys_info import get_distribution

@ -9,8 +9,6 @@ import itertools
import pytest
from ansible.module_utils.six import PY3
from ansible.module_utils.common.text.converters import to_text, to_bytes, to_native
@ -42,8 +40,8 @@ def test_to_bytes(in_string, encoding, expected):
@pytest.mark.parametrize('in_string, encoding, expected',
itertools.chain(((d[0], d[2], d[1] if PY3 else d[0]) for d in VALID_STRINGS),
((d[1], d[2], d[1] if PY3 else d[0]) for d in VALID_STRINGS)))
itertools.chain(((d[0], d[2], d[1]) for d in VALID_STRINGS),
((d[1], d[2], d[1]) for d in VALID_STRINGS)))
def test_to_native(in_string, encoding, expected):
"""test happy path of encoding to native strings"""
assert to_native(in_string, encoding) == expected

@ -9,7 +9,6 @@ import pytest
from ansible.module_utils.common import warnings
from ansible.module_utils.common.warnings import deprecate, get_deprecation_messages
from ansible.module_utils.six import PY3
@pytest.fixture
@ -91,7 +90,7 @@ def test_get_deprecation_messages(deprecation_messages, reset):
{'k1': 'v1'},
(1, 2),
6.62607004,
b'bytestr' if PY3 else None,
b'bytestr',
None,
)
)

@ -9,7 +9,6 @@ import pytest
from ansible.module_utils.common import warnings
from ansible.module_utils.common.warnings import warn, get_warning_messages
from ansible.module_utils.six import PY3
@pytest.fixture
@ -51,7 +50,7 @@ def test_get_warning_messages(warning_messages):
{'k1': 'v1'},
(1, 2),
6.62607004,
b'bytestr' if PY3 else None,
b'bytestr',
None,
)
)

@ -3,17 +3,12 @@ from __future__ import annotations
import datetime
from ansible.module_utils.compat.datetime import utcnow, utcfromtimestamp, UTC
from ansible.module_utils.six import PY3
def test_utc():
assert UTC.tzname(None) == 'UTC'
assert UTC.utcoffset(None) == datetime.timedelta(0)
if PY3:
assert UTC.dst(None) is None
else:
assert UTC.dst(None) == datetime.timedelta(0)
def test_utcnow():

@ -10,9 +10,8 @@ from io import BytesIO
import pytest
import ansible.module_utils.basic
from ansible.module_utils.six import PY3, string_types
from ansible.module_utils.common.text.converters import to_bytes
from ansible.module_utils.six.moves.collections_abc import MutableMapping
from collections.abc import MutableMapping
@pytest.fixture
@ -22,7 +21,7 @@ def stdin(mocker, request):
old_argv = sys.argv
sys.argv = ['ansible_unittest']
if isinstance(request.param, string_types):
if isinstance(request.param, str):
args = request.param
elif isinstance(request.param, MutableMapping):
if 'ANSIBLE_MODULE_ARGS' not in request.param:
@ -36,11 +35,9 @@ def stdin(mocker, request):
raise Exception('Malformed data to the stdin pytest fixture')
fake_stdin = BytesIO(to_bytes(args, errors='surrogate_or_strict'))
if PY3:
mocker.patch('ansible.module_utils.basic.sys.stdin', mocker.MagicMock())
mocker.patch('ansible.module_utils.basic.sys.stdin.buffer', fake_stdin)
else:
mocker.patch('ansible.module_utils.basic.sys.stdin', fake_stdin)
yield fake_stdin

@ -10,7 +10,7 @@ import os
import pytest
from itertools import product
from ansible.module_utils.six.moves import builtins
import builtins
# the module we are actually testing (sort of)
from ansible.module_utils.facts.system.distribution import DistributionFactCollector

@ -15,7 +15,6 @@
from __future__ import annotations
from ansible.module_utils import distro
from ansible.module_utils.six import string_types
# Generic test case with minimal assertions about specific returned values.
@ -29,7 +28,7 @@ class TestDistro():
def test_id(self):
id = distro.id()
assert isinstance(id, string_types), 'distro.id() returned %s (%s) which is not a string' % (id, type(id))
assert isinstance(id, str), 'distro.id() returned %s (%s) which is not a string' % (id, type(id))
def test_opensuse_leap_id(self):
name = distro.name()

@ -3,7 +3,6 @@ from __future__ import annotations
import codecs
from ansible.module_utils.common.text.converters import to_bytes, to_native, to_text
from ansible.module_utils.six import PY3, text_type, binary_type
def test_exports():
@ -12,9 +11,9 @@ def test_exports():
from ansible.module_utils import _text
assert _text.codecs == codecs
assert _text.PY3 == PY3
assert _text.text_type == text_type
assert _text.binary_type == binary_type
assert _text.PY3 is True
assert _text.text_type is str
assert _text.binary_type is bytes
assert _text.to_bytes == to_bytes
assert _text.to_native == to_native
assert _text.to_text == to_text

@ -5,7 +5,7 @@
from __future__ import annotations
from ansible.module_utils.urls import generic_urlparse
from ansible.module_utils.six.moves.urllib.parse import urlparse, urlunparse
from urllib.parse import urlparse, urlunparse
def test_generic_urlparse():

@ -8,7 +8,6 @@ from unittest.mock import patch, MagicMock, mock_open
from ansible.module_utils.common._utils import get_all_subclasses
from ansible.modules import hostname
from units.modules.utils import ModuleTestCase, set_module_args
from ansible.module_utils.six import PY2
class TestHostname(ModuleTestCase):
@ -27,8 +26,6 @@ class TestHostname(ModuleTestCase):
m = mock_open()
builtins = 'builtins'
if PY2:
builtins = '__builtin__'
with patch('%s.open' % builtins, m):
instance.get_permanent_hostname()
instance.get_current_hostname()

@ -11,7 +11,6 @@ import platform
import pytest
from ansible.modules import service
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.six import PY2
from units.modules.utils import set_module_args
@ -28,7 +27,7 @@ def mocker_sunos_service(mocker):
# Read a mocked /etc/release file
mocked_etc_release_data = mocker.mock_open(
read_data=" Oracle Solaris 12.0")
builtin_open = "__builtin__.open" if PY2 else "builtins.open"
builtin_open = "builtins.open"
mocker.patch(builtin_open, mocked_etc_release_data)
service_status = mocker.patch.object(

@ -30,7 +30,6 @@ import unittest
from unittest.mock import patch, MagicMock
from ansible import errors
from ansible.module_utils import six
from ansible.module_utils.common.text.converters import to_bytes, to_text
from ansible.parsing import vault
@ -505,7 +504,7 @@ class TestVaultCipherAes256(unittest.TestCase):
b_password = b'hunter42'
b_salt = os.urandom(32)
b_key_cryptography = self.vault_cipher._create_key_cryptography(b_password, b_salt, key_length=32, iv_length=16)
self.assertIsInstance(b_key_cryptography, six.binary_type)
self.assertIsInstance(b_key_cryptography, bytes)
def test_create_key_known_cryptography(self):
b_password = b'hunter42'
@ -513,13 +512,13 @@ class TestVaultCipherAes256(unittest.TestCase):
# A fixed salt
b_salt = b'q' * 32 # q is the most random letter.
b_key_1 = self.vault_cipher._create_key_cryptography(b_password, b_salt, key_length=32, iv_length=16)
self.assertIsInstance(b_key_1, six.binary_type)
self.assertIsInstance(b_key_1, bytes)
# verify we get the same answer
# we could potentially run a few iterations of this and time it to see if it's roughly constant time
# and or that it exceeds some minimal time, but that would likely cause unreliable fails, esp in CI
b_key_2 = self.vault_cipher._create_key_cryptography(b_password, b_salt, key_length=32, iv_length=16)
self.assertIsInstance(b_key_2, six.binary_type)
self.assertIsInstance(b_key_2, bytes)
self.assertEqual(b_key_1, b_key_2)
def test_is_equal_is_equal(self):
@ -610,7 +609,7 @@ class TestVaultLib(unittest.TestCase):
plaintext = u'Some text to encrypt in a café'
b_vaulttext = self.v.encrypt(plaintext)
self.assertIsInstance(b_vaulttext, six.binary_type)
self.assertIsInstance(b_vaulttext, bytes)
b_header = b'$ANSIBLE_VAULT;1.1;AES256\n'
self.assertEqual(b_vaulttext[:len(b_header)], b_header)
@ -619,7 +618,7 @@ class TestVaultLib(unittest.TestCase):
plaintext = u'Some text to encrypt in a café'
b_vaulttext = self.v.encrypt(plaintext, vault_id='test_id')
self.assertIsInstance(b_vaulttext, six.binary_type)
self.assertIsInstance(b_vaulttext, bytes)
b_header = b'$ANSIBLE_VAULT;1.2;AES256;test_id\n'
self.assertEqual(b_vaulttext[:len(b_header)], b_header)
@ -629,7 +628,7 @@ class TestVaultLib(unittest.TestCase):
plaintext = to_bytes(u'Some text to encrypt in a café')
b_vaulttext = self.v.encrypt(plaintext)
self.assertIsInstance(b_vaulttext, six.binary_type)
self.assertIsInstance(b_vaulttext, bytes)
b_header = b'$ANSIBLE_VAULT;1.1;AES256\n'
self.assertEqual(b_vaulttext[:len(b_header)], b_header)

@ -24,7 +24,6 @@ from io import StringIO
import unittest
from ansible import errors
from ansible.module_utils.six import text_type, binary_type
from ansible.parsing.yaml.loader import AnsibleLoader
from ansible.parsing import vault
from ansible.parsing.yaml.objects import AnsibleVaultEncryptedUnicode
@ -64,7 +63,7 @@ class TestAnsibleLoaderBasic(unittest.TestCase):
loader = AnsibleLoader(stream, 'myfile.yml')
data = loader.get_single_data()
self.assertEqual(data, u'Ansible')
self.assertIsInstance(data, text_type)
self.assertIsInstance(data, str)
self.assertEqual(data.ansible_pos, ('myfile.yml', 2, 17))
@ -75,7 +74,7 @@ class TestAnsibleLoaderBasic(unittest.TestCase):
loader = AnsibleLoader(stream, 'myfile.yml')
data = loader.get_single_data()
self.assertEqual(data, u'Cafè Eñyei')
self.assertIsInstance(data, text_type)
self.assertIsInstance(data, str)
self.assertEqual(data.ansible_pos, ('myfile.yml', 2, 17))
@ -88,8 +87,8 @@ class TestAnsibleLoaderBasic(unittest.TestCase):
data = loader.get_single_data()
self.assertEqual(data, {'webster': 'daniel', 'oed': 'oxford'})
self.assertEqual(len(data), 2)
self.assertIsInstance(list(data.keys())[0], text_type)
self.assertIsInstance(list(data.values())[0], text_type)
self.assertIsInstance(list(data.keys())[0], str)
self.assertIsInstance(list(data.values())[0], str)
# Beginning of the first key
self.assertEqual(data.ansible_pos, ('myfile.yml', 2, 17))
@ -106,7 +105,7 @@ class TestAnsibleLoaderBasic(unittest.TestCase):
data = loader.get_single_data()
self.assertEqual(data, [u'a', u'b'])
self.assertEqual(len(data), 2)
self.assertIsInstance(data[0], text_type)
self.assertIsInstance(data[0], str)
self.assertEqual(data.ansible_pos, ('myfile.yml', 2, 17))
@ -353,10 +352,10 @@ class TestAnsibleLoaderPlay(unittest.TestCase):
def walk(self, data):
# Make sure there's no str in the data
self.assertNotIsInstance(data, binary_type)
self.assertNotIsInstance(data, bytes)
# Descend into various container types
if isinstance(data, text_type):
if isinstance(data, str):
# strings are a sequence so we have to be explicit here
return
elif isinstance(data, (Sequence, Set)):

@ -20,7 +20,6 @@ from __future__ import annotations
import unittest
from ansible.errors import AnsibleParserError, AnsibleAssertionError
from ansible.module_utils.six import string_types
from ansible.playbook.attribute import FieldAttribute, NonInheritableFieldAttribute
from ansible.template import Templar
from ansible.playbook import base
@ -334,9 +333,9 @@ class BaseSubClass(base.Base):
test_attr_bool = FieldAttribute(isa='bool', always_post_validate=True)
test_attr_int = FieldAttribute(isa='int', always_post_validate=True)
test_attr_float = FieldAttribute(isa='float', default=3.14159, always_post_validate=True)
test_attr_list = FieldAttribute(isa='list', listof=string_types, always_post_validate=True)
test_attr_list = FieldAttribute(isa='list', listof=(str,), always_post_validate=True)
test_attr_list_no_listof = FieldAttribute(isa='list', always_post_validate=True)
test_attr_list_required = FieldAttribute(isa='list', listof=string_types, required=True,
test_attr_list_required = FieldAttribute(isa='list', listof=(str,), required=True,
default=list, always_post_validate=True)
test_attr_string = FieldAttribute(isa='string', default='the_test_attr_string_default_value')
test_attr_string_required = FieldAttribute(isa='string', required=True,

@ -27,8 +27,8 @@ import unittest
from unittest.mock import patch, MagicMock, mock_open
from ansible.errors import AnsibleError, AnsibleAuthenticationFailure
from ansible.module_utils.six import text_type
from ansible.module_utils.six.moves import shlex_quote, builtins
import builtins
import shlex
from ansible.module_utils.common.text.converters import to_bytes
from ansible.playbook.play_context import PlayContext
from ansible.plugins.action import ActionBase
@ -195,7 +195,7 @@ class TestActionBase(unittest.TestCase):
# create a mock connection, so we don't actually try and connect to things
def env_prefix(**args):
return ' '.join(['%s=%s' % (k, shlex_quote(text_type(v))) for k, v in args.items()])
return ' '.join(['%s=%s' % (k, shlex.quote(str(v))) for k, v in args.items()])
mock_connection = MagicMock()
mock_connection._shell.env_prefix.side_effect = env_prefix

@ -27,7 +27,7 @@ from ansible.errors import AnsibleAuthenticationFailure
import unittest
from unittest.mock import patch, MagicMock, PropertyMock
from ansible.errors import AnsibleError, AnsibleConnectionFailure, AnsibleFileNotFound
from ansible.module_utils.six.moves import shlex_quote
import shlex
from ansible.module_utils.common.text.converters import to_bytes
from ansible.playbook.play_context import PlayContext
from ansible.plugins.connection import ssh
@ -246,7 +246,7 @@ class TestConnectionBaseClass(unittest.TestCase):
# Test with SCP_IF_SSH set to smart
# Test when SFTP works
conn.set_option('scp_if_ssh', 'smart')
expected_in_data = b' '.join((b'put', to_bytes(shlex_quote('/path/to/in/file')), to_bytes(shlex_quote('/path/to/dest/file')))) + b'\n'
expected_in_data = b' '.join((b'put', to_bytes(shlex.quote('/path/to/in/file')), to_bytes(shlex.quote('/path/to/dest/file')))) + b'\n'
conn.put_file('/path/to/in/file', '/path/to/dest/file')
conn._bare_run.assert_called_with('some command to run', expected_in_data, checkrc=False)
@ -266,13 +266,13 @@ class TestConnectionBaseClass(unittest.TestCase):
# test with SCPP_IF_SSH disabled
conn.set_option('scp_if_ssh', False)
expected_in_data = b' '.join((b'put', to_bytes(shlex_quote('/path/to/in/file')), to_bytes(shlex_quote('/path/to/dest/file')))) + b'\n'
expected_in_data = b' '.join((b'put', to_bytes(shlex.quote('/path/to/in/file')), to_bytes(shlex.quote('/path/to/dest/file')))) + b'\n'
conn.put_file('/path/to/in/file', '/path/to/dest/file')
conn._bare_run.assert_called_with('some command to run', expected_in_data, checkrc=False)
expected_in_data = b' '.join((b'put',
to_bytes(shlex_quote('/path/to/in/file/with/unicode-fö〩')),
to_bytes(shlex_quote('/path/to/dest/file/with/unicode-fö〩')))) + b'\n'
to_bytes(shlex.quote('/path/to/in/file/with/unicode-fö〩')),
to_bytes(shlex.quote('/path/to/dest/file/with/unicode-fö〩')))) + b'\n'
conn.put_file(u'/path/to/in/file/with/unicode-fö〩', u'/path/to/dest/file/with/unicode-fö〩')
conn._bare_run.assert_called_with('some command to run', expected_in_data, checkrc=False)
@ -304,7 +304,7 @@ class TestConnectionBaseClass(unittest.TestCase):
# Test with SCP_IF_SSH set to smart
# Test when SFTP works
conn.set_option('scp_if_ssh', 'smart')
expected_in_data = b' '.join((b'get', to_bytes(shlex_quote('/path/to/in/file')), to_bytes(shlex_quote('/path/to/dest/file')))) + b'\n'
expected_in_data = b' '.join((b'get', to_bytes(shlex.quote('/path/to/in/file')), to_bytes(shlex.quote('/path/to/dest/file')))) + b'\n'
conn.set_options({})
conn.fetch_file('/path/to/in/file', '/path/to/dest/file')
conn._bare_run.assert_called_with('some command to run', expected_in_data, checkrc=False)
@ -326,13 +326,13 @@ class TestConnectionBaseClass(unittest.TestCase):
# test with SCP_IF_SSH disabled
conn.set_option('scp_if_ssh', False)
expected_in_data = b' '.join((b'get', to_bytes(shlex_quote('/path/to/in/file')), to_bytes(shlex_quote('/path/to/dest/file')))) + b'\n'
expected_in_data = b' '.join((b'get', to_bytes(shlex.quote('/path/to/in/file')), to_bytes(shlex.quote('/path/to/dest/file')))) + b'\n'
conn.fetch_file('/path/to/in/file', '/path/to/dest/file')
conn._bare_run.assert_called_with('some command to run', expected_in_data, checkrc=False)
expected_in_data = b' '.join((b'get',
to_bytes(shlex_quote('/path/to/in/file/with/unicode-fö〩')),
to_bytes(shlex_quote('/path/to/dest/file/with/unicode-fö〩')))) + b'\n'
to_bytes(shlex.quote('/path/to/in/file/with/unicode-fö〩')),
to_bytes(shlex.quote('/path/to/dest/file/with/unicode-fö〩')))) + b'\n'
conn.fetch_file(u'/path/to/in/file/with/unicode-fö〩', u'/path/to/dest/file/with/unicode-fö〩')
conn._bare_run.assert_called_with('some command to run', expected_in_data, checkrc=False)

@ -24,7 +24,6 @@ from unittest import mock
from ansible import constants as C
import unittest
from ansible.module_utils.six import string_types
from ansible.module_utils.common.text.converters import to_text
from units.mock.path import mock_unfrackpath_noop
@ -158,8 +157,8 @@ class TestInventoryPlugins(unittest.TestCase):
variables = inventory.get_host('host1').vars
for i in range(len(values)):
if isinstance(values[i], string_types):
self.assertIsInstance(variables['var%s' % i], string_types)
if isinstance(values[i], str):
self.assertIsInstance(variables['var%s' % i], str)
else:
self.assertIsInstance(variables['var%s' % i], type(values[i]))

@ -32,8 +32,7 @@ from units.mock.loader import DictDataLoader
import unittest
from unittest.mock import mock_open, patch
from ansible.errors import AnsibleError
from ansible.module_utils.six import text_type
from ansible.module_utils.six.moves import builtins
import builtins
from ansible.module_utils.common.text.converters import to_bytes
from ansible.plugins.loader import PluginLoader, lookup_loader
from ansible.plugins.lookup import password
@ -274,13 +273,13 @@ class TestRandomPassword(unittest.TestCase):
def test_default(self):
res = password.random_password()
self.assertEqual(len(res), DEFAULT_LENGTH)
self.assertTrue(isinstance(res, text_type))
self.assertTrue(isinstance(res, str))
self._assert_valid_chars(res, DEFAULT_CANDIDATE_CHARS)
def test_zero_length(self):
res = password.random_password(length=0)
self.assertEqual(len(res), 0)
self.assertTrue(isinstance(res, text_type))
self.assertTrue(isinstance(res, str))
self._assert_valid_chars(res, u',')
def test_just_a_common(self):
@ -435,7 +434,7 @@ class TestLookupModuleWithoutPasslib(BaseTestLookupModule):
# FIXME: assert something useful
for result in results:
assert len(result) == DEFAULT_LENGTH
assert isinstance(result, text_type)
assert isinstance(result, str)
@patch.object(PluginLoader, '_get_paths')
@patch('ansible.plugins.lookup.password._write_password_file')
@ -518,7 +517,7 @@ class TestLookupModuleWithPasslib(BaseTestLookupModule):
# verify the string and parsehash agree on the number of rounds
self.assertEqual(int(str_parts[2]), crypt_parts['rounds'])
self.assertIsInstance(result, text_type)
self.assertIsInstance(result, str)
@patch('ansible.plugins.lookup.password._write_password_file')
def test_password_already_created_encrypt(self, mock_write_file):
@ -554,7 +553,7 @@ class TestLookupModuleWithPasslibWrappedAlgo(BaseTestLookupModule):
self.assertEqual(len(results), 1)
result = results[0]
self.assertIsInstance(result, text_type)
self.assertIsInstance(result, str)
expected_password_length = 76
self.assertEqual(len(result), expected_password_length)

@ -8,7 +8,6 @@ import re
import sys
from importlib import import_module
from ansible.module_utils.six import PY3, string_types
from ansible.modules import ping as ping_module
from ansible.utils.collection_loader import AnsibleCollectionConfig, AnsibleCollectionRef
from ansible.utils.collection_loader._collection_finder import (
@ -37,7 +36,7 @@ def teardown(*args, **kwargs):
r'FileFinder\.find_loader\(\) is deprecated and slated for removal in Python 3\.12; use find_spec\(\) instead'
':DeprecationWarning',
)
@pytest.mark.skipif(not PY3 or sys.version_info >= (3, 12), reason='Testing Python 2 codepath (find_module) on Python 3, <= 3.11')
@pytest.mark.skipif(sys.version_info >= (3, 12), reason='Testing Python 2 codepath (find_module) on Python 3, <= 3.11')
def test_find_module_py3_lt_312():
dir_to_a_file = os.path.dirname(ping_module.__file__)
path_hook_finder = _AnsiblePathHookFinder(_AnsibleCollectionFinder(), dir_to_a_file)
@ -298,10 +297,7 @@ def test_path_hook_setup():
except Exception as phe:
pathhook_exc = phe
if PY3:
assert str(pathhook_exc) == 'need exactly one FileFinder import hook (found 0)'
else:
assert found_hook is None
assert repr(_AnsiblePathHookFinder(object(), '/bogus/path')) == "_AnsiblePathHookFinder(path='/bogus/path')"
@ -819,7 +815,7 @@ def test_collectionref_components_valid(name, subdirs, resource, ref_type, pytho
]
)
def test_legacy_plugin_dir_to_plugin_type(dirname, expected_result):
if isinstance(expected_result, string_types):
if isinstance(expected_result, str):
assert AnsibleCollectionRef.legacy_plugin_dir_to_plugin_type(dirname) == expected_result
else:
with pytest.raises(expected_result):

@ -22,7 +22,6 @@ import os
import unittest
from unittest.mock import MagicMock, patch
from ansible.inventory.manager import InventoryManager
from ansible.module_utils.six import iteritems
from ansible.playbook.play import Play
@ -57,7 +56,7 @@ class TestVariableManager(unittest.TestCase):
v._extra_vars = extra_vars
myvars = v.get_vars(use_cache=False)
for (key, val) in iteritems(extra_vars):
for key, val in extra_vars.items():
self.assertEqual(myvars.get(key), val)
def test_variable_manager_options_vars(self):
@ -71,7 +70,7 @@ class TestVariableManager(unittest.TestCase):
v._extra_vars = options_vars
myvars = v.get_vars(use_cache=False)
for (key, val) in iteritems(options_vars):
for key, val in options_vars.items():
self.assertEqual(myvars.get(key), val)
def test_variable_manager_play_vars(self):

Loading…
Cancel
Save