1
0
Fork 0
mirror of https://github.com/ansible-collections/community.general.git synced 2026-02-04 07:51:50 +00:00

straight up: ruff format (#11329)

* straight up: ruff format

* Apply suggestions from code review
This commit is contained in:
Alexei Znamensky 2025-12-28 01:36:24 +13:00 committed by GitHub
parent 04d0a4daf3
commit d549baa5e1
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
36 changed files with 438 additions and 396 deletions

View file

@ -9,43 +9,49 @@ def callback_results_extractor(outputs_results):
results = []
for result in outputs_results:
differences = []
expected_output = result['test']['expected_output']
stdout_lines = result['stdout_lines']
expected_output = result["test"]["expected_output"]
stdout_lines = result["stdout_lines"]
for i in range(max(len(expected_output), len(stdout_lines))):
line = "line_%s" % (i + 1)
test_line = stdout_lines[i] if i < len(stdout_lines) else None
expected_lines = expected_output[i] if i < len(expected_output) else None
if not isinstance(expected_lines, str) and expected_lines is not None:
if test_line not in expected_lines:
differences.append({
'line': {
'expected_one_of': expected_lines,
'got': test_line,
differences.append(
{
"line": {
"expected_one_of": expected_lines,
"got": test_line,
}
}
})
)
else:
if test_line != expected_lines:
differences.append({
'line': {
'expected': expected_lines,
'got': test_line,
differences.append(
{
"line": {
"expected": expected_lines,
"got": test_line,
}
}
})
results.append({
'name': result['test']['name'],
'output': {
'differences': differences,
'expected': expected_output,
'got': stdout_lines,
},
})
)
results.append(
{
"name": result["test"]["name"],
"output": {
"differences": differences,
"expected": expected_output,
"got": stdout_lines,
},
}
)
return results
class FilterModule:
''' Jinja2 compat filters '''
"""Jinja2 compat filters"""
def filters(self):
return {
'callback_results_extractor': callback_results_extractor,
"callback_results_extractor": callback_results_extractor,
}

View file

@ -11,20 +11,21 @@ from ansible.plugins.action import ActionBase
try:
from ansible.utils.datatag import trust_value as _trust_value
except ImportError:
def _trust_value(input):
return input
class ActionModule(ActionBase):
''' Fail with custom message '''
"""Fail with custom message"""
_requires_connection = False
_VALID_ARGS = frozenset(('msg', 'that'))
_VALID_ARGS = frozenset(("msg", "that"))
def _make_safe(self, text):
# A simple str(text) won't do it since AnsibleUnsafeText is clever :-)
return ''.join(chr(ord(x)) for x in text)
return "".join(chr(ord(x)) for x in text)
def run(self, tmp=None, task_vars=None):
if task_vars is None:
@ -33,18 +34,18 @@ class ActionModule(ActionBase):
result = super(ActionModule, self).run(tmp, task_vars)
del tmp # tmp no longer has any effect
if 'that' not in self._task.args:
if "that" not in self._task.args:
raise AnsibleError('conditional required in "that" string')
fail_msg = 'Assertion failed'
success_msg = 'All assertions passed'
fail_msg = "Assertion failed"
success_msg = "All assertions passed"
thats = self._task.args['that']
thats = self._task.args["that"]
result['_ansible_verbose_always'] = True
result["_ansible_verbose_always"] = True
for that in thats:
if hasattr(self._templar, 'evaluate_conditional'):
if hasattr(self._templar, "evaluate_conditional"):
trusted_that = _trust_value(that) if _trust_value else that
test_result = self._templar.evaluate_conditional(conditional=trusted_that)
else:
@ -52,14 +53,14 @@ class ActionModule(ActionBase):
cond.when = [str(self._make_safe(that))]
test_result = cond.evaluate_conditional(templar=self._templar, all_vars=task_vars)
if not test_result:
result['failed'] = True
result['evaluated_to'] = test_result
result['assertion'] = that
result["failed"] = True
result["evaluated_to"] = test_result
result["assertion"] = that
result['msg'] = fail_msg
result["msg"] = fail_msg
return result
result['changed'] = False
result['msg'] = success_msg
result["changed"] = False
result["msg"] = success_msg
return result

View file

@ -37,17 +37,19 @@ def main():
info = None
arg_formats = {}
for arg, fmt_spec in p['arg_formats'].items():
func = getattr(fmt, fmt_spec['func'])
for arg, fmt_spec in p["arg_formats"].items():
func = getattr(fmt, fmt_spec["func"])
args = fmt_spec.get("args", [])
arg_formats[arg] = func(*args)
try:
runner = CmdRunner(module, [module.params["cmd"], '--'], arg_formats=arg_formats, path_prefix=module.params["path_prefix"])
runner = CmdRunner(
module, [module.params["cmd"], "--"], arg_formats=arg_formats, path_prefix=module.params["path_prefix"]
)
with runner.context(p['arg_order'], check_mode_skip=p['check_mode_skip']) as ctx:
result = ctx.run(**p['arg_values'])
with runner.context(p["arg_order"], check_mode_skip=p["check_mode_skip"]) as ctx:
result = ctx.run(**p["arg_values"])
info = ctx.run_info
check = "check"
rc, out, err = result if result is not None else (None, None, None)
@ -57,5 +59,5 @@ def main():
module.fail_json(rc=1, module_stderr=traceback.format_exc(), msg="Module crashed with exception")
if __name__ == '__main__':
if __name__ == "__main__":
main()

View file

@ -3,4 +3,4 @@
# SPDX-License-Identifier: GPL-3.0-or-later
# single_app_project/core/settings.py
SECRET_KEY = 'testtesttesttesttest'
SECRET_KEY = "testtesttesttesttest"

View file

@ -11,10 +11,11 @@ import sys
def main():
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'single_app_project.core.settings')
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "single_app_project.core.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
if __name__ == '__main__':
if __name__ == "__main__":
main()

View file

@ -12,7 +12,7 @@ import sys
def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'p1.settings')
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "p1.settings")
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
@ -24,5 +24,5 @@ def main():
execute_from_command_line(sys.argv)
if __name__ == '__main__':
if __name__ == "__main__":
main()

View file

@ -27,7 +27,7 @@ BASE_DIR = Path(__file__).resolve().parent.parent
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '%g@gyhl*q@@g(_ab@t^76dao^#b9-v8mw^50)x_bv6wpl+mukj'
SECRET_KEY = "%g@gyhl*q@@g(_ab@t^76dao^#b9-v8mw^50)x_bv6wpl+mukj"
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
@ -38,52 +38,52 @@ ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
"django.middleware.security.SecurityMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"django.middleware.common.CommonMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
"django.middleware.clickjacking.XFrameOptionsMiddleware",
]
ROOT_URLCONF = 'p1.urls'
ROOT_URLCONF = "p1.urls"
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": [],
"APP_DIRS": True,
"OPTIONS": {
"context_processors": [
"django.template.context_processors.debug",
"django.template.context_processors.request",
"django.contrib.auth.context_processors.auth",
"django.contrib.messages.context_processors.messages",
],
},
},
]
WSGI_APPLICATION = 'p1.wsgi.application'
WSGI_APPLICATION = "p1.wsgi.application"
# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": BASE_DIR / "db.sqlite3",
}
}
@ -93,16 +93,16 @@ DATABASES = {
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
"NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator",
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
"NAME": "django.contrib.auth.password_validation.MinimumLengthValidator",
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
"NAME": "django.contrib.auth.password_validation.CommonPasswordValidator",
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator",
},
]
@ -110,9 +110,9 @@ AUTH_PASSWORD_VALIDATORS = [
# Internationalization
# https://docs.djangoproject.com/en/3.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
LANGUAGE_CODE = "en-us"
TIME_ZONE = 'UTC'
TIME_ZONE = "UTC"
USE_I18N = True
@ -124,8 +124,8 @@ USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = '/tmp/django-static'
STATIC_URL = "/static/"
STATIC_ROOT = "/tmp/django-static"
if "DJANGO_ANSIBLE_RAISE" in os.environ:
raise ValueError("DJANGO_ANSIBLE_RAISE={0}".format(os.environ["DJANGO_ANSIBLE_RAISE"]))

View file

@ -23,5 +23,5 @@ from django.contrib import admin
from django.urls import path
urlpatterns = [
path('admin/', admin.site.urls),
path("admin/", admin.site.urls),
]

View file

@ -3,4 +3,4 @@
# SPDX-License-Identifier: GPL-3.0-or-later
# single_app_project/core/settings.py
SECRET_KEY = 'testtesttesttesttest'
SECRET_KEY = "testtesttesttesttest"

View file

@ -11,10 +11,11 @@ import sys
def main():
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'single_app_project.core.settings')
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "single_app_project.core.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
if __name__ == '__main__':
if __name__ == "__main__":
main()

View file

@ -12,7 +12,7 @@ import sys
def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'p1.settings')
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "p1.settings")
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
@ -24,5 +24,5 @@ def main():
execute_from_command_line(sys.argv)
if __name__ == '__main__':
if __name__ == "__main__":
main()

View file

@ -27,7 +27,7 @@ BASE_DIR = Path(__file__).resolve().parent.parent
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '%g@gyhl*q@@g(_ab@t^76dao^#b9-v8mw^50)x_bv6wpl+mukj'
SECRET_KEY = "%g@gyhl*q@@g(_ab@t^76dao^#b9-v8mw^50)x_bv6wpl+mukj"
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
@ -38,52 +38,52 @@ ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
"django.middleware.security.SecurityMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"django.middleware.common.CommonMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
"django.middleware.clickjacking.XFrameOptionsMiddleware",
]
ROOT_URLCONF = 'p1.urls'
ROOT_URLCONF = "p1.urls"
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": [],
"APP_DIRS": True,
"OPTIONS": {
"context_processors": [
"django.template.context_processors.debug",
"django.template.context_processors.request",
"django.contrib.auth.context_processors.auth",
"django.contrib.messages.context_processors.messages",
],
},
},
]
WSGI_APPLICATION = 'p1.wsgi.application'
WSGI_APPLICATION = "p1.wsgi.application"
# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": BASE_DIR / "db.sqlite3",
}
}
@ -93,16 +93,16 @@ DATABASES = {
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
"NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator",
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
"NAME": "django.contrib.auth.password_validation.MinimumLengthValidator",
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
"NAME": "django.contrib.auth.password_validation.CommonPasswordValidator",
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator",
},
]
@ -110,9 +110,9 @@ AUTH_PASSWORD_VALIDATORS = [
# Internationalization
# https://docs.djangoproject.com/en/3.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
LANGUAGE_CODE = "en-us"
TIME_ZONE = 'UTC'
TIME_ZONE = "UTC"
USE_I18N = True
@ -124,8 +124,8 @@ USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = '/tmp/django-static'
STATIC_URL = "/static/"
STATIC_ROOT = "/tmp/django-static"
if "DJANGO_ANSIBLE_RAISE" in os.environ:
raise ValueError("DJANGO_ANSIBLE_RAISE={0}".format(os.environ["DJANGO_ANSIBLE_RAISE"]))

View file

@ -23,5 +23,5 @@ from django.contrib import admin
from django.urls import path
urlpatterns = [
path('admin/', admin.site.urls),
path("admin/", admin.site.urls),
]

View file

@ -20,7 +20,7 @@ except ImportError:
# Argument parsing
if len(sys.argv) != 4:
print('Syntax: {0} <bind> <port> <path>'.format(sys.argv[0]))
print("Syntax: {0} <bind> <port> <path>".format(sys.argv[0]))
sys.exit(-1)
HOST, PORT, PATH = sys.argv[1:4]
@ -34,16 +34,16 @@ class Handler(SimpleHTTPRequestHandler):
# to support using another base directory than CWD.
# abandon query parameters
path = path.split('?', 1)[0]
path = path.split('#', 1)[0]
path = path.split("?", 1)[0]
path = path.split("#", 1)[0]
# Don't forget explicit trailing slash when normalizing. Issue17324
trailing_slash = path.rstrip().endswith('/')
trailing_slash = path.rstrip().endswith("/")
try:
path = unquote(path, errors='surrogatepass')
path = unquote(path, errors="surrogatepass")
except (UnicodeDecodeError, TypeError) as exc:
path = unquote(path)
path = posixpath.normpath(path)
words = path.split('/')
words = path.split("/")
words = filter(None, words)
path = PATH
for word in words:
@ -52,7 +52,7 @@ class Handler(SimpleHTTPRequestHandler):
continue
path = os.path.join(path, word)
if trailing_slash:
path += '/'
path += "/"
return path

View file

@ -16,15 +16,17 @@ try:
except ModuleNotFoundError:
from http.server import HTTPServer, SimpleHTTPRequestHandler
httpd = HTTPServer(('localhost', port), SimpleHTTPRequestHandler)
httpd = HTTPServer(("localhost", port), SimpleHTTPRequestHandler)
try:
httpd.socket = ssl.wrap_socket(httpd.socket, server_side=True,
certfile=os.path.join(root_dir, 'cert.pem'),
keyfile=os.path.join(root_dir, 'key.pem'))
httpd.socket = ssl.wrap_socket(
httpd.socket,
server_side=True,
certfile=os.path.join(root_dir, "cert.pem"),
keyfile=os.path.join(root_dir, "key.pem"),
)
except AttributeError:
# Python 3.12 or newer:
context = ssl.create_default_context(purpose=ssl.Purpose.CLIENT_AUTH)
context.load_cert_chain(certfile=os.path.join(root_dir, 'cert.pem'),
keyfile=os.path.join(root_dir, 'key.pem'))
context.load_cert_chain(certfile=os.path.join(root_dir, "cert.pem"), keyfile=os.path.join(root_dir, "key.pem"))
httpd.socket = context.wrap_socket(httpd.socket)
httpd.handle_request()

View file

@ -10,7 +10,7 @@ import http.server
import socketserver
if __name__ == '__main__':
if __name__ == "__main__":
PORT = int(sys.argv[1])
Handler = http.server.SimpleHTTPRequestHandler
httpd = socketserver.TCPServer(("", PORT), Handler)

View file

@ -6,7 +6,7 @@
from __future__ import annotations
DOCUMENTATION = '''
DOCUMENTATION = """
---
module: collection_module
short_description: Test collection module
@ -14,11 +14,11 @@ description:
- This is a test module in a local collection.
author: "Felix Fontein (@felixfontein)"
options: {}
'''
"""
EXAMPLES = ''' # '''
EXAMPLES = """ # """
RETURN = ''' # '''
RETURN = """ # """
from ansible.module_utils.basic import AnsibleModule
@ -27,5 +27,5 @@ def main():
AnsibleModule(argument_spec={}).exit_json()
if __name__ == '__main__':
if __name__ == "__main__":
main()

View file

@ -6,7 +6,7 @@
from __future__ import annotations
DOCUMENTATION = '''
DOCUMENTATION = """
---
module: collection_module
short_description: Test collection module
@ -14,11 +14,11 @@ description:
- This is a test module in a local collection.
author: "Felix Fontein (@felixfontein)"
options: {}
'''
"""
EXAMPLES = ''' # '''
EXAMPLES = """ # """
RETURN = ''' # '''
RETURN = """ # """
from ansible.module_utils.basic import AnsibleModule
@ -27,5 +27,5 @@ def main():
AnsibleModule(argument_spec={}).exit_json()
if __name__ == '__main__':
if __name__ == "__main__":
main()

View file

@ -6,7 +6,7 @@
from __future__ import annotations
DOCUMENTATION = '''
DOCUMENTATION = """
---
module: collection_module
short_description: Test collection module
@ -14,11 +14,11 @@ description:
- This is a test module in a local collection.
author: "Felix Fontein (@felixfontein)"
options: {}
'''
"""
EXAMPLES = ''' # '''
EXAMPLES = """ # """
RETURN = ''' # '''
RETURN = """ # """
from ansible.module_utils.basic import AnsibleModule
@ -27,5 +27,5 @@ def main():
AnsibleModule(argument_spec={}).exit_json()
if __name__ == '__main__':
if __name__ == "__main__":
main()

View file

@ -6,7 +6,7 @@
from __future__ import annotations
DOCUMENTATION = '''
DOCUMENTATION = """
---
module: collection_module
short_description: Test collection module
@ -14,11 +14,11 @@ description:
- This is a test module in a local collection.
author: "Felix Fontein (@felixfontein)"
options: {}
'''
"""
EXAMPLES = ''' # '''
EXAMPLES = """ # """
RETURN = ''' # '''
RETURN = """ # """
from ansible.module_utils.basic import AnsibleModule
@ -27,5 +27,5 @@ def main():
AnsibleModule(argument_spec={}).exit_json()
if __name__ == '__main__':
if __name__ == "__main__":
main()

View file

@ -6,7 +6,7 @@
from __future__ import annotations
DOCUMENTATION = '''
DOCUMENTATION = """
---
module: local_module
short_description: Test local module
@ -14,11 +14,11 @@ description:
- This is a test module locally next to a playbook.
author: "Felix Fontein (@felixfontein)"
options: {}
'''
"""
EXAMPLES = ''' # '''
EXAMPLES = """ # """
RETURN = ''' # '''
RETURN = """ # """
from ansible.module_utils.basic import AnsibleModule
@ -27,5 +27,5 @@ def main():
AnsibleModule(argument_spec={}).exit_json()
if __name__ == '__main__':
if __name__ == "__main__":
main()

View file

@ -4,11 +4,12 @@
from __future__ import annotations
import lmdb
map_size = 1024 * 100
env = lmdb.open('./jp.mdb', map_size=map_size)
env = lmdb.open("./jp.mdb", map_size=map_size)
with env.begin(write=True) as txn:
txn.put('fr'.encode(), 'France'.encode())
txn.put('nl'.encode(), 'Netherlands'.encode())
txn.put('es'.encode(), 'Spain'.encode())
txn.put('be'.encode(), 'Belgium'.encode())
txn.put('lu'.encode(), 'Luxembourg'.encode())
txn.put("fr".encode(), "France".encode())
txn.put("nl".encode(), "Netherlands".encode())
txn.put("es".encode(), "Spain".encode())
txn.put("be".encode(), "Belgium".encode())
txn.put("lu".encode(), "Luxembourg".encode())

View file

@ -14,17 +14,19 @@ import sys
# Handle TLS and non-TLS support
try:
import smtpd_tls
HAS_TLS = True
except ImportError:
import smtpd
HAS_TLS = False
print('Library smtpd-tls is missing or not supported, hence starttls is NOT supported.')
print("Library smtpd-tls is missing or not supported, hence starttls is NOT supported.")
# Handle custom ports
port = '25:465'
port = "25:465"
if len(sys.argv) > 1:
port = sys.argv[1]
ports = port.split(':')
ports = port.split(":")
if len(ports) > 1:
port1, port2 = int(ports[0]), int(ports[1])
else:
@ -32,30 +34,30 @@ else:
# Handle custom certificate
basename = os.path.splitext(sys.argv[0])[0]
certfile = basename + '.crt'
certfile = basename + ".crt"
if len(sys.argv) > 2:
certfile = sys.argv[2]
# Handle custom key
keyfile = basename + '.key'
keyfile = basename + ".key"
if len(sys.argv) > 3:
keyfile = sys.argv[3]
ssl_ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
if HAS_TLS and ssl_ctx is not None:
print('Using %s and %s' % (certfile, keyfile))
print("Using %s and %s" % (certfile, keyfile))
ssl_ctx.load_cert_chain(certfile=certfile, keyfile=keyfile)
print('Start SMTP server on port', port1)
smtp_server1 = smtpd_tls.DebuggingServer(('127.0.0.1', port1), None, ssl_ctx=ssl_ctx, starttls=True)
print("Start SMTP server on port", port1)
smtp_server1 = smtpd_tls.DebuggingServer(("127.0.0.1", port1), None, ssl_ctx=ssl_ctx, starttls=True)
if port2:
print('Start TLS SMTP server on port', port2)
smtp_server2 = smtpd_tls.DebuggingServer(('127.0.0.1', port2), None, ssl_ctx=ssl_ctx, starttls=False)
print("Start TLS SMTP server on port", port2)
smtp_server2 = smtpd_tls.DebuggingServer(("127.0.0.1", port2), None, ssl_ctx=ssl_ctx, starttls=False)
else:
print('Start SMTP server on port', port1)
smtp_server1 = smtpd.DebuggingServer(('127.0.0.1', port1), None) # pylint: disable=used-before-assignment
print("Start SMTP server on port", port1)
smtp_server1 = smtpd.DebuggingServer(("127.0.0.1", port1), None) # pylint: disable=used-before-assignment
if port2:
print('WARNING: TLS is NOT supported on this system, not listening on port %s.' % port2)
print("WARNING: TLS is NOT supported on this system, not listening on port %s." % port2)
asyncore.loop()

View file

@ -6,7 +6,7 @@
from __future__ import annotations
DOCUMENTATION = '''
DOCUMENTATION = """
module: mdepfail
author: "Alexei Znamensky (@russoz)"
short_description: Simple module for testing
@ -22,7 +22,7 @@ options:
c:
description: cccc
type: str
'''
"""
EXAMPLES = ""
@ -36,28 +36,28 @@ with deps.declare("nopackagewiththisname"):
class MSimple(ModuleHelper):
output_params = ('a', 'b', 'c')
output_params = ("a", "b", "c")
module = dict(
argument_spec=dict(
a=dict(type='int'),
b=dict(type='str'),
c=dict(type='str'),
a=dict(type="int"),
b=dict(type="str"),
c=dict(type="str"),
),
)
def __init_module__(self):
self.vars.set('value', None)
self.vars.set('abc', "abc", diff=True)
self.vars.set("value", None)
self.vars.set("abc", "abc", diff=True)
deps.validate(self.module)
def __run__(self):
if (0 if self.vars.a is None else self.vars.a) >= 100:
raise Exception("a >= 100")
if self.vars.c == "abc change":
self.vars['abc'] = "changed abc"
self.vars["abc"] = "changed abc"
if self.vars.a == 2:
self.vars['b'] = str(self.vars.b) * 2
self.vars['c'] = str(self.vars.c) * 2
self.vars["b"] = str(self.vars.b) * 2
self.vars["c"] = str(self.vars.c) * 2
def main():
@ -65,5 +65,5 @@ def main():
msimple.run()
if __name__ == '__main__':
if __name__ == "__main__":
main()

View file

@ -6,7 +6,7 @@
from __future__ import annotations
DOCUMENTATION = '''
DOCUMENTATION = """
module: msimple
author: "Alexei Znamensky (@russoz)"
short_description: Simple module for testing
@ -22,7 +22,7 @@ options:
c:
description: cccc
type: str
'''
"""
EXAMPLES = ""
@ -33,26 +33,26 @@ from ansible_collections.community.general.plugins.module_utils.mh.deco import c
class MSimple(ModuleHelper):
output_params = ('a', 'b', 'c', 'm')
output_params = ("a", "b", "c", "m")
module = dict(
argument_spec=dict(
a=dict(type='int', default=0),
b=dict(type='str'),
c=dict(type='str'),
m=dict(type='str'),
a=dict(type="int", default=0),
b=dict(type="str"),
c=dict(type="str"),
m=dict(type="str"),
),
supports_check_mode=True,
)
def __init_module__(self):
self.vars.set('value', None)
self.vars.set('abc', "abc", diff=True)
self.vars.set("value", None)
self.vars.set("abc", "abc", diff=True)
@check_mode_skip
def process_a3_bc(self):
if self.vars.a == 3:
self.vars['b'] = str(self.vars.b) * 3
self.vars['c'] = str(self.vars.c) * 3
self.vars["b"] = str(self.vars.b) * 3
self.vars["c"] = str(self.vars.c) * 3
def __run__(self):
if self.vars.m:
@ -60,10 +60,10 @@ class MSimple(ModuleHelper):
if self.vars.a >= 100:
raise Exception("a >= 100")
if self.vars.c == "abc change":
self.vars['abc'] = "changed abc"
self.vars["abc"] = "changed abc"
if self.vars.a == 2:
self.vars['b'] = str(self.vars.b) * 2
self.vars['c'] = str(self.vars.c) * 2
self.vars["b"] = str(self.vars.b) * 2
self.vars["c"] = str(self.vars.c) * 2
self.process_a3_bc()
@ -72,5 +72,5 @@ def main():
msimple.run()
if __name__ == '__main__':
if __name__ == "__main__":
main()

View file

@ -6,7 +6,7 @@
from __future__ import annotations
DOCUMENTATION = '''
DOCUMENTATION = """
module: msimpleda
author: "Alexei Znamensky (@russoz)"
short_description: Simple module for testing DeprecationAttrsMixin
@ -16,7 +16,7 @@ options:
a:
description: aaaa
type: int
'''
"""
EXAMPLES = ""
@ -24,15 +24,15 @@ RETURN = ""
from ansible_collections.community.general.plugins.module_utils.module_helper import ModuleHelper
from ansible_collections.community.general.plugins.module_utils.mh.mixins.deprecate_attrs import ( # noqa: F401, pylint: disable=unused-import
DeprecateAttrsMixin
DeprecateAttrsMixin,
)
class MSimpleDA(ModuleHelper):
output_params = ('a',)
output_params = ("a",)
module = dict(
argument_spec=dict(
a=dict(type='int'),
a=dict(type="int"),
),
)
@ -60,5 +60,5 @@ def main():
MSimpleDA.execute()
if __name__ == '__main__':
if __name__ == "__main__":
main()

View file

@ -6,7 +6,7 @@
from __future__ import annotations
DOCUMENTATION = '''
DOCUMENTATION = """
module: mstate
author: "Alexei Znamensky (@russoz)"
short_description: State-based module for testing
@ -28,7 +28,7 @@ options:
type: str
choices: [join, b_x_a, c_x_a, both_x_a]
default: join
'''
"""
EXAMPLES = ""
@ -38,30 +38,30 @@ from ansible_collections.community.general.plugins.module_utils.module_helper im
class MState(StateModuleHelper):
output_params = ('a', 'b', 'c', 'state')
output_params = ("a", "b", "c", "state")
module = dict(
argument_spec=dict(
a=dict(type='int', required=True),
b=dict(type='str'),
c=dict(type='str'),
state=dict(type='str', choices=['join', 'b_x_a', 'c_x_a', 'both_x_a', 'nop'], default='join'),
a=dict(type="int", required=True),
b=dict(type="str"),
c=dict(type="str"),
state=dict(type="str", choices=["join", "b_x_a", "c_x_a", "both_x_a", "nop"], default="join"),
),
)
def __init_module__(self):
self.vars.set('result', "abc", diff=True)
self.vars.set("result", "abc", diff=True)
def state_join(self):
self.vars['result'] = "".join([str(self.vars.a), str(self.vars.b), str(self.vars.c)])
self.vars["result"] = "".join([str(self.vars.a), str(self.vars.b), str(self.vars.c)])
def state_b_x_a(self):
self.vars['result'] = str(self.vars.b) * self.vars.a
self.vars["result"] = str(self.vars.b) * self.vars.a
def state_c_x_a(self):
self.vars['result'] = str(self.vars.c) * self.vars.a
self.vars["result"] = str(self.vars.c) * self.vars.a
def state_both_x_a(self):
self.vars['result'] = (str(self.vars.b) + str(self.vars.c)) * self.vars.a
self.vars["result"] = (str(self.vars.b) + str(self.vars.c)) * self.vars.a
def state_nop(self):
pass
@ -72,5 +72,5 @@ def main():
mstate.run()
if __name__ == '__main__':
if __name__ == "__main__":
main()

View file

@ -17,9 +17,9 @@ username = sys.argv[3]
password = sys.argv[4]
if username:
url = 'http://%s:%s@127.0.0.1:9001/RPC2' % (quote(username, safe=''), quote(password, safe=''))
url = "http://%s:%s@127.0.0.1:9001/RPC2" % (quote(username, safe=""), quote(password, safe=""))
else:
url = 'http://127.0.0.1:9001/RPC2'
url = "http://127.0.0.1:9001/RPC2"
server = ServerProxy(url, verbose=True)
server.supervisor.sendProcessStdin(proc, 'import sys; print(%s); sys.stdout.flush();\n' % value)
server.supervisor.sendProcessStdin(proc, "import sys; print(%s); sys.stdout.flush();\n" % value)

View file

@ -6,7 +6,7 @@
from __future__ import annotations
DOCUMENTATION = '''
DOCUMENTATION = """
---
module: collection_module
short_description: Test collection module
@ -14,11 +14,11 @@ description:
- This is a test module in a local collection.
author: "Felix Fontein (@felixfontein)"
options: {}
'''
"""
EXAMPLES = ''' # '''
EXAMPLES = """ # """
RETURN = ''' # '''
RETURN = """ # """
from ansible.module_utils.basic import AnsibleModule
@ -27,5 +27,5 @@ def main():
AnsibleModule(argument_spec={}).exit_json()
if __name__ == '__main__':
if __name__ == "__main__":
main()

View file

@ -6,7 +6,7 @@
from __future__ import annotations
DOCUMENTATION = '''
DOCUMENTATION = """
---
module: local_module
short_description: Test local module
@ -14,11 +14,11 @@ description:
- This is a test module locally next to a playbook.
author: "Felix Fontein (@felixfontein)"
options: {}
'''
"""
EXAMPLES = ''' # '''
EXAMPLES = """ # """
RETURN = ''' # '''
RETURN = """ # """
from ansible.module_utils.basic import AnsibleModule
@ -27,5 +27,5 @@ def main():
AnsibleModule(argument_spec={}).exit_json()
if __name__ == '__main__':
if __name__ == "__main__":
main()