diff options
author | Andrei Zeliankou <zelenkov@nginx.com> | 2024-01-15 15:48:58 +0000 |
---|---|---|
committer | Andrei Zeliankou <zelenkov@nginx.com> | 2024-01-15 15:48:58 +0000 |
commit | 5a8337933df1cf3aba967d86549e236dd9173386 (patch) | |
tree | 30842acf799fc521702b1c4b070332c72feaaa1c | |
parent | e95a91cbfac018b9877d9e389e614e9f2a9f1313 (diff) | |
download | unit-5a8337933df1cf3aba967d86549e236dd9173386.tar.gz unit-5a8337933df1cf3aba967d86549e236dd9173386.tar.bz2 |
Tests: pathlib used where appropriate
Also fixed various pylint errors and style issues.
72 files changed, 306 insertions, 256 deletions
diff --git a/test/conftest.py b/test/conftest.py index 8d2850fd..2fe4d8dc 100644 --- a/test/conftest.py +++ b/test/conftest.py @@ -11,10 +11,12 @@ import sys import tempfile import time from multiprocessing import Process +from pathlib import Path import pytest -from unit.check.discover_available import discover_available + from unit.check.check_prerequisites import check_prerequisites +from unit.check.discover_available import discover_available from unit.http import HTTP1 from unit.log import Log from unit.log import print_log_on_assert @@ -265,27 +267,26 @@ def unit_run(state_dir=None): if not option.restart and 'unitd' in unit_instance: return unit_instance - builddir = f'{option.current_dir}/build' - libdir = f'{builddir}/lib' + builddir = f'{option.current_dir}/build' + libdir = f'{builddir}/lib' modulesdir = f'{libdir}/unit/modules' - sbindir = f'{builddir}/sbin' - unitd = f'{sbindir}/unitd' + sbindir = f'{builddir}/sbin' + unitd = f'{sbindir}/unitd' - if not os.path.isfile(unitd): - exit('Could not find unit') + if not Path(unitd).is_file(): + sys.exit('Could not find unit') - temp_dir = tempfile.mkdtemp(prefix='unit-test-') - option.temp_dir = temp_dir - public_dir(temp_dir) + temporary_dir = tempfile.mkdtemp(prefix='unit-test-') + option.temp_dir = temporary_dir + public_dir(temporary_dir) - if oct(stat.S_IMODE(os.stat(builddir).st_mode)) != '0o777': + if oct(stat.S_IMODE(Path(builddir).stat().st_mode)) != '0o777': public_dir(builddir) - statedir = f'{temp_dir}/state' if state_dir is None else state_dir - if not os.path.isdir(statedir): - os.mkdir(statedir) + statedir = f'{temporary_dir}/state' if state_dir is None else state_dir + Path(statedir).mkdir(exist_ok=True) - control_sock = f'{temp_dir}/control.unit.sock' + control_sock = f'{temporary_dir}/control.unit.sock' unitd_args = [ unitd, @@ -295,31 +296,32 @@ def unit_run(state_dir=None): '--statedir', statedir, '--pid', - f'{temp_dir}/unit.pid', + f'{temporary_dir}/unit.pid', '--log', - f'{temp_dir}/unit.log', + f'{temporary_dir}/unit.log', '--control', - f'unix:{temp_dir}/control.unit.sock', + f'unix:{temporary_dir}/control.unit.sock', '--tmpdir', - temp_dir, + temporary_dir, ] if option.user: unitd_args.extend(['--user', option.user]) - with open(f'{temp_dir}/unit.log', 'w') as log: + with open(f'{temporary_dir}/unit.log', 'w', encoding='utf-8') as log: unit_instance['process'] = subprocess.Popen(unitd_args, stderr=log) if not waitforfiles(control_sock): Log.print_log() - exit('Could not start unit') + sys.exit('Could not start unit') - unit_instance['temp_dir'] = temp_dir + unit_instance['temp_dir'] = temporary_dir unit_instance['control_sock'] = control_sock unit_instance['unitd'] = unitd - with open(f'{temp_dir}/unit.pid', 'r') as f: - unit_instance['pid'] = f.read().rstrip() + unit_instance['pid'] = ( + Path(f'{temporary_dir}/unit.pid').read_text(encoding='utf-8').rstrip() + ) if state_dir is None: _clear_conf() @@ -424,26 +426,27 @@ def _clear_conf(*, log=None): def _clear_temp_dir(): - temp_dir = unit_instance['temp_dir'] + temporary_dir = unit_instance['temp_dir'] - if is_findmnt and not waitforunmount(temp_dir, timeout=600): - exit('Could not unmount some filesystems in tmpdir ({temp_dir}).') + if is_findmnt and not waitforunmount(temporary_dir, timeout=600): + sys.exit('Could not unmount filesystems in tmpdir ({temporary_dir}).') - for item in os.listdir(temp_dir): - if item not in [ + for item in Path(temporary_dir).iterdir(): + if item.name not in [ 'control.unit.sock', 'state', 'unit.pid', 'unit.log', ]: - path = os.path.join(temp_dir, item) - public_dir(path) - if os.path.isfile(path) or stat.S_ISSOCK(os.stat(path).st_mode): - os.remove(path) + + public_dir(item) + + if item.is_file() or stat.S_ISSOCK(item.stat().st_mode): + item.unlink() else: for _ in range(10): try: - shutil.rmtree(path) + shutil.rmtree(item) break except OSError as err: # OSError: [Errno 16] Device or resource busy @@ -456,7 +459,7 @@ def _clear_temp_dir(): def _check_processes(): router_pid = _fds_info['router']['pid'] controller_pid = _fds_info['controller']['pid'] - unit_pid = unit_instance['pid'] + main_pid = unit_instance['pid'] for _ in range(600): out = ( @@ -466,7 +469,7 @@ def _check_processes(): .decode() .splitlines() ) - out = [l for l in out if unit_pid in l] + out = [l for l in out if main_pid in l] if len(out) <= 3: break @@ -485,14 +488,14 @@ def _check_processes(): out = [ l for l in out - if re.search(fr'{router_pid}\s+{unit_pid}.*unit: router', l) is None + if re.search(fr'{router_pid}\s+{main_pid}.*unit: router', l) is None ] assert len(out) == 1, 'one router' out = [ l for l in out - if re.search(fr'{controller_pid}\s+{unit_pid}.*unit: controller', l) + if re.search(fr'{controller_pid}\s+{main_pid}.*unit: controller', l) is None ] assert len(out) == 0, 'one controller' @@ -542,9 +545,9 @@ def _check_fds(*, log=None): def _count_fds(pid): - procfile = f'/proc/{pid}/fd' - if os.path.isdir(procfile): - return len(os.listdir(procfile)) + procfile = Path(f'/proc/{pid}/fd') + if procfile.is_dir(): + return len(list(procfile.iterdir())) try: out = subprocess.check_output( @@ -616,7 +619,7 @@ def pytest_sessionfinish(): public_dir(option.cache_dir) shutil.rmtree(option.cache_dir) - if not option.save_log and os.path.isdir(option.temp_dir): + if not option.save_log and Path(option.temp_dir).is_dir(): public_dir(option.temp_dir) shutil.rmtree(option.temp_dir) diff --git a/test/python/body_generate/wsgi.py b/test/python/body_generate/wsgi.py index 73462be6..3d12ac60 100644 --- a/test/python/body_generate/wsgi.py +++ b/test/python/body_generate/wsgi.py @@ -1,6 +1,6 @@ def application(env, start_response): length = env.get('HTTP_X_LENGTH', '10') - bytes = b'X' * int(length) + body = b'X' * int(length) start_response('200', [('Content-Length', length)]) - return [bytes] + return [body] diff --git a/test/python/delayed/asgi.py b/test/python/delayed/asgi.py index 1cb15a92..3c25e49a 100644 --- a/test/python/delayed/asgi.py +++ b/test/python/delayed/asgi.py @@ -33,7 +33,9 @@ async def application(scope, receive, send): { 'type': 'http.response.start', 'status': 200, - 'headers': [(b'content-length', str(len(body)).encode()),], + 'headers': [ + (b'content-length', str(len(body)).encode()), + ], } ) diff --git a/test/python/environment/wsgi.py b/test/python/environment/wsgi.py index 91e0ba49..622b8bc0 100644 --- a/test/python/environment/wsgi.py +++ b/test/python/environment/wsgi.py @@ -2,9 +2,11 @@ import os def application(env, start_response): - vars = env.get('HTTP_X_VARIABLES').split(',') + variables = env.get('HTTP_X_VARIABLES').split(',') - body = ','.join([str(os.environ[var]) for var in vars if var in os.environ]) + body = ','.join( + [str(os.environ[var]) for var in variables if var in os.environ] + ) body = body.encode() start_response('200', [('Content-Length', str(len(body)))]) diff --git a/test/python/iter_exception/wsgi.py b/test/python/iter_exception/wsgi.py index 2779a845..66a09af7 100644 --- a/test/python/iter_exception/wsgi.py +++ b/test/python/iter_exception/wsgi.py @@ -8,9 +8,7 @@ class application: def __iter__(self): self.__i = 0 self._skip_level = int(self.environ.get('HTTP_X_SKIP', 0)) - self._not_skip_close = int( - self.environ.get('HTTP_X_NOT_SKIP_CLOSE', 0) - ) + self._not_skip_close = int(self.environ.get('HTTP_X_NOT_SKIP_CLOSE', 0)) self._is_chunked = self.environ.get('HTTP_X_CHUNKED') headers = [(('Content-Length', '10'))] diff --git a/test/python/legacy/asgi.py b/test/python/legacy/asgi.py index 1d45cc4f..8be8932e 100644 --- a/test/python/legacy/asgi.py +++ b/test/python/legacy/asgi.py @@ -9,6 +9,8 @@ async def app_http(receive, send): { 'type': 'http.response.start', 'status': 200, - 'headers': [(b'content-length', b'0'),], + 'headers': [ + (b'content-length', b'0'), + ], } ) diff --git a/test/python/legacy_force/asgi.py b/test/python/legacy_force/asgi.py index ad2785f2..56c7061d 100644 --- a/test/python/legacy_force/asgi.py +++ b/test/python/legacy_force/asgi.py @@ -1,11 +1,10 @@ def application(scope, receive=None, send=None): assert scope['type'] == 'http' - if receive == None and send == None: + if receive is None and send is None: return app_http - else: - return app_http(receive, send) + return app_http(receive, send) async def app_http(receive, send): @@ -13,6 +12,8 @@ async def app_http(receive, send): { 'type': 'http.response.start', 'status': 200, - 'headers': [(b'content-length', b'0'),], + 'headers': [ + (b'content-length', b'0'), + ], } ) diff --git a/test/python/lifespan/empty/asgi.py b/test/python/lifespan/empty/asgi.py index 27395a28..2071e6e0 100644 --- a/test/python/lifespan/empty/asgi.py +++ b/test/python/lifespan/empty/asgi.py @@ -3,7 +3,7 @@ import os async def handler(prefix, scope, receive, send): if scope['type'] == 'lifespan': - with open(f'{prefix}version', 'w+') as f: + with open(f'{prefix}version', 'w+', encoding='utf-8') as f: f.write( f"{scope['asgi']['version']} {scope['asgi']['spec_version']}" ) diff --git a/test/python/lifespan/failed/asgi.py b/test/python/lifespan/failed/asgi.py index 8f315f70..fbd006f9 100644 --- a/test/python/lifespan/failed/asgi.py +++ b/test/python/lifespan/failed/asgi.py @@ -6,6 +6,6 @@ async def application(scope, receive, send): await send({"type": "lifespan.startup.failed"}) raise Exception('Exception blah') - elif message['type'] == 'lifespan.shutdown': + if message['type'] == 'lifespan.shutdown': await send({'type': 'lifespan.shutdown.complete'}) return diff --git a/test/python/restart/longstart.py b/test/python/restart/longstart.py index 777398ac..3bc383b7 100644 --- a/test/python/restart/longstart.py +++ b/test/python/restart/longstart.py @@ -3,6 +3,7 @@ import time time.sleep(2) + def application(environ, start_response): body = str(os.getpid()).encode() diff --git a/test/python/unicode/wsgi.py b/test/python/unicode/wsgi.py index f2f85f5d..8c9a59dd 100644 --- a/test/python/unicode/wsgi.py +++ b/test/python/unicode/wsgi.py @@ -1,7 +1,7 @@ def application(environ, start_response): temp_dir = environ.get('HTTP_TEMP_DIR') - with open(f'{temp_dir}/tempfile', 'w') as f: + with open(f'{temp_dir}/tempfile', 'w', encoding='utf-8') as f: f.write('\u26a0\ufe0f') start_response('200', [('Content-Length', '0')]) diff --git a/test/python/user_group/wsgi.py b/test/python/user_group/wsgi.py index 4003c064..8f3ba50d 100644 --- a/test/python/user_group/wsgi.py +++ b/test/python/user_group/wsgi.py @@ -6,7 +6,12 @@ def application(environ, start_response): uid = os.geteuid() gid = os.getegid() - out = json.dumps({'UID': uid, 'GID': gid,}).encode('utf-8') + out = json.dumps( + { + 'UID': uid, + 'GID': gid, + } + ).encode('utf-8') start_response( '200 OK', diff --git a/test/test_access_log.py b/test/test_access_log.py index 3c5e6cbb..873c941a 100644 --- a/test/test_access_log.py +++ b/test/test_access_log.py @@ -1,6 +1,7 @@ import time import pytest + from unit.applications.lang.python import ApplicationPython from unit.option import option @@ -17,11 +18,11 @@ def load(script): ), 'access_log configure' -def set_format(format): +def set_format(log_format): assert 'success' in client.conf( { 'path': f'{option.temp_dir}/access.log', - 'format': format, + 'format': log_format, }, 'access_log', ), 'access_log format' @@ -283,14 +284,14 @@ def test_access_log_change(temp_dir, wait_for_record): def test_access_log_format(wait_for_record): load('empty') - def check_format(format, expect, url='/'): - set_format(format) + def check_format(log_format, expect, url='/'): + set_format(log_format) assert client.get(url=url)['status'] == 200 assert wait_for_record(expect, 'access.log') is not None, 'found' - format = 'BLAH\t0123456789' - check_format(format, format) + log_format = 'BLAH\t0123456789' + check_format(log_format, log_format) check_format('$uri $status $uri $status', '/ 200 / 200') diff --git a/test/test_asgi_application.py b/test/test_asgi_application.py index 4b59fafd..e6668b2f 100644 --- a/test/test_asgi_application.py +++ b/test/test_asgi_application.py @@ -3,6 +3,7 @@ import time import pytest from packaging import version + from unit.applications.lang.python import ApplicationPython prerequisites = { diff --git a/test/test_asgi_application_unix_abstract.py b/test/test_asgi_application_unix_abstract.py index 980a98a9..f35ce0d7 100644 --- a/test/test_asgi_application_unix_abstract.py +++ b/test/test_asgi_application_unix_abstract.py @@ -1,4 +1,5 @@ from packaging import version + from unit.applications.lang.python import ApplicationPython prerequisites = { diff --git a/test/test_asgi_lifespan.py b/test/test_asgi_lifespan.py index 5df7475e..e09ea1cc 100644 --- a/test/test_asgi_lifespan.py +++ b/test/test_asgi_lifespan.py @@ -1,7 +1,8 @@ -import os +from pathlib import Path -from conftest import unit_stop from packaging import version + +from conftest import unit_stop from unit.applications.lang.python import ApplicationPython from unit.option import option @@ -14,32 +15,26 @@ client = ApplicationPython(load_module='asgi') def assert_cookies(prefix): for name in ['startup', 'shutdown']: - path = f'{option.test_dir}/python/lifespan/empty/{prefix}{name}' - exists = os.path.isfile(path) - if exists: - os.remove(path) + path = Path(f'{option.test_dir}/python/lifespan/empty/{prefix}{name}') + exists = path.is_file() + path.unlink(missing_ok=True) assert not exists, name - path = f'{option.test_dir}/python/lifespan/empty/{prefix}version' + path = Path(f'{option.test_dir}/python/lifespan/empty/{prefix}version') + versions = path.read_text(encoding='utf-8') + path.unlink() - with open(path, 'r') as f: - version = f.read() - - os.remove(path) - - assert version == '3.0 2.0', 'version' + assert versions == '3.0 2.0', 'versions' def setup_cookies(prefix): - base_dir = f'{option.test_dir}/python/lifespan/empty' - - os.chmod(base_dir, 0o777) + base_dir = Path(f'{option.test_dir}/python/lifespan/empty') + base_dir.chmod(0o777) for name in ['startup', 'shutdown', 'version']: - path = f'{option.test_dir}/python/lifespan/empty/{prefix}{name}' - open(path, 'a').close() - os.chmod(path, 0o777) + path = Path(f'{option.test_dir}/python/lifespan/empty/{prefix}{name}') + path.touch(0o777) def test_asgi_lifespan(): diff --git a/test/test_asgi_targets.py b/test/test_asgi_targets.py index 63bde713..3d4e2e24 100644 --- a/test/test_asgi_targets.py +++ b/test/test_asgi_targets.py @@ -1,5 +1,6 @@ import pytest from packaging import version + from unit.applications.lang.python import ApplicationPython from unit.option import option diff --git a/test/test_asgi_websockets.py b/test/test_asgi_websockets.py index eb7a20e7..f93c97ab 100644 --- a/test/test_asgi_websockets.py +++ b/test/test_asgi_websockets.py @@ -3,6 +3,7 @@ import time import pytest from packaging import version + from unit.applications.lang.python import ApplicationPython from unit.applications.websockets import ApplicationWebsocket diff --git a/test/test_client_ip.py b/test/test_client_ip.py index d7bc399d..538db18b 100644 --- a/test/test_client_ip.py +++ b/test/test_client_ip.py @@ -1,4 +1,5 @@ import pytest + from unit.applications.lang.python import ApplicationPython from unit.option import option diff --git a/test/test_configuration.py b/test/test_configuration.py index a311922f..a7d519e9 100644 --- a/test/test_configuration.py +++ b/test/test_configuration.py @@ -1,6 +1,7 @@ import socket import pytest + from unit.control import Control prerequisites = {'modules': {'python': 'any'}} diff --git a/test/test_forwarded_header.py b/test/test_forwarded_header.py index eaa83dce..4b2f9424 100644 --- a/test/test_forwarded_header.py +++ b/test/test_forwarded_header.py @@ -1,4 +1,5 @@ import pytest + from unit.applications.lang.python import ApplicationPython prerequisites = {'modules': {'python': 'any'}} diff --git a/test/test_go_application.py b/test/test_go_application.py index 8f406744..469d4346 100644 --- a/test/test_go_application.py +++ b/test/test_go_application.py @@ -123,7 +123,7 @@ def test_go_application_command_line_arguments_type(): client.load('command_line_arguments') assert 'error' in client.conf( - '' "a b c", 'applications/command_line_arguments/arguments' + "a b c", 'applications/command_line_arguments/arguments' ), 'arguments type' diff --git a/test/test_go_isolation.py b/test/test_go_isolation.py index ba3390ea..a864e9f6 100644 --- a/test/test_go_isolation.py +++ b/test/test_go_isolation.py @@ -3,6 +3,7 @@ import os import pwd import pytest + from unit.applications.lang.go import ApplicationGo from unit.option import option from unit.utils import getns @@ -319,7 +320,7 @@ def test_go_isolation_rootfs_container_priv(require, temp_dir): def test_go_isolation_rootfs_automount_tmpfs(is_su, require, temp_dir): try: - open("/proc/self/mountinfo") + open("/proc/self/mountinfo", encoding='utf-8') except: pytest.skip('The system lacks /proc/self/mountinfo file') diff --git a/test/test_http_header.py b/test/test_http_header.py index cf5866e9..f6579df5 100644 --- a/test/test_http_header.py +++ b/test/test_http_header.py @@ -1,4 +1,5 @@ import pytest + from unit.applications.lang.python import ApplicationPython prerequisites = {'modules': {'python': 'any'}} diff --git a/test/test_java_application.py b/test/test_java_application.py index 3a6a62d6..33151182 100644 --- a/test/test_java_application.py +++ b/test/test_java_application.py @@ -1,7 +1,7 @@ import io -import os import re import time +from pathlib import Path from unit.applications.lang.java import ApplicationJava from unit.option import option @@ -875,6 +875,7 @@ def test_java_application_get_headers(): assert headers['X-Reply-0'] == 'blah', 'get headers' assert headers['X-Reply-1'] == 'blah', 'get headers 2' + def test_java_application_many_headers(): client.load('get_headers') @@ -956,7 +957,7 @@ def test_java_application_multipart(search_in_file, temp_dir): reldst = '/uploads' fulldst = f'{temp_dir}{reldst}' - os.mkdir(fulldst) + Path(fulldst).mkdir(parents=True) public_dir(fulldst) fields = { diff --git a/test/test_java_isolation_rootfs.py b/test/test_java_isolation_rootfs.py index 66b2a81e..0ed66133 100644 --- a/test/test_java_isolation_rootfs.py +++ b/test/test_java_isolation_rootfs.py @@ -2,6 +2,7 @@ import os import subprocess import pytest + from unit.applications.lang.java import ApplicationJava from unit.option import option @@ -25,6 +26,7 @@ def setup_method_fixture(temp_dir): f'{temp_dir}/jars', ], stderr=subprocess.STDOUT, + check=True, ) except KeyboardInterrupt: @@ -39,6 +41,7 @@ def setup_method_fixture(temp_dir): subprocess.run( ["umount", "--lazy", f"{option.temp_dir}/jars"], stderr=subprocess.STDOUT, + check=True, ) except KeyboardInterrupt: diff --git a/test/test_java_websockets.py b/test/test_java_websockets.py index c323830b..94ac6f86 100644 --- a/test/test_java_websockets.py +++ b/test/test_java_websockets.py @@ -2,6 +2,7 @@ import struct import time import pytest + from unit.applications.lang.java import ApplicationJava from unit.applications.websockets import ApplicationWebsocket diff --git a/test/test_njs.py b/test/test_njs.py index ce92e1ef..aaaa23aa 100644 --- a/test/test_njs.py +++ b/test/test_njs.py @@ -1,6 +1,7 @@ -import os +from pathlib import Path import pytest + from unit.applications.proto import ApplicationProto from unit.option import option from unit.utils import waitforfiles @@ -22,9 +23,9 @@ def setup_method_fixture(temp_dir): def create_files(*files): assets_dir = f'{option.temp_dir}/assets/' - os.makedirs(assets_dir) + Path(assets_dir).mkdir() - [open(assets_dir + f, 'a') for f in files] + _ = [Path(assets_dir + f).touch() for f in files] waitforfiles(*[assets_dir + f for f in files]) diff --git a/test/test_node_application.py b/test/test_node_application.py index 5077b9cb..aaad2bcf 100644 --- a/test/test_node_application.py +++ b/test/test_node_application.py @@ -1,6 +1,7 @@ import re import pytest + from unit.applications.lang.node import ApplicationNode from unit.utils import waitforfiles @@ -149,11 +150,13 @@ def test_node_application_write_buffer(): assert client.get()['body'] == 'buffer', 'write buffer' + def test_node_application_write_array(): client.load('write_array') assert client.get()['body'] == 'array', 'write array' + def test_node_application_write_callback(temp_dir): client.load('write_callback') @@ -303,11 +306,13 @@ def test_node_application_get_header_names(): 'x-header', ], 'get header names' + def test_node_application_flush_headers(): client.load('flush_headers') assert client.get()['headers']['X-Header'] == 'blah' + def test_node_application_has_header(): client.load('has_header') diff --git a/test/test_node_es_modules.py b/test/test_node_es_modules.py index ac2c545f..4effafea 100644 --- a/test/test_node_es_modules.py +++ b/test/test_node_es_modules.py @@ -1,4 +1,5 @@ from packaging import version + from unit.applications.lang.node import ApplicationNode from unit.applications.websockets import ApplicationWebsocket diff --git a/test/test_node_websockets.py b/test/test_node_websockets.py index d26452aa..68bdd578 100644 --- a/test/test_node_websockets.py +++ b/test/test_node_websockets.py @@ -2,6 +2,7 @@ import struct import time import pytest + from unit.applications.lang.node import ApplicationNode from unit.applications.websockets import ApplicationWebsocket diff --git a/test/test_perl_application.py b/test/test_perl_application.py index 115b0ec7..ad355117 100644 --- a/test/test_perl_application.py +++ b/test/test_perl_application.py @@ -1,6 +1,7 @@ import re import pytest + from unit.applications.lang.perl import ApplicationPerl prerequisites = {'modules': {'perl': 'all'}} diff --git a/test/test_php_application.py b/test/test_php_application.py index 8a6641cb..90db38fa 100644 --- a/test/test_php_application.py +++ b/test/test_php_application.py @@ -7,6 +7,7 @@ import time from pathlib import Path import pytest + from unit.applications.lang.php import ApplicationPHP from unit.option import option @@ -93,13 +94,13 @@ def set_opcache(app, val): def set_preload(preload): - with open(f'{option.temp_dir}/php.ini', 'w') as ini: - ini.write( - f"""opcache.preload = {option.test_dir}/php/opcache/preload\ + Path(f'{option.temp_dir}/php.ini').write_text( + f"""opcache.preload = {option.test_dir}/php/opcache/preload\ /{preload} opcache.preload_user = {option.user or getpass.getuser()} -""" - ) +""", + encoding='utf-8', + ) assert 'success' in client.conf( {"file": f"{option.temp_dir}/php.ini"}, @@ -718,9 +719,11 @@ def test_php_application_index_default(): def test_php_application_trailing_slash(temp_dir): new_root = f'{temp_dir}/php-root' - os.makedirs(f'{new_root}/path') - Path(f'{new_root}/path/index.php').write_text('<?php echo "OK\n"; ?>') + Path(f'{new_root}/path').mkdir(parents=True) + Path(f'{new_root}/path/index.php').write_text( + '<?php echo "OK\n"; ?>', encoding='utf-8' + ) addr = f'{temp_dir}/sock' @@ -761,9 +764,7 @@ def test_php_application_trailing_slash(temp_dir): def test_php_application_forbidden(temp_dir): - new_root = f'{temp_dir}/php-root/path' - os.makedirs(new_root) - os.chmod(new_root, 0o000) + Path(f'{temp_dir}/php-root/path').mkdir(mode=0o000, parents=True) assert 'success' in client.conf( { @@ -787,7 +788,7 @@ def test_php_application_extension_check(temp_dir): assert client.get(url='/index.wrong')['status'] != 200, 'status' new_root = f'{temp_dir}/php' - os.mkdir(new_root) + Path(new_root).mkdir(parents=True) shutil.copy(f'{option.test_dir}/php/phpinfo/index.wrong', new_root) assert 'success' in client.conf( diff --git a/test/test_proxy.py b/test/test_proxy.py index b64e19db..cd16fe5e 100644 --- a/test/test_proxy.py +++ b/test/test_proxy.py @@ -3,6 +3,7 @@ import socket import time import pytest + from conftest import run_process from unit.applications.lang.python import ApplicationPython from unit.option import option diff --git a/test/test_proxy_chunked.py b/test/test_proxy_chunked.py index f9e9fe10..23476cd9 100644 --- a/test/test_proxy_chunked.py +++ b/test/test_proxy_chunked.py @@ -4,6 +4,7 @@ import socket import time import pytest + from conftest import run_process from unit.applications.lang.python import ApplicationPython from unit.utils import waitforsocket @@ -52,7 +53,7 @@ def run_server(server_port): part = sock.recv(buff_size) data += part - if not len(part): + if not part: break return data @@ -80,7 +81,7 @@ def run_server(server_port): req = f'{req}{add}\r\n' for chunk in re.split(r'([@#])', req): - if chunk == '@' or chunk == '#': + if chunk in ('@', '#'): if chunk == '#': time.sleep(0.1) continue @@ -90,10 +91,10 @@ def run_server(server_port): connection.close() -def chunks(chunks): +def chunks(chunks_lst): body = '\r\n\r\n' - for l, c in chunks: + for l, c in chunks_lst: body = f'{body}{l}\r\n{c}\r\n' return f'{body}0\r\n\r\n' diff --git a/test/test_python_application.py b/test/test_python_application.py index 058a87df..466a59a2 100644 --- a/test/test_python_application.py +++ b/test/test_python_application.py @@ -8,6 +8,7 @@ import venv import pytest from packaging import version + from unit.applications.lang.python import ApplicationPython prerequisites = {'modules': {'python': 'all'}} @@ -586,8 +587,8 @@ def test_python_application_encoding(): if not matches: pytest.skip('no available locales') - def unify(str): - str.upper().replace('-', '').replace('_', '') + def unify(enc): + enc.upper().replace('-', '').replace('_', '') for loc in matches: assert 'success' in client.conf( diff --git a/test/test_python_isolation.py b/test/test_python_isolation.py index 5b97e292..fd692cb6 100644 --- a/test/test_python_isolation.py +++ b/test/test_python_isolation.py @@ -1,9 +1,9 @@ -import os import re import subprocess from pathlib import Path import pytest + from unit.applications.lang.python import ApplicationPython from unit.option import option from unit.utils import findmnt @@ -24,10 +24,10 @@ def get_cgroup(app_name): cgroup = f'/proc/{pid}/cgroup' - if not os.path.isfile(cgroup): + if not Path(cgroup).is_file(): pytest.skip(f'no cgroup at {cgroup}') - with open(cgroup, 'r') as f: + with open(cgroup, 'r', encoding='utf-8') as f: return f.read().rstrip() diff --git a/test/test_python_procman.py b/test/test_python_procman.py index 4643a9b8..b4378c4f 100644 --- a/test/test_python_procman.py +++ b/test/test_python_procman.py @@ -4,6 +4,7 @@ import subprocess import time import pytest + from unit.applications.lang.python import ApplicationPython from unit.option import option diff --git a/test/test_reconfigure.py b/test/test_reconfigure.py index a5fe1b1a..28d1b4c9 100644 --- a/test/test_reconfigure.py +++ b/test/test_reconfigure.py @@ -1,6 +1,7 @@ import time import pytest + from unit.applications.proto import ApplicationProto client = ApplicationProto() diff --git a/test/test_reconfigure_tls.py b/test/test_reconfigure_tls.py index 50638391..3cd01b13 100644 --- a/test/test_reconfigure_tls.py +++ b/test/test_reconfigure_tls.py @@ -3,6 +3,7 @@ import ssl import time import pytest + from unit.applications.tls import ApplicationTLS prerequisites = {'modules': {'openssl': 'any'}} @@ -93,6 +94,8 @@ def test_reconfigure_tls_2(): clear_conf() + success = False + try: ssl_sock.do_handshake() except ssl.SSLError: diff --git a/test/test_respawn.py b/test/test_respawn.py index dc465cda..03254037 100644 --- a/test/test_respawn.py +++ b/test/test_respawn.py @@ -3,6 +3,7 @@ import subprocess import time import pytest + from unit.applications.lang.python import ApplicationPython prerequisites = {'modules': {'python': 'any'}} diff --git a/test/test_response_headers.py b/test/test_response_headers.py index ec07c8c4..e62c1293 100644 --- a/test/test_response_headers.py +++ b/test/test_response_headers.py @@ -1,8 +1,9 @@ from pathlib import Path import pytest -from unit.applications.proto import ApplicationProto + from unit.applications.lang.python import ApplicationPython +from unit.applications.proto import ApplicationProto from unit.option import option client = ApplicationProto() @@ -12,7 +13,7 @@ client_python = ApplicationPython() @pytest.fixture(autouse=True) def setup_method_fixture(temp_dir): path = Path(f'{temp_dir}/index.html') - path.write_text('0123456789') + path.write_text('0123456789', encoding='utf-8') assert 'success' in client.conf( { diff --git a/test/test_return.py b/test/test_return.py index 3ffcaa4e..af15b886 100644 --- a/test/test_return.py +++ b/test/test_return.py @@ -1,6 +1,7 @@ import re import pytest + from unit.applications.proto import ApplicationProto client = ApplicationProto() @@ -90,7 +91,7 @@ def test_return_update(): def test_return_location(): reserved = ":/?#[]@!&'()*+,;=" unreserved = ( - "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" "0123456789-._~" + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~" ) unsafe = " \"%<>\\^`{|}" unsafe_enc = "%20%22%25%3C%3E%5C%5E%60%7B%7C%7D" diff --git a/test/test_rewrite.py b/test/test_rewrite.py index 0a4ffe42..f94fb528 100644 --- a/test/test_rewrite.py +++ b/test/test_rewrite.py @@ -1,6 +1,7 @@ -import os +from pathlib import Path import pytest + from unit.applications.proto import ApplicationProto client = ApplicationProto() @@ -39,9 +40,9 @@ def set_rewrite(rewrite, uri): def test_rewrite(findall, wait_for_record): assert client.get()['status'] == 200 - assert wait_for_record(rf'\[notice\].*"routes/1" selected') is not None - assert len(findall(rf'\[notice\].*URI rewritten to "/new"')) == 1 - assert len(findall(rf'\[notice\].*URI rewritten')) == 1 + assert wait_for_record(r'\[notice\].*"routes/1" selected') is not None + assert len(findall(r'\[notice\].*URI rewritten to "/new"')) == 1 + assert len(findall(r'\[notice\].*URI rewritten')) == 1 set_rewrite("", "") assert client.get()['status'] == 200 @@ -131,11 +132,9 @@ def test_rewrite_location(): def test_rewrite_share(temp_dir): - os.makedirs(f'{temp_dir}/dir') - os.makedirs(f'{temp_dir}/foo') - - with open(f'{temp_dir}/foo/index.html', 'w') as fooindex: - fooindex.write('fooindex') + Path(f'{temp_dir}/dir').mkdir() + Path(f'{temp_dir}/foo/').mkdir() + Path(f'{temp_dir}/foo/index.html').write_text('fooindex', encoding='utf-8') # same action block diff --git a/test/test_routing.py b/test/test_routing.py index ce5952eb..0b6eced2 100644 --- a/test/test_routing.py +++ b/test/test_routing.py @@ -1,5 +1,6 @@ # -*- coding: utf-8 -*- import pytest + from unit.applications.lang.python import ApplicationPython from unit.option import option @@ -24,8 +25,8 @@ def setup_method_fixture(): ), 'routing configure' -def route(route): - return client.conf([route], 'routes') +def route(conf_route): + return client.conf([conf_route], 'routes') def route_match(match): @@ -40,19 +41,21 @@ def route_match_invalid(match): ), 'route match configure invalid' -def host(host, status): +def host(host_header, status): assert ( - client.get(headers={'Host': host, 'Connection': 'close'})['status'] + client.get(headers={'Host': host_header, 'Connection': 'close'})[ + 'status' + ] == status ), 'match host' -def cookie(cookie, status): +def cookie(cookie_header, status): assert ( client.get( headers={ 'Host': 'localhost', - 'Cookie': cookie, + 'Cookie': cookie_header, 'Connection': 'close', }, )['status'] diff --git a/test/test_ruby_application.py b/test/test_ruby_application.py index 3ac62f71..aae89999 100644 --- a/test/test_ruby_application.py +++ b/test/test_ruby_application.py @@ -2,6 +2,7 @@ import re import subprocess import pytest + from unit.applications.lang.ruby import ApplicationRuby prerequisites = {'modules': {'ruby': 'all'}} diff --git a/test/test_settings.py b/test/test_settings.py index 0cdc6c0d..9d37d6ca 100644 --- a/test/test_settings.py +++ b/test/test_settings.py @@ -4,6 +4,7 @@ import subprocess import time import pytest + from unit.applications.lang.python import ApplicationPython prerequisites = {'modules': {'python': 'any'}} diff --git a/test/test_static.py b/test/test_static.py index 98f27c7f..e2fc2283 100644 --- a/test/test_static.py +++ b/test/test_static.py @@ -1,7 +1,9 @@ import os import socket +from pathlib import Path import pytest + from unit.applications.proto import ApplicationProto from unit.utils import waitforfiles @@ -11,18 +13,13 @@ client = ApplicationProto() @pytest.fixture(autouse=True) def setup_method_fixture(temp_dir): - os.makedirs(f'{temp_dir}/assets/dir') assets_dir = f'{temp_dir}/assets' - with open(f'{assets_dir}/index.html', 'w') as index, open( - f'{assets_dir}/README', 'w' - ) as readme, open(f'{assets_dir}/log.log', 'w') as log, open( - f'{assets_dir}/dir/file', 'w' - ) as file: - index.write('0123456789') - readme.write('readme') - log.write('[debug]') - file.write('blah') + Path(f'{assets_dir}/dir').mkdir(parents=True) + Path(f'{assets_dir}/index.html').write_text('0123456789', encoding='utf-8') + Path(f'{assets_dir}/README').write_text('readme', encoding='utf-8') + Path(f'{assets_dir}/log.log').write_text('[debug]', encoding='utf-8') + Path(f'{assets_dir}/dir/file').write_text('blah', encoding='utf-8') assert 'success' in client.conf( { @@ -103,7 +100,7 @@ def test_static_etag(temp_dir): assert etag != etag_2, 'different ETag' assert etag == client.get(url='/')['headers']['ETag'], 'same ETag' - with open(f'{temp_dir}/assets/index.html', 'w') as f: + with open(f'{temp_dir}/assets/index.html', 'w', encoding='utf-8') as f: f.write('blah') assert etag != client.get(url='/')['headers']['ETag'], 'new ETag' @@ -119,18 +116,16 @@ def test_static_redirect(): def test_static_space_in_name(temp_dir): assets_dir = f'{temp_dir}/assets' - os.rename( - f'{assets_dir}/dir/file', - f'{assets_dir}/dir/fi le', - ) + Path(f'{assets_dir}/dir/file').rename(f'{assets_dir}/dir/fi le') + assert waitforfiles(f'{assets_dir}/dir/fi le') assert client.get(url='/dir/fi le')['body'] == 'blah', 'file name' - os.rename(f'{assets_dir}/dir', f'{assets_dir}/di r') + Path(f'{assets_dir}/dir').rename(f'{assets_dir}/di r') assert waitforfiles(f'{assets_dir}/di r/fi le') assert client.get(url='/di r/fi le')['body'] == 'blah', 'dir name' - os.rename(f'{assets_dir}/di r', f'{assets_dir}/ di r ') + Path(f'{assets_dir}/di r').rename(f'{assets_dir}/ di r ') assert waitforfiles(f'{assets_dir}/ di r /fi le') assert ( client.get(url='/ di r /fi le')['body'] == 'blah' @@ -149,17 +144,14 @@ def test_static_space_in_name(temp_dir): == 'blah' ), 'encoded 2' - os.rename( - f'{assets_dir}/ di r /fi le', - f'{assets_dir}/ di r / fi le ', - ) + Path(f'{assets_dir}/ di r /fi le').rename(f'{assets_dir}/ di r / fi le ') assert waitforfiles(f'{assets_dir}/ di r / fi le ') assert ( client.get(url='/%20di%20r%20/%20fi%20le%20')['body'] == 'blah' ), 'file name enclosing' try: - open(f'{temp_dir}/ф а', 'a').close() + Path(f'{temp_dir}/ф а').touch() utf8 = True except KeyboardInterrupt: @@ -169,17 +161,13 @@ def test_static_space_in_name(temp_dir): utf8 = False if utf8: - os.rename( - f'{assets_dir}/ di r / fi le ', - f'{assets_dir}/ di r /фа йл', + Path(f'{assets_dir}/ di r / fi le ').rename( + f'{assets_dir}/ di r /фа йл' ) assert waitforfiles(f'{assets_dir}/ di r /фа йл') assert client.get(url='/ di r /фа йл')['body'] == 'blah' - os.rename( - f'{assets_dir}/ di r ', - f'{assets_dir}/ди ректория', - ) + Path(f'{assets_dir}/ di r ').rename(f'{assets_dir}/ди ректория') assert waitforfiles(f'{assets_dir}/ди ректория/фа йл') assert ( client.get(url='/ди ректория/фа йл')['body'] == 'blah' diff --git a/test/test_static_chroot.py b/test/test_static_chroot.py index fb14d7ab..31e10b4e 100644 --- a/test/test_static_chroot.py +++ b/test/test_static_chroot.py @@ -2,21 +2,23 @@ import os from pathlib import Path import pytest + from unit.applications.proto import ApplicationProto from unit.option import option prerequisites = {'features': {'chroot': True}} client = ApplicationProto() +test_path = f'/{os.path.relpath(Path(__file__))}' @pytest.fixture(autouse=True) def setup_method_fixture(temp_dir): - os.makedirs(f'{temp_dir}/assets/dir') - Path(f'{temp_dir}/assets/index.html').write_text('0123456789') - Path(f'{temp_dir}/assets/dir/file').write_text('blah') - - client.test_path = f'/{os.path.relpath(Path(__file__))}' + Path(f'{temp_dir}/assets/dir').mkdir(parents=True) + Path(f'{temp_dir}/assets/index.html').write_text( + '0123456789', encoding='utf-8' + ) + Path(f'{temp_dir}/assets/dir/file').write_text('blah', encoding='utf-8') assert 'success' in client.conf( { @@ -85,7 +87,7 @@ def test_static_chroot_empty(): assert client.get(url='/dir/file')['status'] == 200, 'empty absolute' assert 'success' in update_action("", ".$uri") - assert client.get(url=client.test_path)['status'] == 200, 'empty relative' + assert client.get(url=test_path)['status'] == 200, 'empty relative' def test_static_chroot_relative(require): @@ -95,10 +97,10 @@ def test_static_chroot_relative(require): assert client.get(url='/dir/file')['status'] == 403, 'relative chroot' assert 'success' in client.conf({"share": ".$uri"}, 'routes/0/action') - assert client.get(url=client.test_path)['status'] == 200, 'relative share' + assert client.get(url=test_path)['status'] == 200, 'relative share' assert 'success' in update_action(".", ".$uri") - assert client.get(url=client.test_path)['status'] == 200, 'relative' + assert client.get(url=test_path)['status'] == 200, 'relative' def test_static_chroot_variables(temp_dir): diff --git a/test/test_static_fallback.py b/test/test_static_fallback.py index 25e466a3..9b5fcb53 100644 --- a/test/test_static_fallback.py +++ b/test/test_static_fallback.py @@ -2,6 +2,7 @@ import os from pathlib import Path import pytest + from unit.applications.proto import ApplicationProto client = ApplicationProto() @@ -11,7 +12,7 @@ client = ApplicationProto() def setup_method_fixture(temp_dir): assets_dir = f'{temp_dir}/assets' os.makedirs(f'{assets_dir}/dir') - Path(f'{assets_dir}/index.html').write_text('0123456789') + Path(f'{assets_dir}/index.html').write_text('0123456789', encoding='utf-8') os.makedirs(f'{assets_dir}/403') os.chmod(f'{assets_dir}/403', 0o000) diff --git a/test/test_static_mount.py b/test/test_static_mount.py index d8d3b698..41b436e2 100644 --- a/test/test_static_mount.py +++ b/test/test_static_mount.py @@ -3,6 +3,7 @@ import subprocess from pathlib import Path import pytest + from unit.applications.proto import ApplicationProto prerequisites = {'features': {'chroot': True}, 'privileged_user': True} @@ -15,9 +16,11 @@ def setup_method_fixture(temp_dir): os.makedirs(f'{temp_dir}/assets/dir/mount') os.makedirs(f'{temp_dir}/assets/dir/dir') os.makedirs(f'{temp_dir}/assets/mount') - Path(f'{temp_dir}/assets/index.html').write_text('index') - Path(f'{temp_dir}/assets/dir/dir/file').write_text('file') - Path(f'{temp_dir}/assets/mount/index.html').write_text('mount') + Path(f'{temp_dir}/assets/index.html').write_text('index', encoding='utf-8') + Path(f'{temp_dir}/assets/dir/dir/file').write_text('file', encoding='utf-8') + Path(f'{temp_dir}/assets/mount/index.html').write_text( + 'mount', encoding='utf-8' + ) try: subprocess.check_output( diff --git a/test/test_static_share.py b/test/test_static_share.py index fa16d267..ee53fe9b 100644 --- a/test/test_static_share.py +++ b/test/test_static_share.py @@ -2,6 +2,7 @@ import os from pathlib import Path import pytest + from unit.applications.proto import ApplicationProto client = ApplicationProto() @@ -12,8 +13,8 @@ def setup_method_fixture(temp_dir): os.makedirs(f'{temp_dir}/assets/dir') os.makedirs(f'{temp_dir}/assets/dir2') - Path(f'{temp_dir}/assets/dir/file').write_text('1') - Path(f'{temp_dir}/assets/dir2/file2').write_text('2') + Path(f'{temp_dir}/assets/dir/file').write_text('1', encoding='utf-8') + Path(f'{temp_dir}/assets/dir2/file2').write_text('2', encoding='utf-8') assert 'success' in client.conf( { diff --git a/test/test_static_symlink.py b/test/test_static_symlink.py index 3b04d70c..2d402d48 100644 --- a/test/test_static_symlink.py +++ b/test/test_static_symlink.py @@ -2,6 +2,7 @@ import os from pathlib import Path import pytest + from unit.applications.proto import ApplicationProto prerequisites = {'features': {'chroot': True}} @@ -12,8 +13,10 @@ client = ApplicationProto() @pytest.fixture(autouse=True) def setup_method_fixture(temp_dir): os.makedirs(f'{temp_dir}/assets/dir/dir') - Path(f'{temp_dir}/assets/index.html').write_text('0123456789') - Path(f'{temp_dir}/assets/dir/file').write_text('blah') + Path(f'{temp_dir}/assets/index.html').write_text( + '0123456789', encoding='utf-8' + ) + Path(f'{temp_dir}/assets/dir/file').write_text('blah', encoding='utf-8') assert 'success' in client.conf( { diff --git a/test/test_static_types.py b/test/test_static_types.py index a468319a..e931d949 100644 --- a/test/test_static_types.py +++ b/test/test_static_types.py @@ -1,6 +1,7 @@ from pathlib import Path import pytest + from unit.applications.proto import ApplicationProto client = ApplicationProto() @@ -10,9 +11,9 @@ client = ApplicationProto() def setup_method_fixture(temp_dir): Path(f'{temp_dir}/assets').mkdir() for ext in ['.xml', '.mp4', '.php', '', '.txt', '.html', '.png']: - Path(f'{temp_dir}/assets/file{ext}').write_text(ext) + Path(f'{temp_dir}/assets/file{ext}').write_text(ext, encoding='utf-8') - Path(f'{temp_dir}/assets/index.html').write_text('index') + Path(f'{temp_dir}/assets/index.html').write_text('index', encoding='utf-8') assert 'success' in client.conf( { diff --git a/test/test_static_variables.py b/test/test_static_variables.py index 5afd0127..62753750 100644 --- a/test/test_static_variables.py +++ b/test/test_static_variables.py @@ -2,6 +2,7 @@ import os from pathlib import Path import pytest + from unit.applications.proto import ApplicationProto client = ApplicationProto() @@ -11,9 +12,11 @@ client = ApplicationProto() def setup_method_fixture(temp_dir): os.makedirs(f'{temp_dir}/assets/dir') os.makedirs(f'{temp_dir}/assets/d$r') - Path(f'{temp_dir}/assets/index.html').write_text('0123456789') - Path(f'{temp_dir}/assets/dir/file').write_text('file') - Path(f'{temp_dir}/assets/d$r/file').write_text('d$r') + Path(f'{temp_dir}/assets/index.html').write_text( + '0123456789', encoding='utf-8' + ) + Path(f'{temp_dir}/assets/dir/file').write_text('file', encoding='utf-8') + Path(f'{temp_dir}/assets/d$r/file').write_text('d$r', encoding='utf-8') assert 'success' in client.conf( { diff --git a/test/test_tls.py b/test/test_tls.py index a56d5428..09921773 100644 --- a/test/test_tls.py +++ b/test/test_tls.py @@ -2,8 +2,10 @@ import io import ssl import subprocess import time +from pathlib import Path import pytest + from unit.applications.tls import ApplicationTLS from unit.option import option @@ -53,9 +55,8 @@ def context_cert_req(cert='root'): def generate_ca_conf(): - with open(f'{option.temp_dir}/ca.conf', 'w') as f: - f.write( - f"""[ ca ] + Path(f'{option.temp_dir}/ca.conf').write_text( + f"""[ ca ] default_ca = myca [ myca ] @@ -72,17 +73,13 @@ copy_extensions = copy commonName = optional [ myca_extensions ] -basicConstraints = critical,CA:TRUE""" - ) - - with open(f'{option.temp_dir}/certserial', 'w') as f: - f.write('1000') - - with open(f'{option.temp_dir}/certindex', 'w') as f: - f.write('') +basicConstraints = critical,CA:TRUE""", + encoding='utf-8', + ) - with open(f'{option.temp_dir}/certindex.attr', 'w') as f: - f.write('') + Path(f'{option.temp_dir}/certserial').write_text('1000', encoding='utf-8') + Path(f'{option.temp_dir}/certindex').touch() + Path(f'{option.temp_dir}/certindex.attr').touch() def remove_tls(application='empty', port=8080): @@ -322,8 +319,8 @@ def test_tls_certificate_chain(temp_dir): with open(crt_path, 'wb') as crt, open(end_path, 'rb') as end, open( int_path, 'rb' - ) as int: - crt.write(end.read() + int.read()) + ) as inter: + crt.write(end.read() + inter.read()) # incomplete chain @@ -428,7 +425,9 @@ def test_tls_certificate_chain_long(temp_dir): else f'{temp_dir}/int{i}.crt' ) - with open(f'{temp_dir}/all.crt', 'a') as chain, open(path) as cert: + with open(f'{temp_dir}/all.crt', 'a', encoding='utf-8') as chain, open( + path, encoding='utf-8' + ) as cert: chain.write(cert.read()) assert 'success' in client.certificate_load( diff --git a/test/test_tls_conf_command.py b/test/test_tls_conf_command.py index 4d772c83..5a9a3f32 100644 --- a/test/test_tls_conf_command.py +++ b/test/test_tls_conf_command.py @@ -1,6 +1,7 @@ import ssl import pytest + from unit.applications.tls import ApplicationTLS prerequisites = {'modules': {'openssl': 'any'}} diff --git a/test/test_tls_sni.py b/test/test_tls_sni.py index aa7ed3c5..61d72125 100644 --- a/test/test_tls_sni.py +++ b/test/test_tls_sni.py @@ -2,6 +2,7 @@ import ssl import subprocess import pytest + from unit.applications.tls import ApplicationTLS from unit.option import option @@ -104,7 +105,7 @@ def config_bundles(bundles): def generate_ca_conf(): - with open(f'{option.temp_dir}/ca.conf', 'w') as f: + with open(f'{option.temp_dir}/ca.conf', 'w', encoding='utf-8') as f: f.write( f"""[ ca ] default_ca = myca @@ -126,10 +127,10 @@ commonName = optional basicConstraints = critical,CA:TRUE""" ) - with open(f'{option.temp_dir}/certserial', 'w') as f: + with open(f'{option.temp_dir}/certserial', 'w', encoding='utf-8') as f: f.write('1000') - with open(f'{option.temp_dir}/certindex', 'w') as f: + with open(f'{option.temp_dir}/certindex', 'w', encoding='utf-8') as f: f.write('') diff --git a/test/test_upstreams_rr.py b/test/test_upstreams_rr.py index ecf24add..a2dc5c68 100644 --- a/test/test_upstreams_rr.py +++ b/test/test_upstreams_rr.py @@ -2,6 +2,7 @@ import os import re import pytest + from unit.applications.lang.python import ApplicationPython from unit.option import option diff --git a/test/test_usr1.py b/test/test_usr1.py index ce756fc0..ecb4d8fd 100644 --- a/test/test_usr1.py +++ b/test/test_usr1.py @@ -1,5 +1,6 @@ import os import signal +from pathlib import Path from unit.applications.lang.python import ApplicationPython from unit.log import Log @@ -23,14 +24,14 @@ def test_usr1_access_log(search_in_file, temp_dir, unit_pid, wait_for_record): assert waitforfiles(log_path), 'open' - os.rename(log_path, f'{temp_dir}/{log_new}') + Path(log_path).rename(f'{temp_dir}/{log_new}') assert client.get()['status'] == 200 assert ( wait_for_record(r'"GET / HTTP/1.1" 200 0 "-" "-"', log_new) is not None ), 'rename new' - assert not os.path.isfile(log_path), 'rename old' + assert not Path(log_path).is_file(), 'rename old' os.kill(unit_pid, signal.SIGUSR1) @@ -51,7 +52,7 @@ def test_usr1_unit_log(search_in_file, temp_dir, unit_pid, wait_for_record): log_path = f'{temp_dir}/unit.log' log_path_new = f'{temp_dir}/{log_new}' - os.rename(log_path, log_path_new) + Path(log_path).rename(log_path_new) Log.swap(log_new) @@ -60,7 +61,7 @@ def test_usr1_unit_log(search_in_file, temp_dir, unit_pid, wait_for_record): assert client.post(body=body)['status'] == 200 assert wait_for_record(body, log_new) is not None, 'rename new' - assert not os.path.isfile(log_path), 'rename old' + assert not Path(log_path).is_file(), 'rename old' os.kill(unit_pid, signal.SIGUSR1) @@ -75,13 +76,10 @@ def test_usr1_unit_log(search_in_file, temp_dir, unit_pid, wait_for_record): finally: # merge two log files into unit.log to check alerts - with open(log_path, 'r', errors='ignore') as unit_log: - log = unit_log.read() - - with open(log_path, 'w') as unit_log, open( - log_path_new, 'r', errors='ignore' - ) as unit_log_new: - unit_log.write(unit_log_new.read()) - unit_log.write(log) + path_log = Path(log_path) + log = path_log.read_text(encoding='utf-8', errors='ignore') + Path( + log_path_new + ).read_text(encoding='utf-8', errors='ignore') + path_log.write_text(log, encoding='utf-8', errors='ignore') Log.swap(log_new) diff --git a/test/test_variables.py b/test/test_variables.py index 0b7b9ea8..9aab8a62 100644 --- a/test/test_variables.py +++ b/test/test_variables.py @@ -1,11 +1,11 @@ -import os -from pathlib import Path import re import time +from pathlib import Path import pytest -from unit.applications.proto import ApplicationProto + from unit.applications.lang.python import ApplicationPython +from unit.applications.proto import ApplicationProto from unit.option import option client = ApplicationProto() @@ -22,11 +22,11 @@ def setup_method_fixture(): ), 'configure routes' -def set_format(format): +def set_format(log_format): assert 'success' in client.conf( { 'path': f'{option.temp_dir}/access.log', - 'format': format, + 'format': log_format, }, 'access_log', ), 'access_log format' @@ -127,8 +127,8 @@ def test_variables_uri(search_in_file, wait_for_record): def test_variables_uri_no_cache(temp_dir): - os.makedirs(f'{temp_dir}/foo/bar') - Path(f'{temp_dir}/foo/bar/index.html').write_text('index') + Path(f'{temp_dir}/foo/bar').mkdir(parents=True) + Path(f'{temp_dir}/foo/bar/index.html').write_text('index', encoding='utf-8') assert 'success' in client.conf( { @@ -443,7 +443,7 @@ def test_variables_response_header(temp_dir, wait_for_record): # share Path(f'{temp_dir}/foo').mkdir() - Path(f'{temp_dir}/foo/index.html').write_text('index') + Path(f'{temp_dir}/foo/index.html').write_text('index', encoding='utf-8') assert 'success' in client.conf( { @@ -514,11 +514,11 @@ def test_variables_response_header_application(require, wait_for_record): def test_variables_invalid(temp_dir): - def check_variables(format): + def check_variables(log_format): assert 'error' in client.conf( { 'path': f'{temp_dir}/access.log', - 'format': format, + 'format': log_format, }, 'access_log', ), 'access_log format' diff --git a/test/unit/applications/lang/go.py b/test/unit/applications/lang/go.py index 5aca5048..2479d4f6 100644 --- a/test/unit/applications/lang/go.py +++ b/test/unit/applications/lang/go.py @@ -53,7 +53,7 @@ class ApplicationGo(ApplicationProto): replace_path = f'{option.current_dir}/build/go/src/unit.nginx.org/go' - with open(f'{temp_dir}go.mod', 'w') as f: + with open(f'{temp_dir}go.mod', 'w', encoding='utf-8') as f: f.write( f"""module test/app require unit.nginx.org/go v0.0.0 diff --git a/test/unit/applications/lang/php.py b/test/unit/applications/lang/php.py index 2ab172b0..ac59ec1b 100644 --- a/test/unit/applications/lang/php.py +++ b/test/unit/applications/lang/php.py @@ -1,4 +1,4 @@ -import os +from pathlib import Path import shutil from unit.applications.proto import ApplicationProto @@ -15,10 +15,9 @@ class ApplicationPHP(ApplicationProto): if kwargs.get('isolation') and kwargs['isolation'].get('rootfs'): rootfs = kwargs['isolation']['rootfs'] - if not os.path.exists(f'{rootfs}/app/php/'): - os.makedirs(f'{rootfs}/app/php/') + Path(f'{rootfs}/app/php/').mkdir(parents=True, exist_ok=True) - if not os.path.exists(f'{rootfs}/app/php/{script}'): + if not Path(f'{rootfs}/app/php/{script}').exists(): shutil.copytree(script_path, f'{rootfs}/app/php/{script}') script_path = f'/app/php/{script}' diff --git a/test/unit/applications/lang/python.py b/test/unit/applications/lang/python.py index 67304d12..67684b04 100644 --- a/test/unit/applications/lang/python.py +++ b/test/unit/applications/lang/python.py @@ -1,4 +1,4 @@ -import os +from pathlib import Path import shutil from urllib.parse import quote @@ -26,10 +26,9 @@ class ApplicationPython(ApplicationProto): if kwargs.get('isolation') and kwargs['isolation'].get('rootfs'): rootfs = kwargs['isolation']['rootfs'] - if not os.path.exists(f'{rootfs}/app/python/'): - os.makedirs(f'{rootfs}/app/python/') + Path(f'{rootfs}/app/python/').mkdir(parents=True, exist_ok=True) - if not os.path.exists(f'{rootfs}/app/python/{name}'): + if not Path(f'{rootfs}/app/python/{name}').exists(): shutil.copytree(script_path, f'{rootfs}/app/python/{name}') script_path = f'/app/python/{name}' diff --git a/test/unit/applications/tls.py b/test/unit/applications/tls.py index 50a27348..75354dd9 100644 --- a/test/unit/applications/tls.py +++ b/test/unit/applications/tls.py @@ -79,7 +79,7 @@ subjectAltName = @alt_names {a_names}''' - with open(conf_path, 'w') as f: + with open(conf_path, 'w', encoding='utf-8') as f: f.write( f'''[ req ] default_bits = 2048 diff --git a/test/unit/applications/websockets.py b/test/unit/applications/websockets.py index 29725943..a8e563d0 100644 --- a/test/unit/applications/websockets.py +++ b/test/unit/applications/websockets.py @@ -6,6 +6,7 @@ import select import struct import pytest + from unit.applications.proto import ApplicationProto GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" @@ -69,7 +70,7 @@ class ApplicationWebsocket(ApplicationProto): return struct.pack('!H', code) + reason.encode('utf-8') def frame_read(self, sock, read_timeout=60): - def recv_bytes(sock, bytes): + def recv_bytes(sock, bytes_len): data = b'' while True: rlist = select.select([sock], [], [], read_timeout)[0] @@ -80,9 +81,9 @@ class ApplicationWebsocket(ApplicationProto): pytest.fail("Can't read response from server.") break - data += sock.recv(bytes - len(data)) + data += sock.recv(bytes_len - len(data)) - if len(data) == bytes: + if len(data) == bytes_len: break return data @@ -206,18 +207,18 @@ class ApplicationWebsocket(ApplicationProto): end = frame_len pos = end - def message(self, sock, type, message, fragmention_size=None, **kwargs): + def message(self, sock, mes_type, message, fragmention_size=None, **kwargs): message_len = len(message) if fragmention_size is None: fragmention_size = message_len if message_len <= fragmention_size: - self.frame_write(sock, type, message, **kwargs) + self.frame_write(sock, mes_type, message, **kwargs) return pos = 0 - op_code = type + op_code = mes_type while pos < message_len: end = min(pos + fragmention_size, message_len) fin = end == message_len diff --git a/test/unit/check/check_prerequisites.py b/test/unit/check/check_prerequisites.py index 44c3f10f..ea319346 100644 --- a/test/unit/check/check_prerequisites.py +++ b/test/unit/check/check_prerequisites.py @@ -1,4 +1,5 @@ import pytest + from unit.option import option diff --git a/test/unit/check/isolation.py b/test/unit/check/isolation.py index e31179e8..861c0818 100644 --- a/test/unit/check/isolation.py +++ b/test/unit/check/isolation.py @@ -1,5 +1,5 @@ import json -import os +from pathlib import Path from unit.applications.lang.go import ApplicationGo from unit.applications.lang.java import ApplicationJava @@ -145,11 +145,12 @@ def check_isolation(): isolation = {'user': userns} - unp_clone_path = '/proc/sys/kernel/unprivileged_userns_clone' - if os.path.exists(unp_clone_path): - with open(unp_clone_path, 'r') as f: - if str(f.read()).rstrip() == '1': - isolation['unprivileged_userns_clone'] = True + path_clone = Path('/proc/sys/kernel/unprivileged_userns_clone') + if ( + path_clone.exists() + and path_clone.read_text(encoding='utf-8').rstrip() == '1' + ): + isolation['unprivileged_userns_clone'] = True for ns in allns: ns_value = getns(ns) diff --git a/test/unit/check/node.py b/test/unit/check/node.py index 6a3d581f..b206e914 100644 --- a/test/unit/check/node.py +++ b/test/unit/check/node.py @@ -1,11 +1,11 @@ -import os import subprocess +from pathlib import Path from unit.option import option def check_node(): - if not os.path.exists(f'{option.current_dir}/node/node_modules'): + if not Path(f'{option.current_dir}/node/node_modules').exists(): return False try: diff --git a/test/unit/control.py b/test/unit/control.py index 164d0e60..8cdf1887 100644 --- a/test/unit/control.py +++ b/test/unit/control.py @@ -16,7 +16,7 @@ def args_handler(conf_func): elif argcount == 3: conf = args[0] - if isinstance(conf, dict) or isinstance(conf, list): + if isinstance(conf, (dict, list)): conf = json.dumps(conf) url = args[1] if len(args) == 2 else url_default diff --git a/test/unit/http.py b/test/unit/http.py index 5a6a1a1b..9401501b 100644 --- a/test/unit/http.py +++ b/test/unit/http.py @@ -7,6 +7,7 @@ import select import socket import pytest + from unit.option import option @@ -38,10 +39,7 @@ class HTTP1: if 'sock' not in kwargs: sock = socket.socket(sock_types[sock_type], socket.SOCK_STREAM) - if ( - sock_type == sock_types['ipv4'] - or sock_type == sock_types['ipv6'] - ): + if sock_type in (sock_types['ipv4'], sock_types['ipv6']): sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) if 'wrapper' in kwargs: @@ -202,7 +200,7 @@ class HTTP1: data += part - if not len(part): + if not part: break return data @@ -263,7 +261,7 @@ class HTTP1: size = int(chunks.pop(0), 16) except ValueError: - pytest.fail(f'Invalid chunk size {size}') + pytest.fail('Invalid chunk size') if size == 0: assert len(chunks) == 1, 'last zero size' diff --git a/test/unit/status.py b/test/unit/status.py index 84c958a3..95096a96 100644 --- a/test/unit/status.py +++ b/test/unit/status.py @@ -30,16 +30,16 @@ class Status: for k in d1 if k in d2 } - else: - return d1 - d2 + + return d1 - d2 return find_diffs(Status.control.conf_get('/status'), Status._status) def get(path='/'): - path = path.split('/')[1:] + path_lst = path.split('/')[1:] diff = Status.diff() - for p in path: - diff = diff[p] + for part in path_lst: + diff = diff[part] return diff |