Tests: pathlib used where appropriate

Also fixed various pylint errors and style issues.
This commit is contained in:
Andrei Zeliankou 2024-01-15 15:48:58 +00:00
parent e95a91cbfa
commit 5a8337933d
72 changed files with 306 additions and 256 deletions

View file

@ -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)

View file

@ -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]

View file

@ -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()),
],
}
)

View file

@ -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)))])

View file

@ -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'))]

View file

@ -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'),
],
}
)

View file

@ -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'),
],
}
)

View file

@ -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']}"
)

View file

@ -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

View file

@ -3,6 +3,7 @@ import time
time.sleep(2)
def application(environ, start_response):
body = str(os.getpid()).encode()

View file

@ -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')])

View file

@ -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',

View file

@ -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')

View file

@ -3,6 +3,7 @@ import time
import pytest
from packaging import version
from unit.applications.lang.python import ApplicationPython
prerequisites = {

View file

@ -1,4 +1,5 @@
from packaging import version
from unit.applications.lang.python import ApplicationPython
prerequisites = {

View file

@ -1,7 +1,8 @@
import os
from pathlib import Path
from packaging import version
from conftest import unit_stop
from packaging import version
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():

View file

@ -1,5 +1,6 @@
import pytest
from packaging import version
from unit.applications.lang.python import ApplicationPython
from unit.option import option

View file

@ -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

View file

@ -1,4 +1,5 @@
import pytest
from unit.applications.lang.python import ApplicationPython
from unit.option import option

View file

@ -1,6 +1,7 @@
import socket
import pytest
from unit.control import Control
prerequisites = {'modules': {'python': 'any'}}

View file

@ -1,4 +1,5 @@
import pytest
from unit.applications.lang.python import ApplicationPython
prerequisites = {'modules': {'python': 'any'}}

View file

@ -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'

View file

@ -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')

View file

@ -1,4 +1,5 @@
import pytest
from unit.applications.lang.python import ApplicationPython
prerequisites = {'modules': {'python': 'any'}}

View file

@ -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 = {

View file

@ -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:

View file

@ -2,6 +2,7 @@ import struct
import time
import pytest
from unit.applications.lang.java import ApplicationJava
from unit.applications.websockets import ApplicationWebsocket

View file

@ -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])

View file

@ -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')

View file

@ -1,4 +1,5 @@
from packaging import version
from unit.applications.lang.node import ApplicationNode
from unit.applications.websockets import ApplicationWebsocket

View file

@ -2,6 +2,7 @@ import struct
import time
import pytest
from unit.applications.lang.node import ApplicationNode
from unit.applications.websockets import ApplicationWebsocket

View file

@ -1,6 +1,7 @@
import re
import pytest
from unit.applications.lang.perl import ApplicationPerl
prerequisites = {'modules': {'perl': 'all'}}

View file

@ -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(

View file

@ -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

View file

@ -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'

View file

@ -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(

View file

@ -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()

View file

@ -4,6 +4,7 @@ import subprocess
import time
import pytest
from unit.applications.lang.python import ApplicationPython
from unit.option import option

View file

@ -1,6 +1,7 @@
import time
import pytest
from unit.applications.proto import ApplicationProto
client = ApplicationProto()

View file

@ -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:

View file

@ -3,6 +3,7 @@ import subprocess
import time
import pytest
from unit.applications.lang.python import ApplicationPython
prerequisites = {'modules': {'python': 'any'}}

View file

@ -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(
{

View file

@ -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"

View file

@ -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

View file

@ -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']

View file

@ -2,6 +2,7 @@ import re
import subprocess
import pytest
from unit.applications.lang.ruby import ApplicationRuby
prerequisites = {'modules': {'ruby': 'all'}}

View file

@ -4,6 +4,7 @@ import subprocess
import time
import pytest
from unit.applications.lang.python import ApplicationPython
prerequisites = {'modules': {'python': 'any'}}

View file

@ -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'

View file

@ -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):

View file

@ -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)

View file

@ -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(

View file

@ -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(
{

View file

@ -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(
{

View file

@ -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(
{

View file

@ -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(
{

View file

@ -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"""
)
basicConstraints = critical,CA:TRUE""",
encoding='utf-8',
)
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('')
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(

View file

@ -1,6 +1,7 @@
import ssl
import pytest
from unit.applications.tls import ApplicationTLS
prerequisites = {'modules': {'openssl': 'any'}}

View file

@ -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('')

View file

@ -2,6 +2,7 @@ import os
import re
import pytest
from unit.applications.lang.python import ApplicationPython
from unit.option import option

View file

@ -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)

View file

@ -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'

View file

@ -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

View file

@ -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}'

View file

@ -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}'

View file

@ -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

View file

@ -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

View file

@ -1,4 +1,5 @@
import pytest
from unit.option import option

View file

@ -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)

View file

@ -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:

View file

@ -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

View file

@ -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'

View file

@ -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