diff options
Diffstat (limited to 'test')
142 files changed, 967 insertions, 688 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/go/404/app.go b/test/go/404/app.go index 7eba2cf4..255f5dac 100644 --- a/test/go/404/app.go +++ b/test/go/404/app.go @@ -18,5 +18,5 @@ func handler(w http.ResponseWriter, r *http.Request) { func main() { http.HandleFunc("/", handler) - unit.ListenAndServe(":7080", nil) + unit.ListenAndServe(":8080", nil) } diff --git a/test/go/command_line_arguments/app.go b/test/go/command_line_arguments/app.go index 1101e1cf..5da12ffe 100644 --- a/test/go/command_line_arguments/app.go +++ b/test/go/command_line_arguments/app.go @@ -19,5 +19,5 @@ func handler(w http.ResponseWriter, r *http.Request) { func main() { http.HandleFunc("/", handler) - unit.ListenAndServe(":7080", nil) + unit.ListenAndServe(":8080", nil) } diff --git a/test/go/cookies/app.go b/test/go/cookies/app.go index 2216e153..49779d35 100644 --- a/test/go/cookies/app.go +++ b/test/go/cookies/app.go @@ -15,5 +15,5 @@ func handler(w http.ResponseWriter, r *http.Request) { func main() { http.HandleFunc("/", handler) - unit.ListenAndServe(":7080", nil) + unit.ListenAndServe(":8080", nil) } diff --git a/test/go/empty/app.go b/test/go/empty/app.go index 9326a19b..61e27f67 100644 --- a/test/go/empty/app.go +++ b/test/go/empty/app.go @@ -9,5 +9,5 @@ func handler(w http.ResponseWriter, r *http.Request) {} func main() { http.HandleFunc("/", handler) - unit.ListenAndServe(":7080", nil) + unit.ListenAndServe(":8080", nil) } diff --git a/test/go/get_variables/app.go b/test/go/get_variables/app.go index 1c0205a8..d70669f2 100644 --- a/test/go/get_variables/app.go +++ b/test/go/get_variables/app.go @@ -13,5 +13,5 @@ func handler(w http.ResponseWriter, r *http.Request) { func main() { http.HandleFunc("/", handler) - unit.ListenAndServe(":7080", nil) + unit.ListenAndServe(":8080", nil) } diff --git a/test/go/mirror/app.go b/test/go/mirror/app.go index 78f047c3..daf55df8 100644 --- a/test/go/mirror/app.go +++ b/test/go/mirror/app.go @@ -17,5 +17,5 @@ func handler(w http.ResponseWriter, r *http.Request) { func main() { http.HandleFunc("/", handler) - unit.ListenAndServe(":7080", nil) + unit.ListenAndServe(":8080", nil) } diff --git a/test/go/ns_inspect/app.go b/test/go/ns_inspect/app.go index 570580e6..977f0d9c 100644 --- a/test/go/ns_inspect/app.go +++ b/test/go/ns_inspect/app.go @@ -97,5 +97,5 @@ func handler(w http.ResponseWriter, r *http.Request) { func main() { http.HandleFunc("/", handler) - unit.ListenAndServe(":7080", nil) + unit.ListenAndServe(":8080", nil) } diff --git a/test/go/post_variables/app.go b/test/go/post_variables/app.go index e6279ac6..06900d4c 100644 --- a/test/go/post_variables/app.go +++ b/test/go/post_variables/app.go @@ -15,5 +15,5 @@ func handler(w http.ResponseWriter, r *http.Request) { func main() { http.HandleFunc("/", handler) - unit.ListenAndServe(":7080", nil) + unit.ListenAndServe(":8080", nil) } diff --git a/test/go/variables/app.go b/test/go/variables/app.go index 4be60cb7..9ef18aae 100644 --- a/test/go/variables/app.go +++ b/test/go/variables/app.go @@ -26,5 +26,5 @@ func handler(w http.ResponseWriter, r *http.Request) { func main() { http.HandleFunc("/", handler) - unit.ListenAndServe(":7080", nil) + unit.ListenAndServe(":8080", nil) } diff --git a/test/node/404/app.js b/test/node/404/app.js index ba15c104..8beec34a 100644 --- a/test/node/404/app.js +++ b/test/node/404/app.js @@ -3,4 +3,4 @@ var fs = require('fs'); require('http').createServer(function (req, res) { res.writeHead(404, {}).end(fs.readFileSync('404.html')); -}).listen(7080); +}).listen(8080); diff --git a/test/node/basic/app.js b/test/node/basic/app.js index 9092022c..2d870003 100644 --- a/test/node/basic/app.js +++ b/test/node/basic/app.js @@ -2,4 +2,4 @@ require('http').createServer(function (req, res) { res.writeHead(200, {'Content-Length': 12, 'Content-Type': 'text/plain'}) .end('Hello World\n'); -}).listen(7080); +}).listen(8080); diff --git a/test/node/double_end/app.js b/test/node/double_end/app.js index 653e33b1..e721db77 100644 --- a/test/node/double_end/app.js +++ b/test/node/double_end/app.js @@ -1,4 +1,4 @@ require('http').createServer(function (req, res) { res.end().end(); -}).listen(7080); +}).listen(8080); diff --git a/test/node/flush_headers/app.js b/test/node/flush_headers/app.js new file mode 100644 index 00000000..4c0e93bc --- /dev/null +++ b/test/node/flush_headers/app.js @@ -0,0 +1,7 @@ + +require('http').createServer(function (req, res) { + res.setHeader('X-Header', 'blah'); + res.flushHeaders(); + res.flushHeaders(); // Should be idempotent. + res.end(); +}).listen(8080); diff --git a/test/node/get_header_names/app.js b/test/node/get_header_names/app.js index a938b762..77aa0327 100644 --- a/test/node/get_header_names/app.js +++ b/test/node/get_header_names/app.js @@ -4,4 +4,4 @@ require('http').createServer(function (req, res) { res.setHeader('X-Header', 'blah'); res.setHeader('X-Names', res.getHeaderNames()); res.end(); -}).listen(7080); +}).listen(8080); diff --git a/test/node/get_header_type/app.js b/test/node/get_header_type/app.js index 6e45b71f..d5a591e8 100644 --- a/test/node/get_header_type/app.js +++ b/test/node/get_header_type/app.js @@ -3,4 +3,4 @@ require('http').createServer(function (req, res) { res.setHeader('X-Number', 100); res.setHeader('X-Type', typeof(res.getHeader('X-Number'))); res.end(); -}).listen(7080); +}).listen(8080); diff --git a/test/node/get_variables/app.js b/test/node/get_variables/app.js index cded43d2..8f317cb4 100644 --- a/test/node/get_variables/app.js +++ b/test/node/get_variables/app.js @@ -5,4 +5,4 @@ require('http').createServer(function (req, res) { res.setHeader('X-Var-2', query.var2); res.setHeader('X-Var-3', query.var3); res.end(); -}).listen(7080); +}).listen(8080); diff --git a/test/node/has_header/app.js b/test/node/has_header/app.js index 04b13916..30e75e4d 100644 --- a/test/node/has_header/app.js +++ b/test/node/has_header/app.js @@ -2,4 +2,4 @@ require('http').createServer(function (req, res) { res.setHeader('X-Has-Header', res.hasHeader(req.headers['x-header']) + ''); res.end(); -}).listen(7080); +}).listen(8080); diff --git a/test/node/header_name_case/app.js b/test/node/header_name_case/app.js index af157547..45acd507 100644 --- a/test/node/header_name_case/app.js +++ b/test/node/header_name_case/app.js @@ -4,4 +4,4 @@ require('http').createServer(function (req, res) { res.setHeader('X-header', '2'); res.setHeader('X-HEADER', '3'); res.end(); -}).listen(7080); +}).listen(8080); diff --git a/test/node/header_name_valid/app.js b/test/node/header_name_valid/app.js index c0c36098..9ac0c3a2 100644 --- a/test/node/header_name_valid/app.js +++ b/test/node/header_name_valid/app.js @@ -3,4 +3,4 @@ require('http').createServer(function (req, res) { res.writeHead(200, {}); res.setHeader('@$', 'test'); res.end(); -}).listen(7080); +}).listen(8080); diff --git a/test/node/header_value_object/app.js b/test/node/header_value_object/app.js index bacdc7d5..6f3d74bc 100644 --- a/test/node/header_value_object/app.js +++ b/test/node/header_value_object/app.js @@ -2,4 +2,4 @@ require('http').createServer(function (req, res) { res.setHeader('X-Header', {}); res.end(); -}).listen(7080); +}).listen(8080); diff --git a/test/node/loader/es_modules_http/app.mjs b/test/node/loader/es_modules_http/app.mjs index c7bcfe49..28ff08d8 100644 --- a/test/node/loader/es_modules_http/app.mjs +++ b/test/node/loader/es_modules_http/app.mjs @@ -3,4 +3,4 @@ import http from "http" http.createServer(function (req, res) { res.writeHead(200, {'Content-Length': 12, 'Content-Type': 'text/plain'}) .end('Hello World\n'); -}).listen(7080); +}).listen(8080); diff --git a/test/node/loader/es_modules_http_indirect/module.mjs b/test/node/loader/es_modules_http_indirect/module.mjs index c7bcfe49..28ff08d8 100644 --- a/test/node/loader/es_modules_http_indirect/module.mjs +++ b/test/node/loader/es_modules_http_indirect/module.mjs @@ -3,4 +3,4 @@ import http from "http" http.createServer(function (req, res) { res.writeHead(200, {'Content-Length': 12, 'Content-Type': 'text/plain'}) .end('Hello World\n'); -}).listen(7080); +}).listen(8080); diff --git a/test/node/loader/es_modules_websocket/app.mjs b/test/node/loader/es_modules_websocket/app.mjs index a71ffa9d..361d855b 100644 --- a/test/node/loader/es_modules_websocket/app.mjs +++ b/test/node/loader/es_modules_websocket/app.mjs @@ -4,7 +4,7 @@ import websocket from "websocket" let server = http.createServer(function() {}); let webSocketServer = websocket.server; -server.listen(7080, function() {}); +server.listen(8080, function() {}); var wsServer = new webSocketServer({ maxReceivedMessageSize: 0x1000000000, diff --git a/test/node/loader/es_modules_websocket_indirect/module.mjs b/test/node/loader/es_modules_websocket_indirect/module.mjs index a71ffa9d..361d855b 100644 --- a/test/node/loader/es_modules_websocket_indirect/module.mjs +++ b/test/node/loader/es_modules_websocket_indirect/module.mjs @@ -4,7 +4,7 @@ import websocket from "websocket" let server = http.createServer(function() {}); let webSocketServer = websocket.server; -server.listen(7080, function() {}); +server.listen(8080, function() {}); var wsServer = new webSocketServer({ maxReceivedMessageSize: 0x1000000000, diff --git a/test/node/loader/transitive_dependency/transitive_http.js b/test/node/loader/transitive_dependency/transitive_http.js index f1eb98e5..171758ed 100644 --- a/test/node/loader/transitive_dependency/transitive_http.js +++ b/test/node/loader/transitive_dependency/transitive_http.js @@ -3,6 +3,6 @@ const http = require("http"); http.createServer(function (req, res) { res.writeHead(200, {'Content-Length': 12, 'Content-Type': 'text/plain'}) .end('Hello World\n'); -}).listen(7080); +}).listen(8080); module.exports = http; diff --git a/test/node/loader/unit_http/app.js b/test/node/loader/unit_http/app.js index 9172e44f..0e0c2b24 100644 --- a/test/node/loader/unit_http/app.js +++ b/test/node/loader/unit_http/app.js @@ -1,4 +1,4 @@ require("unit-http").createServer(function (req, res) { res.writeHead(200, {'Content-Length': 12, 'Content-Type': 'text/plain'}) .end('Hello World\n'); -}).listen(7080); +}).listen(8080); diff --git a/test/node/mirror/app.js b/test/node/mirror/app.js index bdefe1cd..bdb89489 100644 --- a/test/node/mirror/app.js +++ b/test/node/mirror/app.js @@ -8,4 +8,4 @@ require('http').createServer(function (req, res) { res.writeHead(200, {'Content-Length': Buffer.byteLength(body)}) .end(body); }); -}).listen(7080); +}).listen(8080); diff --git a/test/node/options/app.js b/test/node/options/app.js new file mode 100644 index 00000000..bc538080 --- /dev/null +++ b/test/node/options/app.js @@ -0,0 +1,4 @@ +require('http').createServer({}, function (req, res) { + res.writeHead(200, {'Content-Length': 12, 'Content-Type': 'text/plain'}) + .end('Hello World\n'); +}).listen(8080); diff --git a/test/node/post_variables/app.js b/test/node/post_variables/app.js index 12b867cb..4d88434d 100644 --- a/test/node/post_variables/app.js +++ b/test/node/post_variables/app.js @@ -11,4 +11,4 @@ require('http').createServer(function (req, res) { res.setHeader('X-Var-3', query.var3); res.end(); }); -}).listen(7080); +}).listen(8080); diff --git a/test/node/promise_end/app.js b/test/node/promise_end/app.js index 373c3bc6..75c2ef7d 100644 --- a/test/node/promise_end/app.js +++ b/test/node/promise_end/app.js @@ -12,4 +12,4 @@ require('http').createServer(function (req, res) { fs.appendFile('callback', '', function() {}); }); -}).listen(7080); +}).listen(8080); diff --git a/test/node/promise_handler/app.js b/test/node/promise_handler/app.js index 32d7d7b9..7bcb1ae9 100644 --- a/test/node/promise_handler/app.js +++ b/test/node/promise_handler/app.js @@ -13,4 +13,4 @@ require('http').createServer(function (req, res) { fs.appendFile(data.toString(), '', function() {}); }); }); -}).listen(7080); +}).listen(8080); diff --git a/test/node/remove_header/app.js b/test/node/remove_header/app.js index 2a591235..877a7351 100644 --- a/test/node/remove_header/app.js +++ b/test/node/remove_header/app.js @@ -7,4 +7,4 @@ require('http').createServer(function (req, res) { res.setHeader('Has-Header', res.hasHeader('X-Header').toString()); res.end(); -}).listen(7080); +}).listen(8080); diff --git a/test/node/set_header_array/app.js b/test/node/set_header_array/app.js index 965330e2..0dee477e 100644 --- a/test/node/set_header_array/app.js +++ b/test/node/set_header_array/app.js @@ -2,4 +2,4 @@ require('http').createServer(function (req, res) { res.setHeader('Set-Cookie', ['tc=one,two,three', 'tc=four,five,six']); res.end(); -}).listen(7080); +}).listen(8080); diff --git a/test/node/status_message/app.js b/test/node/status_message/app.js index ba51d35b..53eea5c7 100644 --- a/test/node/status_message/app.js +++ b/test/node/status_message/app.js @@ -1,4 +1,4 @@ require('http').createServer(function (req, res) { res.writeHead(200, 'blah', {'Content-Type': 'text/plain'}).end(); -}).listen(7080); +}).listen(8080); diff --git a/test/node/update_header/app.js b/test/node/update_header/app.js index 905ac294..dc3415e6 100644 --- a/test/node/update_header/app.js +++ b/test/node/update_header/app.js @@ -3,4 +3,4 @@ require('http').createServer(function (req, res) { res.setHeader('X-Header', 'test'); res.setHeader('X-Header', 'new'); res.end(); -}).listen(7080); +}).listen(8080); diff --git a/test/node/variables/app.js b/test/node/variables/app.js index a569dddd..b6f36f37 100644 --- a/test/node/variables/app.js +++ b/test/node/variables/app.js @@ -15,4 +15,4 @@ require('http').createServer(function (req, res) { res.setHeader('Http-Host', req.headers['host']); res.writeHead(200, {}).end(body); }); -}).listen(7080); +}).listen(8080); diff --git a/test/node/websockets/mirror/app.js b/test/node/websockets/mirror/app.js index 0443adb2..ee2bdd18 100644 --- a/test/node/websockets/mirror/app.js +++ b/test/node/websockets/mirror/app.js @@ -2,7 +2,7 @@ server = require('http').createServer(function() {}); webSocketServer = require('websocket').server; -server.listen(7080, function() {}); +server.listen(8080, function() {}); var wsServer = new webSocketServer({ maxReceivedMessageSize: 0x1000000000, diff --git a/test/node/websockets/mirror_fragmentation/app.js b/test/node/websockets/mirror_fragmentation/app.js index ea580ac2..ca539ad6 100644 --- a/test/node/websockets/mirror_fragmentation/app.js +++ b/test/node/websockets/mirror_fragmentation/app.js @@ -2,7 +2,7 @@ server = require('http').createServer(function() {}); webSocketServer = require('websocket').server; -server.listen(7080, function() {}); +server.listen(8080, function() {}); var wsServer = new webSocketServer({ httpServer: server diff --git a/test/node/write_array/app.js b/test/node/write_array/app.js index b7abb3fc..761e8537 100644 --- a/test/node/write_array/app.js +++ b/test/node/write_array/app.js @@ -1,4 +1,4 @@ require('http').createServer(function (req, res) { res.writeHead(200, {'Content-Length': 5, 'Content-Type': 'text/plain'}) .end(new Uint8Array(Buffer.from('array', 'utf8'))); -}).listen(7080); +}).listen(8080); diff --git a/test/node/write_before_write_head/app.js b/test/node/write_before_write_head/app.js index 2293111a..10c8b9d6 100644 --- a/test/node/write_before_write_head/app.js +++ b/test/node/write_before_write_head/app.js @@ -2,4 +2,4 @@ require('http').createServer(function (req, res) { res.write('blah'); res.writeHead(200, {'Content-Type': 'text/plain'}).end(); -}).listen(7080); +}).listen(8080); diff --git a/test/node/write_buffer/app.js b/test/node/write_buffer/app.js index 72e9c600..24585ef2 100644 --- a/test/node/write_buffer/app.js +++ b/test/node/write_buffer/app.js @@ -2,4 +2,4 @@ require('http').createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}) .end(Buffer.from('buffer', 'utf8')); -}).listen(7080); +}).listen(8080); diff --git a/test/node/write_callback/app.js b/test/node/write_callback/app.js index 71eb4116..f03cb213 100644 --- a/test/node/write_callback/app.js +++ b/test/node/write_callback/app.js @@ -9,4 +9,4 @@ require('http').createServer(function (req, res) { fs.appendFile('callback', '', function() {}); }); res.end(a); -}).listen(7080); +}).listen(8080); diff --git a/test/node/write_multiple/app.js b/test/node/write_multiple/app.js index e9c51ae0..b1e485e7 100644 --- a/test/node/write_multiple/app.js +++ b/test/node/write_multiple/app.js @@ -4,4 +4,4 @@ require('http').createServer(function (req, res) { res.write('write'); res.write('write2'); res.end('end'); -}).listen(7080); +}).listen(8080); diff --git a/test/node/write_return/app.js b/test/node/write_return/app.js index 345b6c4b..d0b3d850 100644 --- a/test/node/write_return/app.js +++ b/test/node/write_return/app.js @@ -2,4 +2,4 @@ require('http').createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}) .end(res.write('body').toString()); -}).listen(7080); +}).listen(8080); diff --git a/test/python/body_bytearray/asgi.py b/test/python/body_bytearray/asgi.py new file mode 100644 index 00000000..6d2f402f --- /dev/null +++ b/test/python/body_bytearray/asgi.py @@ -0,0 +1,20 @@ +async def application(scope, receive, send): + assert scope['type'] == 'http' + + body = b'' + while True: + m = await receive() + body += m.get('body', b'') + if not m.get('more_body', False): + body = bytearray(body) + break + + await send( + { + 'type': 'http.response.start', + 'status': 200, + 'headers': [(b'content-length', str(len(body)).encode())], + } + ) + + await send({'type': 'http.response.body', 'body': body}) 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/ruby/header_array/config.ru b/test/ruby/header_array/config.ru new file mode 100644 index 00000000..6401ab4b --- /dev/null +++ b/test/ruby/header_array/config.ru @@ -0,0 +1,7 @@ +app = Proc.new do |env| + ['200', { + 'x-array' => ['name=value', '', 'value', 'av'], + }, []] +end + +run app diff --git a/test/ruby/header_array_empty/config.ru b/test/ruby/header_array_empty/config.ru new file mode 100644 index 00000000..df40ffdd --- /dev/null +++ b/test/ruby/header_array_empty/config.ru @@ -0,0 +1,7 @@ +app = Proc.new do |env| + ['200', { + 'x-array' => [], + }, []] +end + +run app diff --git a/test/ruby/header_array_nil/config.ru b/test/ruby/header_array_nil/config.ru new file mode 100644 index 00000000..04550c8d --- /dev/null +++ b/test/ruby/header_array_nil/config.ru @@ -0,0 +1,7 @@ +app = Proc.new do |env| + ['200', { + 'x-array' => [nil], + }, []] +end + +run app diff --git a/test/ruby/input_rewind/config.ru b/test/ruby/input_rewind/config.ru deleted file mode 100644 index fc0d6535..00000000 --- a/test/ruby/input_rewind/config.ru +++ /dev/null @@ -1,8 +0,0 @@ -app = Proc.new do |env| - env['rack.input'].read - env['rack.input'].rewind - body = env['rack.input'].read - ['200', {'Content-Length' => body.length.to_s}, [body]] -end - -run app diff --git a/test/ruby/multipart/config.ru b/test/ruby/multipart/config.ru new file mode 100644 index 00000000..9187997c --- /dev/null +++ b/test/ruby/multipart/config.ru @@ -0,0 +1,7 @@ +app = Proc.new do |env| + [200, { + 'x-multipart-buffer' => env['rack.multipart.buffer_size'].to_s + }, []] +end + +run app diff --git a/test/ruby/session/config.ru b/test/ruby/session/config.ru new file mode 100644 index 00000000..8cea0588 --- /dev/null +++ b/test/ruby/session/config.ru @@ -0,0 +1,6 @@ +app = Proc.new do |env| + env['rack.session'].clear + [200, {}, []] +end + +run app diff --git a/test/test_access_log.py b/test/test_access_log.py index bccea56f..1b0ec8ad 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,16 +18,20 @@ 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' +def set_if(condition): + assert 'success' in client.conf(f'"{condition}"', 'access_log/if') + + def test_access_log_keepalive(wait_for_record): load('mirror') @@ -93,7 +98,7 @@ def test_access_log_ipv6(wait_for_record): load('empty') assert 'success' in client.conf( - {"[::1]:7080": {"pass": "applications/empty"}}, 'listeners' + {"[::1]:8080": {"pass": "applications/empty"}}, 'listeners' ) client.get(sock_type='ipv6') @@ -283,14 +288,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') @@ -307,6 +312,62 @@ def test_access_log_variables(wait_for_record): ), '$body_bytes_sent' +def test_access_log_if(search_in_file, wait_for_record): + load('empty') + set_format('$uri') + + def try_if(condition): + set_if(condition) + assert client.get(url=f'/{condition}')['status'] == 200 + + # const + + try_if('') + try_if('0') + try_if('false') + try_if('undefined') + try_if('!') + try_if('!null') + try_if('1') + + # variable + + set_if('$arg_foo') + assert client.get(url='/bar?bar')['status'] == 200 + assert client.get(url='/foo_empty?foo')['status'] == 200 + assert client.get(url='/foo?foo=1')['status'] == 200 + + # check results + + assert wait_for_record(r'^/foo$', 'access.log') is not None + + assert search_in_file(r'^/$', 'access.log') is None + assert search_in_file(r'^/0$', 'access.log') is None + assert search_in_file(r'^/false$', 'access.log') is None + assert search_in_file(r'^/undefined$', 'access.log') is None + assert search_in_file(r'^/!$', 'access.log') is not None + assert search_in_file(r'^/!null$', 'access.log') is not None + assert search_in_file(r'^/1$', 'access.log') is not None + + assert search_in_file(r'^/bar$', 'access.log') is None + assert search_in_file(r'^/foo_empty$', 'access.log') is None + + +def test_access_log_if_njs(require, search_in_file, wait_for_record): + require({'modules': {'njs': 'any'}}) + + load('empty') + set_format('$uri') + + set_if('`${args.foo == \'1\'}`') + + assert client.get(url='/foo_2?foo=2')['status'] == 200 + assert client.get(url='/foo_1?foo=1')['status'] == 200 + + assert wait_for_record(r'^/foo_1$', 'access.log') is not None + assert search_in_file(r'^/foo_2$', 'access.log') is None + + def test_access_log_incorrect(temp_dir, skip_alert): skip_alert(r'failed to apply new conf') @@ -322,3 +383,5 @@ def test_access_log_incorrect(temp_dir, skip_alert): }, 'access_log', ), 'access_log format incorrect' + + assert 'error' in client.conf('$arg_', 'access_log/if') diff --git a/test/test_asgi_application.py b/test/test_asgi_application.py index 98d4bcd5..226a1ed7 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 = { @@ -60,7 +61,7 @@ def test_asgi_application_ipv6(): client.load('empty') assert 'success' in client.conf( - {"[::1]:7080": {"pass": "applications/empty"}}, 'listeners' + {"[::1]:8080": {"pass": "applications/empty"}}, 'listeners' ) assert client.get(sock_type='ipv6')['status'] == 200 @@ -172,7 +173,7 @@ def test_asgi_application_server_port(): client.load('server_port') assert ( - client.get()['headers']['Server-Port'] == '7080' + client.get()['headers']['Server-Port'] == '8080' ), 'Server-Port header' @@ -217,6 +218,14 @@ def test_asgi_application_shm_ack_handle(): assert resp['body'] == body, 'keep-alive 1' +def test_asgi_application_body_bytearray(): + client.load('body_bytearray') + + body = '0123456789' + + assert client.post(body=body)['body'] == body + + def test_asgi_keepalive_body(): client.load('mirror') 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 499f523d..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(): @@ -59,7 +54,7 @@ def test_asgi_lifespan_targets(): assert 'success' in client.conf( { - "listeners": {"*:7080": {"pass": "routes"}}, + "listeners": {"*:8080": {"pass": "routes"}}, "routes": [ { "match": {"uri": "/1"}, diff --git a/test/test_asgi_targets.py b/test/test_asgi_targets.py index c3ec22f0..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 @@ -16,7 +17,7 @@ def setup_method_fixture(): assert 'success' in client.conf( { - "listeners": {"*:7080": {"pass": "routes"}}, + "listeners": {"*:8080": {"pass": "routes"}}, "routes": [ { "match": {"uri": "/1"}, 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 82c76718..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 @@ -15,11 +16,11 @@ def setup_method_fixture(): def client_ip(options): assert 'success' in client.conf( { - "127.0.0.1:7081": { + "127.0.0.1:8081": { "client_ip": options, "pass": "applications/client_ip", }, - "[::1]:7082": { + "[::1]:8082": { "client_ip": options, "pass": "applications/client_ip", }, @@ -34,8 +35,8 @@ def client_ip(options): def get_xff(xff, sock_type='ipv4'): address = { - 'ipv4': ('127.0.0.1', 7081), - 'ipv6': ('::1', 7082), + 'ipv4': ('127.0.0.1', 8081), + 'ipv6': ('::1', 8082), 'unix': (f'{option.temp_dir}/sock', None), } (addr, port) = address[sock_type] @@ -51,9 +52,9 @@ def get_xff(xff, sock_type='ipv4'): def test_client_ip_single_ip(): client_ip({'header': 'X-Forwarded-For', 'source': '123.123.123.123'}) - assert client.get(port=7081)['body'] == '127.0.0.1', 'ipv4 default' + assert client.get(port=8081)['body'] == '127.0.0.1', 'ipv4 default' assert ( - client.get(sock_type='ipv6', port=7082)['body'] == '::1' + client.get(sock_type='ipv6', port=8082)['body'] == '::1' ), 'ipv6 default' assert get_xff('1.1.1.1') == '127.0.0.1', 'bad source' assert get_xff('blah') == '127.0.0.1', 'bad header' @@ -61,9 +62,9 @@ def test_client_ip_single_ip(): client_ip({'header': 'X-Forwarded-For', 'source': '127.0.0.1'}) - assert client.get(port=7081)['body'] == '127.0.0.1', 'ipv4 default 2' + assert client.get(port=8081)['body'] == '127.0.0.1', 'ipv4 default 2' assert ( - client.get(sock_type='ipv6', port=7082)['body'] == '::1' + client.get(sock_type='ipv6', port=8082)['body'] == '::1' ), 'ipv6 default 2' assert get_xff('1.1.1.1') == '1.1.1.1', 'replace' assert get_xff('blah') == '127.0.0.1', 'bad header 2' @@ -159,7 +160,7 @@ def test_client_ip_empty_source(): def test_client_ip_invalid(): assert 'error' in client.conf( { - "127.0.0.1:7081": { + "127.0.0.1:8081": { "client_ip": {"source": '127.0.0.1'}, "pass": "applications/client_ip", } @@ -170,7 +171,7 @@ def test_client_ip_invalid(): def check_invalid_source(source): assert 'error' in client.conf( { - "127.0.0.1:7081": { + "127.0.0.1:8081": { "client_ip": { "header": "X-Forwarded-For", "source": source, diff --git a/test/test_configuration.py b/test/test_configuration.py index 19a2a1a5..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'}} @@ -234,12 +235,12 @@ def test_applications_relative_path(): @pytest.mark.skip('not yet, unsafe') def test_listeners_empty(): - assert 'error' in client.conf({"*:7080": {}}, 'listeners'), 'listener empty' + assert 'error' in client.conf({"*:8080": {}}, 'listeners'), 'listener empty' def test_listeners_no_app(): assert 'error' in client.conf( - {"*:7080": {"pass": "applications/app"}}, 'listeners' + {"*:8080": {"pass": "applications/app"}}, 'listeners' ), 'listeners no app' @@ -254,9 +255,9 @@ def test_listeners_unix_abstract(system): def test_listeners_addr(): - assert 'success' in try_addr("*:7080"), 'wildcard' - assert 'success' in try_addr("127.0.0.1:7081"), 'explicit' - assert 'success' in try_addr("[::1]:7082"), 'explicit ipv6' + assert 'success' in try_addr("*:8080"), 'wildcard' + assert 'success' in try_addr("127.0.0.1:8081"), 'explicit' + assert 'success' in try_addr("[::1]:8082"), 'explicit ipv6' def test_listeners_addr_error(): @@ -266,7 +267,7 @@ def test_listeners_addr_error(): def test_listeners_addr_error_2(skip_alert): skip_alert(r'bind.*failed', r'failed to apply new conf') - assert 'error' in try_addr("[f607:7403:1e4b:6c66:33b2:843f:2517:da27]:7080") + assert 'error' in try_addr("[f607:7403:1e4b:6c66:33b2:843f:2517:da27]:8080") def test_listeners_port_release(): @@ -277,7 +278,7 @@ def test_listeners_port_release(): client.conf( { - "listeners": {"127.0.0.1:7080": {"pass": "routes"}}, + "listeners": {"127.0.0.1:8080": {"pass": "routes"}}, "routes": [], } ) @@ -285,7 +286,7 @@ def test_listeners_port_release(): resp = client.conf({"listeners": {}, "applications": {}}) try: - s.bind(('127.0.0.1', 7080)) + s.bind(('127.0.0.1', 8080)) s.listen() except OSError: @@ -302,7 +303,7 @@ def test_json_application_name_large(): assert 'success' in client.conf( { - "listeners": {"*:7080": {"pass": f"applications/{name}"}}, + "listeners": {"*:8080": {"pass": f"applications/{name}"}}, "applications": { name: { "type": "python", @@ -349,7 +350,7 @@ def test_json_application_python_prefix(): "prefix": "/app", } }, - "listeners": {"*:7080": {"pass": "routes"}}, + "listeners": {"*:8080": {"pass": "routes"}}, "routes": [ { "match": {"uri": "/app/*"}, @@ -378,7 +379,7 @@ def test_json_application_prefix_target(): }, } }, - "listeners": {"*:7080": {"pass": "routes"}}, + "listeners": {"*:8080": {"pass": "routes"}}, "routes": [ { "match": {"uri": "/app/*"}, @@ -405,7 +406,7 @@ def test_json_application_invalid_python_prefix(): "prefix": "app", } }, - "listeners": {"*:7080": {"pass": "applications/sub-app"}}, + "listeners": {"*:8080": {"pass": "applications/sub-app"}}, } assert 'error' in client.conf(conf) @@ -422,7 +423,7 @@ def test_json_application_empty_python_prefix(): "prefix": "", } }, - "listeners": {"*:7080": {"pass": "applications/sub-app"}}, + "listeners": {"*:8080": {"pass": "applications/sub-app"}}, } assert 'error' in client.conf(conf) @@ -441,7 +442,7 @@ def test_json_application_many2(): # open files limit due to the lack of file descriptors. for a in range(100) }, - "listeners": {"*:7080": {"pass": "applications/app-1"}}, + "listeners": {"*:8080": {"pass": "applications/app-1"}}, } assert 'success' in client.conf(conf) diff --git a/test/test_forwarded_header.py b/test/test_forwarded_header.py index c3f4a4c6..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'}} @@ -14,11 +15,11 @@ def setup_method_fixture(): def forwarded_header(forwarded): assert 'success' in client.conf( { - "127.0.0.1:7081": { + "127.0.0.1:8081": { "forwarded": forwarded, "pass": "applications/forwarded_header", }, - "[::1]:7082": { + "[::1]:8082": { "forwarded": forwarded, "pass": "applications/forwarded_header", }, @@ -28,7 +29,7 @@ def forwarded_header(forwarded): def get_fwd(sock_type='ipv4', xff=None, xfp=None): - port = 7081 if sock_type == 'ipv4' else 7082 + port = 8081 if sock_type == 'ipv4' else 8082 headers = {'Connection': 'close'} @@ -243,7 +244,7 @@ def test_forwarded_header_source_range(): def test_forwarded_header_invalid(): assert 'error' in client.conf( { - "127.0.0.1:7081": { + "127.0.0.1:8081": { "forwarded": {"source": '127.0.0.1'}, "pass": "applications/forwarded_header", } @@ -254,7 +255,7 @@ def test_forwarded_header_invalid(): def check_invalid_source(source): assert 'error' in client.conf( { - "127.0.0.1:7081": { + "127.0.0.1:8081": { "forwarded": { "client_ip": "X-Forwarded-For", "source": source, 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 af836e6f..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'}} @@ -333,7 +334,7 @@ def test_http_header_host_port(): client.load('host') resp = client.get( - headers={'Host': 'exmaple.com:7080', 'Connection': 'close'} + headers={'Host': 'exmaple.com:8080', 'Connection': 'close'} ) assert resp['status'] == 200, 'Host port status' @@ -341,7 +342,7 @@ def test_http_header_host_port(): resp['headers']['X-Server-Name'] == 'exmaple.com' ), 'Host port SERVER_NAME' assert ( - resp['headers']['X-Http-Host'] == 'exmaple.com:7080' + resp['headers']['X-Http-Host'] == 'exmaple.com:8080' ), 'Host port HTTP_HOST' @@ -373,14 +374,14 @@ def test_http_header_host_literal(): def test_http_header_host_literal_ipv6(): client.load('host') - resp = client.get(headers={'Host': '[::1]:7080', 'Connection': 'close'}) + resp = client.get(headers={'Host': '[::1]:8080', 'Connection': 'close'}) assert resp['status'] == 200, 'Host literal ipv6 status' assert ( resp['headers']['X-Server-Name'] == '[::1]' ), 'Host literal ipv6 SERVER_NAME' assert ( - resp['headers']['X-Http-Host'] == '[::1]:7080' + resp['headers']['X-Http-Host'] == '[::1]:8080' ), 'Host literal ipv6 HTTP_HOST' diff --git a/test/test_java_application.py b/test/test_java_application.py index eefc5c79..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 @@ -20,7 +20,7 @@ def test_java_conf_error(temp_dir, skip_alert): ) assert 'error' in client.conf( { - "listeners": {"*:7080": {"pass": "applications/app"}}, + "listeners": {"*:8080": {"pass": "applications/app"}}, "applications": { "app": { "type": client.get_application_type(), @@ -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 162cc0bd..8ef815fd 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 @@ -14,7 +15,7 @@ client = ApplicationProto() def setup_method_fixture(temp_dir): assert 'success' in client.conf( { - "listeners": {"*:7080": {"pass": "routes"}}, + "listeners": {"*:8080": {"pass": "routes"}}, "routes": [{"action": {"share": f"{temp_dir}/assets$uri"}}], } ) @@ -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(exist_ok=True) - [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]) @@ -82,6 +83,38 @@ def test_njs_variables(temp_dir): set_share(f'"`{temp_dir}/assets/${{args.foo}}`"') assert client.get(url='/?foo=str')['status'] == 200, 'args' + check_expression('/${vars.header_host}') + + set_share(f'"`{temp_dir}/assets/${{vars[\\"arg_foo\\"]}}`"') + assert client.get(url='/?foo=str')['status'] == 200, 'vars' + + set_share(f'"`{temp_dir}/assets/${{vars.non_exist}}`"') + assert client.get()['status'] == 404, 'undefined' + + create_files('undefined') + assert client.get()['status'] == 200, 'undefined 2' + + +def test_njs_variables_cacheable(temp_dir): + create_files('str') + + def check_rewrite(rewrite, uri): + assert 'success' in client.conf( + [ + { + "action": { + "rewrite": rewrite, + "share": f"`{temp_dir}/assets{uri}`", + }, + }, + ], + 'routes', + ) + assert client.get()['status'] == 200 + + check_rewrite('/str', '${uri}') + check_rewrite('/str', '${vars.uri}') + def test_njs_invalid(skip_alert): skip_alert(r'js exception:') @@ -92,6 +125,7 @@ def test_njs_invalid(skip_alert): check_invalid('"`a"') check_invalid('"`a``"') check_invalid('"`a`/"') + check_invalid('"`${vars.}`"') def check_invalid_resolve(template): assert 'success' in client.conf(template, 'routes/0/action/share') @@ -99,3 +133,4 @@ def test_njs_invalid(skip_alert): check_invalid_resolve('"`${a}`"') check_invalid_resolve('"`${uri.a.a}`"') + check_invalid_resolve('"`${vars.a.a}`"') diff --git a/test/test_njs_modules.py b/test/test_njs_modules.py index d821d455..a639fabd 100644 --- a/test/test_njs_modules.py +++ b/test/test_njs_modules.py @@ -23,7 +23,7 @@ def test_njs_modules(): assert 'success' in client.conf( { "settings": {"js_module": "next"}, - "listeners": {"*:7080": {"pass": "routes/first"}}, + "listeners": {"*:8080": {"pass": "routes/first"}}, "routes": { "first": [{"action": {"pass": "`routes/${next.route()}`"}}], "next": [{"action": {"return": 200}}], @@ -68,7 +68,7 @@ def test_njs_modules_import(): assert 'success' in client.conf( { "settings": {"js_module": "import_from"}, - "listeners": {"*:7080": {"pass": "routes/first"}}, + "listeners": {"*:8080": {"pass": "routes/first"}}, "routes": { "first": [ {"action": {"pass": "`routes/${import_from.num()}`"}} @@ -86,7 +86,7 @@ def test_njs_modules_this(): assert 'success' in client.conf( { "settings": {"js_module": "global_this"}, - "listeners": {"*:7080": {"pass": "routes/first"}}, + "listeners": {"*:8080": {"pass": "routes/first"}}, "routes": { "first": [ {"action": {"pass": "`routes/${global_this.str()}`"}} diff --git a/test/test_node_application.py b/test/test_node_application.py index ab8aa8f8..88ae3136 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 @@ -20,6 +21,12 @@ def test_node_application_basic(): assert_basic_application() +def test_node_application_options(wait_for_record): + client.load('options') + + assert_basic_application() + assert wait_for_record(r'constructor was called with unsupported') is not None + def test_node_application_loader_unit_http(): client.load('loader/unit_http') @@ -79,7 +86,7 @@ def test_node_application_variables(date_to_sec_epoch, sec_epoch): 'Request-Method': 'POST', 'Request-Uri': '/', 'Http-Host': 'localhost', - 'Server-Protocol': 'HTTP/1.1', + 'Server-Protocol': '1.1', 'Custom-Header': 'blah', }, 'headers' assert resp['body'] == body, 'body' @@ -149,11 +156,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') @@ -304,6 +313,12 @@ def test_node_application_get_header_names(): ], '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 7e6571fb..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'}} @@ -88,7 +89,7 @@ def test_perl_application_server_port(): client.load('server_port') assert ( - client.get()['headers']['Server-Port'] == '7080' + client.get()['headers']['Server-Port'] == '8080' ), 'Server-Port header' diff --git a/test/test_php_application.py b/test/test_php_application.py index 17440909..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"}, @@ -174,7 +175,7 @@ def test_php_application_query_string_empty(): def test_php_application_query_string_rewrite(): assert 'success' in client.conf( { - "listeners": {"*:7080": {"pass": "routes"}}, + "listeners": {"*:8080": {"pass": "routes"}}, "routes": [ { "action": { @@ -678,7 +679,7 @@ def test_php_application_error_log(findall, wait_for_record): def test_php_application_script(): assert 'success' in client.conf( { - "listeners": {"*:7080": {"pass": "applications/script"}}, + "listeners": {"*:8080": {"pass": "applications/script"}}, "applications": { "script": { "type": client.get_application_type(), @@ -699,7 +700,7 @@ def test_php_application_script(): def test_php_application_index_default(): assert 'success' in client.conf( { - "listeners": {"*:7080": {"pass": "applications/phpinfo"}}, + "listeners": {"*:8080": {"pass": "applications/phpinfo"}}, "applications": { "phpinfo": { "type": client.get_application_type(), @@ -718,16 +719,18 @@ 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' assert 'success' in client.conf( { "listeners": { - "*:7080": {"pass": "applications/php-path"}, + "*:8080": {"pass": "applications/php-path"}, f'unix:{addr}': {"pass": "applications/php-path"}, }, "applications": { @@ -745,7 +748,7 @@ def test_php_application_trailing_slash(temp_dir): resp = client.get(url='/path?q=a') assert resp['status'] == 301, 'uri without trailing /' assert ( - resp['headers']['Location'] == 'http://localhost:7080/path/?q=a' + resp['headers']['Location'] == 'http://localhost:8080/path/?q=a' ), 'Location with query string' resp = client.get( @@ -761,13 +764,11 @@ 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( { - "listeners": {"*:7080": {"pass": "applications/php-path"}}, + "listeners": {"*:8080": {"pass": "applications/php-path"}}, "applications": { "php-path": { "type": client.get_application_type(), @@ -787,12 +788,12 @@ 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( { - "listeners": {"*:7080": {"pass": "applications/phpinfo"}}, + "listeners": {"*:8080": {"pass": "applications/phpinfo"}}, "applications": { "phpinfo": { "type": client.get_application_type(), diff --git a/test/test_php_basic.py b/test/test_php_basic.py index 64754961..076b7498 100644 --- a/test/test_php_basic.py +++ b/test/test_php_basic.py @@ -14,7 +14,7 @@ conf_app = { } conf_basic = { - "listeners": {"*:7080": {"pass": "applications/app"}}, + "listeners": {"*:8080": {"pass": "applications/app"}}, "applications": conf_app, } @@ -60,14 +60,14 @@ def test_php_get_listeners(): assert 'success' in client.conf(conf_basic) assert client.conf_get()['listeners'] == { - "*:7080": {"pass": "applications/app"} + "*:8080": {"pass": "applications/app"} }, 'listeners' assert client.conf_get('listeners') == { - "*:7080": {"pass": "applications/app"} + "*:8080": {"pass": "applications/app"} }, 'listeners prefix' - assert client.conf_get('listeners/*:7080') == { + assert client.conf_get('listeners/*:8080') == { "pass": "applications/app" }, 'listeners prefix 2' @@ -75,23 +75,23 @@ def test_php_get_listeners(): def test_php_change_listener(): assert 'success' in client.conf(conf_basic) assert 'success' in client.conf( - {"*:7081": {"pass": "applications/app"}}, 'listeners' + {"*:8081": {"pass": "applications/app"}}, 'listeners' ) assert client.conf_get('listeners') == { - "*:7081": {"pass": "applications/app"} + "*:8081": {"pass": "applications/app"} }, 'change listener' def test_php_add_listener(): assert 'success' in client.conf(conf_basic) assert 'success' in client.conf( - {"pass": "applications/app"}, 'listeners/*:7082' + {"pass": "applications/app"}, 'listeners/*:8082' ) assert client.conf_get('listeners') == { - "*:7080": {"pass": "applications/app"}, - "*:7082": {"pass": "applications/app"}, + "*:8080": {"pass": "applications/app"}, + "*:8082": {"pass": "applications/app"}, }, 'add listener' @@ -113,7 +113,7 @@ def test_php_delete(): assert 'success' in client.conf(conf_basic) assert 'error' in client.conf_delete('applications/app') - assert 'success' in client.conf_delete('listeners/*:7080') + assert 'success' in client.conf_delete('listeners/*:8080') assert 'success' in client.conf_delete('applications/app') assert 'error' in client.conf_delete('applications/app') @@ -126,5 +126,5 @@ def test_php_delete_blocks(): assert 'success' in client.conf(conf_app, 'applications') assert 'success' in client.conf( - {"*:7081": {"pass": "applications/app"}}, 'listeners' + {"*:8081": {"pass": "applications/app"}}, 'listeners' ), 'applications restore' diff --git a/test/test_php_targets.py b/test/test_php_targets.py index 857a2dc8..6085db40 100644 --- a/test/test_php_targets.py +++ b/test/test_php_targets.py @@ -10,7 +10,7 @@ def test_php_application_targets(): targets_dir = f"{option.test_dir}/php/targets" assert 'success' in client.conf( { - "listeners": {"*:7080": {"pass": "routes"}}, + "listeners": {"*:8080": {"pass": "routes"}}, "routes": [ { "match": {"uri": "/1"}, @@ -65,7 +65,7 @@ def test_php_application_targets(): def test_php_application_targets_error(): assert 'success' in client.conf( { - "listeners": {"*:7080": {"pass": "applications/targets/default"}}, + "listeners": {"*:8080": {"pass": "applications/targets/default"}}, "applications": { "targets": { "type": client.get_application_type(), @@ -83,7 +83,7 @@ def test_php_application_targets_error(): assert client.get()['status'] == 200 assert 'error' in client.conf( - {"pass": "applications/targets/blah"}, 'listeners/*:7080' + {"pass": "applications/targets/blah"}, 'listeners/*:8080' ), 'invalid targets pass' assert 'error' in client.conf( f'"{option.test_dir}/php/targets"', diff --git a/test/test_python_procman.py b/test/test_procman.py index 4643a9b8..b4378c4f 100644 --- a/test/test_python_procman.py +++ b/test/test_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_proxy.py b/test/test_proxy.py index 207e90e7..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 @@ -23,10 +24,10 @@ def setup_method_fixture(): assert 'success' in client.conf( { "listeners": { - "*:7080": {"pass": "routes"}, - "*:7081": {"pass": "applications/mirror"}, + "*:8080": {"pass": "routes"}, + "*:8081": {"pass": "applications/mirror"}, }, - "routes": [{"action": {"proxy": "http://127.0.0.1:7081"}}], + "routes": [{"action": {"proxy": "http://127.0.0.1:8081"}}], "applications": { "mirror": { "type": client.get_application_type(), @@ -110,19 +111,19 @@ def test_proxy_chain(): assert 'success' in client.conf( { "listeners": { - "*:7080": {"pass": "routes/first"}, - "*:7081": {"pass": "routes/second"}, - "*:7082": {"pass": "routes/third"}, - "*:7083": {"pass": "routes/fourth"}, - "*:7084": {"pass": "routes/fifth"}, - "*:7085": {"pass": "applications/mirror"}, + "*:8080": {"pass": "routes/first"}, + "*:8081": {"pass": "routes/second"}, + "*:8082": {"pass": "routes/third"}, + "*:8083": {"pass": "routes/fourth"}, + "*:8084": {"pass": "routes/fifth"}, + "*:8085": {"pass": "applications/mirror"}, }, "routes": { - "first": [{"action": {"proxy": "http://127.0.0.1:7081"}}], - "second": [{"action": {"proxy": "http://127.0.0.1:7082"}}], - "third": [{"action": {"proxy": "http://127.0.0.1:7083"}}], - "fourth": [{"action": {"proxy": "http://127.0.0.1:7084"}}], - "fifth": [{"action": {"proxy": "http://127.0.0.1:7085"}}], + "first": [{"action": {"proxy": "http://127.0.0.1:8081"}}], + "second": [{"action": {"proxy": "http://127.0.0.1:8082"}}], + "third": [{"action": {"proxy": "http://127.0.0.1:8083"}}], + "fourth": [{"action": {"proxy": "http://127.0.0.1:8084"}}], + "fifth": [{"action": {"proxy": "http://127.0.0.1:8085"}}], }, "applications": { "mirror": { @@ -210,7 +211,7 @@ def test_proxy_parallel(): def test_proxy_header(): assert 'success' in client.conf( - {"pass": "applications/custom_header"}, 'listeners/*:7081' + {"pass": "applications/custom_header"}, 'listeners/*:8081' ), 'custom_header configure' header_value = 'blah' @@ -325,7 +326,7 @@ def test_proxy_fragmented_body_close(): def test_proxy_nowhere(): assert 'success' in client.conf( - [{"action": {"proxy": "http://127.0.0.1:7082"}}], 'routes' + [{"action": {"proxy": "http://127.0.0.1:8082"}}], 'routes' ), 'proxy path changed' assert get_http10()['status'] == 502, 'status' @@ -334,14 +335,14 @@ def test_proxy_nowhere(): def test_proxy_ipv6(): assert 'success' in client.conf( { - "*:7080": {"pass": "routes"}, - "[::1]:7081": {'application': 'mirror'}, + "*:8080": {"pass": "routes"}, + "[::1]:8081": {'application': 'mirror'}, }, 'listeners', ), 'add ipv6 listener configure' assert 'success' in client.conf( - [{"action": {"proxy": "http://[::1]:7081"}}], 'routes' + [{"action": {"proxy": "http://[::1]:8081"}}], 'routes' ), 'proxy ipv6 configure' assert get_http10()['status'] == 200, 'status' @@ -352,7 +353,7 @@ def test_proxy_unix(temp_dir): assert 'success' in client.conf( { - "*:7080": {"pass": "routes"}, + "*:8080": {"pass": "routes"}, f'unix:{addr}': {'application': 'mirror'}, }, 'listeners', @@ -367,7 +368,7 @@ def test_proxy_unix(temp_dir): def test_proxy_delayed(): assert 'success' in client.conf( - {"pass": "applications/delayed"}, 'listeners/*:7081' + {"pass": "applications/delayed"}, 'listeners/*:8081' ), 'delayed configure' body = '0123456789' * 1000 @@ -400,7 +401,7 @@ def test_proxy_delayed(): def test_proxy_delayed_close(): assert 'success' in client.conf( - {"pass": "applications/delayed"}, 'listeners/*:7081' + {"pass": "applications/delayed"}, 'listeners/*:8081' ), 'delayed configure' sock = post_http10( @@ -469,11 +470,11 @@ def test_proxy_invalid(): check_proxy('http://127.0.0.1:') check_proxy('http://127.0.0.1:blah') check_proxy('http://127.0.0.1:-1') - check_proxy('http://127.0.0.1:7080b') + check_proxy('http://127.0.0.1:8080b') check_proxy('http://[]') - check_proxy('http://[]:7080') - check_proxy('http://[:]:7080') - check_proxy('http://[::7080') + check_proxy('http://[]:8080') + check_proxy('http://[:]:8080') + check_proxy('http://[::8080') @pytest.mark.skip('not yet') @@ -486,11 +487,11 @@ def test_proxy_loop(skip_alert): assert 'success' in client.conf( { "listeners": { - "*:7080": {"pass": "routes"}, - "*:7081": {"pass": "applications/mirror"}, - "*:7082": {"pass": "routes"}, + "*:8080": {"pass": "routes"}, + "*:8081": {"pass": "applications/mirror"}, + "*:8082": {"pass": "routes"}, }, - "routes": [{"action": {"proxy": "http://127.0.0.1:7082"}}], + "routes": [{"action": {"proxy": "http://127.0.0.1:8082"}}], "applications": { "mirror": { "type": client.get_application_type(), diff --git a/test/test_proxy_chunked.py b/test/test_proxy_chunked.py index a066e1e8..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 @@ -22,7 +23,7 @@ def setup_method_fixture(): assert 'success' in client.conf( { "listeners": { - "*:7080": {"pass": "routes"}, + "*:8080": {"pass": "routes"}, }, "routes": [ {"action": {"proxy": f'http://127.0.0.1:{SERVER_PORT}'}} @@ -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 18473d59..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'}} @@ -160,7 +161,7 @@ def test_python_application_server_port(): client.load('server_port') assert ( - client.get()['headers']['Server-Port'] == '7080' + client.get()['headers']['Server-Port'] == '8080' ), 'Server-Port header' @@ -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_basic.py b/test/test_python_basic.py index 37859c8c..81c768aa 100644 --- a/test/test_python_basic.py +++ b/test/test_python_basic.py @@ -14,7 +14,7 @@ conf_app = { } conf_basic = { - "listeners": {"*:7080": {"pass": "applications/app"}}, + "listeners": {"*:8080": {"pass": "applications/app"}}, "applications": conf_app, } @@ -64,14 +64,14 @@ def test_python_get_listeners(): assert 'success' in client.conf(conf_basic) assert client.conf_get()['listeners'] == { - "*:7080": {"pass": "applications/app"} + "*:8080": {"pass": "applications/app"} }, 'listeners' assert client.conf_get('listeners') == { - "*:7080": {"pass": "applications/app"} + "*:8080": {"pass": "applications/app"} }, 'listeners prefix' - assert client.conf_get('listeners/*:7080') == { + assert client.conf_get('listeners/*:8080') == { "pass": "applications/app" }, 'listeners prefix 2' @@ -79,23 +79,23 @@ def test_python_get_listeners(): def test_python_change_listener(): assert 'success' in client.conf(conf_basic) assert 'success' in client.conf( - {"*:7081": {"pass": "applications/app"}}, 'listeners' + {"*:8081": {"pass": "applications/app"}}, 'listeners' ) assert client.conf_get('listeners') == { - "*:7081": {"pass": "applications/app"} + "*:8081": {"pass": "applications/app"} }, 'change listener' def test_python_add_listener(): assert 'success' in client.conf(conf_basic) assert 'success' in client.conf( - {"pass": "applications/app"}, 'listeners/*:7082' + {"pass": "applications/app"}, 'listeners/*:8082' ) assert client.conf_get('listeners') == { - "*:7080": {"pass": "applications/app"}, - "*:7082": {"pass": "applications/app"}, + "*:8080": {"pass": "applications/app"}, + "*:8082": {"pass": "applications/app"}, }, 'add listener' @@ -117,7 +117,7 @@ def test_python_delete(): assert 'success' in client.conf(conf_basic) assert 'error' in client.conf_delete('applications/app') - assert 'success' in client.conf_delete('listeners/*:7080') + assert 'success' in client.conf_delete('listeners/*:8080') assert 'success' in client.conf_delete('applications/app') assert 'error' in client.conf_delete('applications/app') @@ -130,5 +130,5 @@ def test_python_delete_blocks(): assert 'success' in client.conf(conf_app, 'applications') assert 'success' in client.conf( - {"*:7081": {"pass": "applications/app"}}, 'listeners' + {"*:8081": {"pass": "applications/app"}}, 'listeners' ), 'applications restore' diff --git a/test/test_python_isolation.py b/test/test_python_isolation.py index 260a87a2..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() @@ -151,8 +151,8 @@ def test_python_isolation_cgroup_two(require): assert 'success' in client.conf( { "listeners": { - "*:7080": {"pass": "applications/one"}, - "*:7081": {"pass": "applications/two"}, + "*:8080": {"pass": "applications/one"}, + "*:8081": {"pass": "applications/two"}, }, "applications": { "one": { @@ -193,7 +193,7 @@ def test_python_isolation_cgroup_invalid(require): script_path = f'{option.test_dir}/python/empty' assert 'error' in client.conf( { - "listeners": {"*:7080": {"pass": "applications/empty"}}, + "listeners": {"*:8080": {"pass": "applications/empty"}}, "applications": { "empty": { "type": "python", diff --git a/test/test_python_targets.py b/test/test_python_targets.py index 46e77c19..10f10b70 100644 --- a/test/test_python_targets.py +++ b/test/test_python_targets.py @@ -11,7 +11,7 @@ def test_python_targets(): assert 'success' in client.conf( { - "listeners": {"*:7080": {"pass": "routes"}}, + "listeners": {"*:8080": {"pass": "routes"}}, "routes": [ { "match": {"uri": "/1"}, @@ -56,7 +56,7 @@ def test_python_targets_prefix(): assert 'success' in client.conf( { - "listeners": {"*:7080": {"pass": "routes"}}, + "listeners": {"*:8080": {"pass": "routes"}}, "routes": [ { "match": {"uri": ["/app*"]}, diff --git a/test/test_reconfigure.py b/test/test_reconfigure.py index 53258b41..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() @@ -10,7 +11,7 @@ client = ApplicationProto() def setup_method_fixture(): assert 'success' in client.conf( { - "listeners": {"*:7080": {"pass": "routes"}}, + "listeners": {"*:8080": {"pass": "routes"}}, "routes": [{"action": {"return": 200}}], "applications": {}, } diff --git a/test/test_reconfigure_tls.py b/test/test_reconfigure_tls.py index b473b147..4f7d344a 100644 --- a/test/test_reconfigure_tls.py +++ b/test/test_reconfigure_tls.py @@ -3,7 +3,9 @@ import ssl import time import pytest + from unit.applications.tls import ApplicationTLS +from unit.option import option prerequisites = {'modules': {'openssl': 'any'}} @@ -20,7 +22,7 @@ def setup_method_fixture(): assert 'success' in client.conf( { "listeners": { - "*:7080": { + "*:8080": { "pass": "routes", "tls": {"certificate": "default"}, } @@ -40,7 +42,7 @@ def create_socket(): ssl_sock = ctx.wrap_socket( s, server_hostname='localhost', do_handshake_on_connect=False ) - ssl_sock.connect(('127.0.0.1', 7080)) + ssl_sock.connect(('127.0.0.1', 8080)) return ssl_sock @@ -51,7 +53,7 @@ def clear_conf(): @pytest.mark.skip('not yet') def test_reconfigure_tls_switch(): - assert 'success' in client.conf_delete('listeners/*:7080/tls') + assert 'success' in client.conf_delete('listeners/*:8080/tls') (_, sock) = client.get( headers={'Host': 'localhost', 'Connection': 'keep-alive'}, @@ -61,7 +63,7 @@ def test_reconfigure_tls_switch(): assert 'success' in client.conf( {"pass": "routes", "tls": {"certificate": "default"}}, - 'listeners/*:7080', + 'listeners/*:8080', ) assert client.get(sock=sock)['status'] == 200, 'reconfigure' @@ -69,6 +71,9 @@ def test_reconfigure_tls_switch(): def test_reconfigure_tls(): + if option.configure_flag['asan']: + pytest.skip('not yet, router crash') + ssl_sock = create_socket() ssl_sock.sendall("""GET / HTTP/1.1\r\n""".encode()) @@ -93,6 +98,8 @@ def test_reconfigure_tls_2(): clear_conf() + success = False + try: ssl_sock.do_handshake() except ssl.SSLError: @@ -104,6 +111,9 @@ def test_reconfigure_tls_2(): def test_reconfigure_tls_3(): + if option.configure_flag['asan']: + pytest.skip('not yet, router crash') + ssl_sock = create_socket() ssl_sock.do_handshake() 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 50f47d9a..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,12 +13,12 @@ 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( { "listeners": { - "*:7080": {"pass": "routes"}, + "*:8080": {"pass": "routes"}, }, "routes": [ { @@ -59,7 +60,7 @@ def test_response_last_action(): assert 'success' in client.conf( { "listeners": { - "*:7080": {"pass": "routes/first"}, + "*:8080": {"pass": "routes/first"}, }, "routes": { "first": [ @@ -91,7 +92,7 @@ def test_response_pass(require): assert 'success' in client_python.conf( { "listeners": { - "*:7080": {"pass": "routes"}, + "*:8080": {"pass": "routes"}, }, "routes": [ { @@ -121,7 +122,7 @@ def test_response_pass(require): def test_response_fallback(): assert 'success' in client.conf( { - "listeners": {"*:7080": {"pass": "routes"}}, + "listeners": {"*:8080": {"pass": "routes"}}, "routes": [ { "action": { diff --git a/test/test_return.py b/test/test_return.py index 35525ed5..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() @@ -10,7 +11,7 @@ client = ApplicationProto() def setup_method_fixture(): assert 'success' in client.conf( { - "listeners": {"*:7080": {"pass": "routes"}}, + "listeners": {"*:8080": {"pass": "routes"}}, "routes": [{"action": {"return": 200}}], "applications": {}, } @@ -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 8d81ec49..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() @@ -10,7 +11,7 @@ client = ApplicationProto() def setup_method_fixture(): assert 'success' in client.conf( { - "listeners": {"*:7080": {"pass": "routes"}}, + "listeners": {"*:8080": {"pass": "routes"}}, "routes": [ { "match": {"uri": "/"}, @@ -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 @@ -112,7 +113,7 @@ def test_rewrite_location(): def check_location(rewrite, expect): assert 'success' in client.conf( { - "listeners": {"*:7080": {"pass": "routes"}}, + "listeners": {"*:8080": {"pass": "routes"}}, "routes": [ { "action": { @@ -131,17 +132,15 @@ 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 assert 'success' in client.conf( { - "listeners": {"*:7080": {"pass": "routes"}}, + "listeners": {"*:8080": {"pass": "routes"}}, "routes": [ { "action": { @@ -162,7 +161,7 @@ def test_rewrite_share(temp_dir): index_path = f'{temp_dir}${{request_uri}}/index.html' assert 'success' in client.conf( { - "listeners": {"*:7080": {"pass": "routes"}}, + "listeners": {"*:8080": {"pass": "routes"}}, "routes": [ { "match": {"uri": "/foo"}, @@ -182,7 +181,7 @@ def test_rewrite_share(temp_dir): assert 'success' in client.conf( { - "listeners": {"*:7080": {"pass": "routes"}}, + "listeners": {"*:8080": {"pass": "routes"}}, "routes": [ { "match": {"uri": "/foo"}, diff --git a/test/test_routing.py b/test/test_routing.py index a18edb04..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 @@ -12,7 +13,7 @@ client = ApplicationPython() def setup_method_fixture(): assert 'success' in client.conf( { - "listeners": {"*:7080": {"pass": "routes"}}, + "listeners": {"*:8080": {"pass": "routes"}}, "routes": [ { "match": {"method": "GET"}, @@ -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'] @@ -322,7 +325,7 @@ def test_routes_pass_encode(): def check_pass(path, name): assert 'success' in client.conf( { - "listeners": {"*:7080": {"pass": f'applications/{path}'}}, + "listeners": {"*:8080": {"pass": f'applications/{path}'}}, "applications": { name: { "type": client.get_application_type(), @@ -345,7 +348,7 @@ def test_routes_pass_encode(): def check_pass_error(path, name): assert 'error' in client.conf( { - "listeners": {"*:7080": {"pass": f'applications/{path}'}}, + "listeners": {"*:8080": {"pass": f'applications/{path}'}}, "applications": { name: { "type": client.get_application_type(), @@ -365,7 +368,7 @@ def test_routes_pass_encode(): def test_routes_absent(): assert 'success' in client.conf( { - "listeners": {"*:7081": {"pass": "applications/empty"}}, + "listeners": {"*:8081": {"pass": "applications/empty"}}, "applications": { "empty": { "type": client.get_application_type(), @@ -378,19 +381,19 @@ def test_routes_absent(): } ) - assert client.get(port=7081)['status'] == 200, 'routes absent' + assert client.get(port=8081)['status'] == 200, 'routes absent' def test_routes_pass_invalid(): assert 'error' in client.conf( - {"pass": "routes/blah"}, 'listeners/*:7080' + {"pass": "routes/blah"}, 'listeners/*:8080' ), 'routes invalid' def test_route_empty(): assert 'success' in client.conf( { - "listeners": {"*:7080": {"pass": "routes/main"}}, + "listeners": {"*:8080": {"pass": "routes/main"}}, "routes": {"main": []}, "applications": {}, } @@ -437,14 +440,14 @@ def test_routes_route_pass(): "upstreams": { "one": { "servers": { - "127.0.0.1:7081": {}, - "127.0.0.1:7082": {}, + "127.0.0.1:8081": {}, + "127.0.0.1:8082": {}, }, }, "two": { "servers": { - "127.0.0.1:7081": {}, - "127.0.0.1:7082": {}, + "127.0.0.1:8081": {}, + "127.0.0.1:8082": {}, }, }, }, @@ -480,14 +483,14 @@ def test_routes_route_pass_invalid(): "upstreams": { "one": { "servers": { - "127.0.0.1:7081": {}, - "127.0.0.1:7082": {}, + "127.0.0.1:8081": {}, + "127.0.0.1:8082": {}, }, }, "two": { "servers": { - "127.0.0.1:7081": {}, - "127.0.0.1:7082": {}, + "127.0.0.1:8081": {}, + "127.0.0.1:8082": {}, }, }, }, @@ -512,10 +515,10 @@ def test_routes_action_unique(temp_dir): assert 'success' in client.conf( { "listeners": { - "*:7080": {"pass": "routes"}, - "*:7081": {"pass": "applications/app"}, + "*:8080": {"pass": "routes"}, + "*:8081": {"pass": "applications/app"}, }, - "routes": [{"action": {"proxy": "http://127.0.0.1:7081"}}], + "routes": [{"action": {"proxy": "http://127.0.0.1:8081"}}], "applications": { "app": { "type": client.get_application_type(), @@ -528,12 +531,12 @@ def test_routes_action_unique(temp_dir): ) assert 'error' in client.conf( - {"proxy": "http://127.0.0.1:7081", "share": temp_dir}, + {"proxy": "http://127.0.0.1:8081", "share": temp_dir}, 'routes/0/action', ), 'proxy share' assert 'error' in client.conf( { - "proxy": "http://127.0.0.1:7081", + "proxy": "http://127.0.0.1:8081", "pass": "applications/app", }, 'routes/0/action', @@ -560,7 +563,7 @@ def test_routes_rules_two(): def test_routes_two(): assert 'success' in client.conf( { - "listeners": {"*:7080": {"pass": "routes/first"}}, + "listeners": {"*:8080": {"pass": "routes/first"}}, "routes": { "first": [ { @@ -606,14 +609,14 @@ def test_routes_match_host_ipv4(): route_match({"host": "127.0.0.1"}) host('127.0.0.1', 200) - host('127.0.0.1:7080', 200) + host('127.0.0.1:8080', 200) def test_routes_match_host_ipv6(): route_match({"host": "[::1]"}) host('[::1]', 200) - host('[::1]:7080', 200) + host('[::1]:8080', 200) def test_routes_match_host_positive_many(): @@ -649,7 +652,7 @@ def test_routes_match_host_case_insensitive(): def test_routes_match_host_port(): route_match({"host": "example.com"}) - host('example.com:7080', 200) + host('example.com:8080', 200) def test_routes_match_host_empty(): @@ -718,7 +721,7 @@ def test_routes_reconfigure(): assert 'success' in client.conf( { - "listeners": {"*:7080": {"pass": "routes/main"}}, + "listeners": {"*:8080": {"pass": "routes/main"}}, "routes": {"main": [{"action": {"return": 200}}]}, "applications": {}, } @@ -801,7 +804,7 @@ def test_routes_edit(): assert 'success' in client.conf( { - "listeners": {"*:7080": {"pass": "routes/main"}}, + "listeners": {"*:8080": {"pass": "routes/main"}}, "routes": {"main": [{"action": {"return": 200}}]}, "applications": {}, } @@ -817,7 +820,7 @@ def test_routes_edit(): assert client.get()['status'] == 200, 'routes edit GET 7' assert 'success' in client.conf_delete( - 'listeners/*:7080' + 'listeners/*:8080' ), 'route edit configure 8' assert 'success' in client.conf_delete( 'routes/main' @@ -1646,14 +1649,14 @@ def test_routes_source_port(): def test_routes_source_addr(): assert 'success' in client.conf( { - "*:7080": {"pass": "routes"}, - "[::1]:7081": {"pass": "routes"}, + "*:8080": {"pass": "routes"}, + "[::1]:8081": {"pass": "routes"}, }, 'listeners', ), 'source listeners configure' def get_ipv6(): - return client.get(sock_type='ipv6', port=7081) + return client.get(sock_type='ipv6', port=8081) route_match({"source": "127.0.0.1"}) assert client.get()['status'] == 200, 'exact' @@ -1707,64 +1710,64 @@ def test_routes_source_addr(): def test_routes_source_ipv6(): assert 'success' in client.conf( { - "[::1]:7080": {"pass": "routes"}, - "127.0.0.1:7081": {"pass": "routes"}, + "[::1]:8080": {"pass": "routes"}, + "127.0.0.1:8081": {"pass": "routes"}, }, 'listeners', ), 'source listeners configure' route_match({"source": "::1"}) assert client.get(sock_type='ipv6')['status'] == 200, 'exact' - assert client.get(port=7081)['status'] == 404, 'exact ipv4' + assert client.get(port=8081)['status'] == 404, 'exact ipv4' route_match({"source": ["::1"]}) assert client.get(sock_type='ipv6')['status'] == 200, 'exact 2' - assert client.get(port=7081)['status'] == 404, 'exact 2 ipv4' + assert client.get(port=8081)['status'] == 404, 'exact 2 ipv4' route_match({"source": "!::1"}) assert client.get(sock_type='ipv6')['status'] == 404, 'exact neg' - assert client.get(port=7081)['status'] == 200, 'exact neg ipv4' + assert client.get(port=8081)['status'] == 200, 'exact neg ipv4' route_match({"source": "::2"}) assert client.get(sock_type='ipv6')['status'] == 404, 'exact 3' - assert client.get(port=7081)['status'] == 404, 'exact 3 ipv4' + assert client.get(port=8081)['status'] == 404, 'exact 3 ipv4' route_match({"source": "::1-::1"}) assert client.get(sock_type='ipv6')['status'] == 200, 'range' - assert client.get(port=7081)['status'] == 404, 'range ipv4' + assert client.get(port=8081)['status'] == 404, 'range ipv4' route_match({"source": "::2-::2"}) assert client.get(sock_type='ipv6')['status'] == 404, 'range 2' - assert client.get(port=7081)['status'] == 404, 'range 2 ipv4' + assert client.get(port=8081)['status'] == 404, 'range 2 ipv4' route_match({"source": "::2-::3"}) assert client.get(sock_type='ipv6')['status'] == 404, 'range 3' - assert client.get(port=7081)['status'] == 404, 'range 3 ipv4' + assert client.get(port=8081)['status'] == 404, 'range 3 ipv4' route_match({"source": "::1-::2"}) assert client.get(sock_type='ipv6')['status'] == 200, 'range 4' - assert client.get(port=7081)['status'] == 404, 'range 4 ipv4' + assert client.get(port=8081)['status'] == 404, 'range 4 ipv4' route_match({"source": "::0-::2"}) assert client.get(sock_type='ipv6')['status'] == 200, 'range 5' - assert client.get(port=7081)['status'] == 404, 'range 5 ipv4' + assert client.get(port=8081)['status'] == 404, 'range 5 ipv4' route_match({"source": "::0-::1"}) assert client.get(sock_type='ipv6')['status'] == 200, 'range 6' - assert client.get(port=7081)['status'] == 404, 'range 6 ipv4' + assert client.get(port=8081)['status'] == 404, 'range 6 ipv4' def test_routes_source_cidr(): assert 'success' in client.conf( { - "*:7080": {"pass": "routes"}, - "[::1]:7081": {"pass": "routes"}, + "*:8080": {"pass": "routes"}, + "[::1]:8081": {"pass": "routes"}, }, 'listeners', ), 'source listeners configure' def get_ipv6(): - return client.get(sock_type='ipv6', port=7081) + return client.get(sock_type='ipv6', port=8081) route_match({"source": "127.0.0.1/32"}) assert client.get()['status'] == 200, '32' @@ -1790,35 +1793,35 @@ def test_routes_source_cidr(): def test_routes_source_cidr_ipv6(): assert 'success' in client.conf( { - "[::1]:7080": {"pass": "routes"}, - "127.0.0.1:7081": {"pass": "routes"}, + "[::1]:8080": {"pass": "routes"}, + "127.0.0.1:8081": {"pass": "routes"}, }, 'listeners', ), 'source listeners configure' route_match({"source": "::1/128"}) assert client.get(sock_type='ipv6')['status'] == 200, '128' - assert client.get(port=7081)['status'] == 404, '128 ipv4' + assert client.get(port=8081)['status'] == 404, '128 ipv4' route_match({"source": "::0/128"}) assert client.get(sock_type='ipv6')['status'] == 404, '128 2' - assert client.get(port=7081)['status'] == 404, '128 ipv4' + assert client.get(port=8081)['status'] == 404, '128 ipv4' route_match({"source": "::0/127"}) assert client.get(sock_type='ipv6')['status'] == 200, '127' - assert client.get(port=7081)['status'] == 404, '127 ipv4' + assert client.get(port=8081)['status'] == 404, '127 ipv4' route_match({"source": "::0/32"}) assert client.get(sock_type='ipv6')['status'] == 200, '32' - assert client.get(port=7081)['status'] == 404, '32 ipv4' + assert client.get(port=8081)['status'] == 404, '32 ipv4' route_match({"source": "::0/1"}) assert client.get(sock_type='ipv6')['status'] == 200, '1' - assert client.get(port=7081)['status'] == 404, '1 ipv4' + assert client.get(port=8081)['status'] == 404, '1 ipv4' route_match({"source": "::/0"}) assert client.get(sock_type='ipv6')['status'] == 200, '0' - assert client.get(port=7081)['status'] == 404, '0 ipv4' + assert client.get(port=8081)['status'] == 404, '0 ipv4' def test_routes_source_unix(temp_dir): @@ -1826,7 +1829,7 @@ def test_routes_source_unix(temp_dir): assert 'success' in client.conf( { - "127.0.0.1:7081": {"pass": "routes"}, + "127.0.0.1:8081": {"pass": "routes"}, f'unix:{addr}': {"pass": "routes"}, }, 'listeners', @@ -1843,7 +1846,7 @@ def test_routes_source_unix(temp_dir): ), 'unix ipv6 neg' route_match({"source": "unix"}) - assert client.get(port=7081)['status'] == 404, 'unix ipv4' + assert client.get(port=8081)['status'] == 404, 'unix ipv4' assert client.get(sock_type='unix', addr=addr)['status'] == 200, 'unix' @@ -1916,7 +1919,7 @@ def test_routes_match_source_invalid(): route_match_invalid({"source": "2001::/129"}) route_match_invalid({"source": "::FFFFF"}) route_match_invalid({"source": "[::1]:"}) - route_match_invalid({"source": "[:::]:7080"}) + route_match_invalid({"source": "[:::]:8080"}) route_match_invalid({"source": "*:"}) route_match_invalid({"source": "*:1-a"}) route_match_invalid({"source": "*:65536"}) @@ -1929,74 +1932,74 @@ def test_routes_match_source_none(): def test_routes_match_destination(): assert 'success' in client.conf( - {"*:7080": {"pass": "routes"}, "*:7081": {"pass": "routes"}}, + {"*:8080": {"pass": "routes"}, "*:8081": {"pass": "routes"}}, 'listeners', ), 'listeners configure' - route_match({"destination": "*:7080"}) + route_match({"destination": "*:8080"}) assert client.get()['status'] == 200, 'dest' - assert client.get(port=7081)['status'] == 404, 'dest 2' + assert client.get(port=8081)['status'] == 404, 'dest 2' - route_match({"destination": ["127.0.0.1:7080"]}) + route_match({"destination": ["127.0.0.1:8080"]}) assert client.get()['status'] == 200, 'dest 3' - assert client.get(port=7081)['status'] == 404, 'dest 4' + assert client.get(port=8081)['status'] == 404, 'dest 4' - route_match({"destination": "!*:7080"}) + route_match({"destination": "!*:8080"}) assert client.get()['status'] == 404, 'dest neg' - assert client.get(port=7081)['status'] == 200, 'dest neg 2' + assert client.get(port=8081)['status'] == 200, 'dest neg 2' - route_match({"destination": ['!*:7080', '!*:7081']}) + route_match({"destination": ['!*:8080', '!*:8081']}) assert client.get()['status'] == 404, 'dest neg 3' - assert client.get(port=7081)['status'] == 404, 'dest neg 4' + assert client.get(port=8081)['status'] == 404, 'dest neg 4' - route_match({"destination": ['!*:7081', '!*:7082']}) + route_match({"destination": ['!*:8081', '!*:8082']}) assert client.get()['status'] == 200, 'dest neg 5' - route_match({"destination": ['*:7080', '!*:7080']}) + route_match({"destination": ['*:8080', '!*:8080']}) assert client.get()['status'] == 404, 'dest neg 6' - route_match({"destination": ['127.0.0.1:7080', '*:7081', '!*:7080']}) + route_match({"destination": ['127.0.0.1:8080', '*:8081', '!*:8080']}) assert client.get()['status'] == 404, 'dest neg 7' - assert client.get(port=7081)['status'] == 200, 'dest neg 8' + assert client.get(port=8081)['status'] == 200, 'dest neg 8' - route_match({"destination": ['!*:7081', '!*:7082', '*:7083']}) + route_match({"destination": ['!*:8081', '!*:8082', '*:8083']}) assert client.get()['status'] == 404, 'dest neg 9' - route_match({"destination": ['*:7081', '!127.0.0.1:7080', '*:7080']}) + route_match({"destination": ['*:8081', '!127.0.0.1:8080', '*:8080']}) assert client.get()['status'] == 404, 'dest neg 10' - assert client.get(port=7081)['status'] == 200, 'dest neg 11' + assert client.get(port=8081)['status'] == 200, 'dest neg 11' assert 'success' in client.conf_delete( 'routes/0/match/destination/0' ), 'remove destination rule' assert client.get()['status'] == 404, 'dest neg 12' - assert client.get(port=7081)['status'] == 404, 'dest neg 13' + assert client.get(port=8081)['status'] == 404, 'dest neg 13' assert 'success' in client.conf_delete( 'routes/0/match/destination/0' ), 'remove destination rule 2' assert client.get()['status'] == 200, 'dest neg 14' - assert client.get(port=7081)['status'] == 404, 'dest neg 15' + assert client.get(port=8081)['status'] == 404, 'dest neg 15' assert 'success' in client.conf_post( "\"!127.0.0.1\"", 'routes/0/match/destination' ), 'add destination rule' assert client.get()['status'] == 404, 'dest neg 16' - assert client.get(port=7081)['status'] == 404, 'dest neg 17' + assert client.get(port=8081)['status'] == 404, 'dest neg 17' def test_routes_match_destination_proxy(): assert 'success' in client.conf( { "listeners": { - "*:7080": {"pass": "routes/first"}, - "*:7081": {"pass": "routes/second"}, + "*:8080": {"pass": "routes/first"}, + "*:8081": {"pass": "routes/second"}, }, "routes": { - "first": [{"action": {"proxy": "http://127.0.0.1:7081"}}], + "first": [{"action": {"proxy": "http://127.0.0.1:8081"}}], "second": [ { - "match": {"destination": ["127.0.0.1:7081"]}, + "match": {"destination": ["127.0.0.1:8081"]}, "action": {"return": 200}, } ], diff --git a/test/test_routing_tls.py b/test/test_routing_tls.py index 4a97c8e4..f8cef546 100644 --- a/test/test_routing_tls.py +++ b/test/test_routing_tls.py @@ -11,8 +11,8 @@ def test_routes_match_scheme_tls(): assert 'success' in client.conf( { "listeners": { - "*:7080": {"pass": "routes"}, - "*:7081": { + "*:8080": {"pass": "routes"}, + "*:8081": { "pass": "routes", "tls": {"certificate": 'default'}, }, @@ -26,4 +26,4 @@ def test_routes_match_scheme_tls(): ), 'scheme configure' assert client.get()['status'] == 200, 'http' - assert client.get_ssl(port=7081)['status'] == 201, 'https' + assert client.get_ssl(port=8081)['status'] == 201, 'https' diff --git a/test/test_ruby_application.py b/test/test_ruby_application.py index 6f533b70..127b75b7 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'}} @@ -91,7 +92,7 @@ def test_ruby_application_server_port(): client.load('server_port') assert ( - client.get()['headers']['Server-Port'] == '7080' + client.get()['headers']['Server-Port'] == '8080' ), 'Server-Port header' @@ -164,15 +165,6 @@ def test_ruby_application_input_each(): @pytest.mark.skip('not yet') -def test_ruby_application_input_rewind(): - client.load('input_rewind') - - body = '0123456789' - - assert client.post(body=body)['body'] == body, 'input rewind' - - -@pytest.mark.skip('not yet') def test_ruby_application_syntax_error(skip_alert): skip_alert( r'Failed to parse rack script', @@ -317,6 +309,26 @@ def test_ruby_application_header_status(): assert client.get()['status'] == 200, 'header status' +def test_ruby_application_header_array(): + client.load('header_array') + + assert client.get()['headers']['x-array'] == 'name=value; ; value; av' + + +def test_ruby_application_header_array_nil(): + client.load('header_array_nil') + + assert client.get()['status'] == 503 + + +def test_ruby_application_header_array_empty(): + client.load('header_array_empty') + + headers = client.get()['headers'] + assert 'x-array' in headers + assert headers['x-array'] == '' + + @pytest.mark.skip('not yet') def test_ruby_application_header_rack(): client.load('header_rack') @@ -324,6 +336,20 @@ def test_ruby_application_header_rack(): assert client.get()['status'] == 500, 'header rack' +@pytest.mark.skip('not yet') +def test_ruby_application_session(): + client.load('session') + + assert client.get()['status'] == 200 + + +@pytest.mark.skip('not yet') +def test_ruby_application_multipart(): + client.load('multipart') + + assert client.get()['status'] == 200 + + def test_ruby_application_body_empty(): client.load('body_empty') diff --git a/test/test_ruby_hooks.py b/test/test_ruby_hooks.py index 38893e47..dd9e0fca 100644 --- a/test/test_ruby_hooks.py +++ b/test/test_ruby_hooks.py @@ -1,8 +1,11 @@ from unit.applications.lang.ruby import ApplicationRuby from unit.option import option from unit.utils import waitforglob +from packaging import version -prerequisites = {'modules': {'ruby': 'all'}} +prerequisites = { + 'modules': {'ruby': lambda v: version.parse(v) >= version.parse('3.0')} +} client = ApplicationRuby() diff --git a/test/test_settings.py b/test/test_settings.py index 33180046..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'}} @@ -460,7 +461,7 @@ def test_settings_log_route(findall, search_in_file, wait_for_record): assert 'success' in client.conf( { - "listeners": {"*:7080": {"pass": "routes"}}, + "listeners": {"*:8080": {"pass": "routes"}}, "routes": [ { "match": { @@ -487,7 +488,7 @@ def test_settings_log_route(findall, search_in_file, wait_for_record): assert 'success' in client.conf( { - "listeners": {"*:7080": {"pass": "routes/main"}}, + "listeners": {"*:8080": {"pass": "routes/main"}}, "routes": { "main": [ { @@ -516,7 +517,7 @@ def test_settings_log_route(findall, search_in_file, wait_for_record): assert 'success' in client.conf( { - "listeners": {"*:7080": {"pass": "routes/first"}}, + "listeners": {"*:8080": {"pass": "routes/first"}}, "routes": { "first": [ { @@ -541,7 +542,7 @@ def test_settings_log_route(findall, search_in_file, wait_for_record): assert 'success' in client.conf( { - "listeners": {"*:7080": {"pass": "routes/fall"}}, + "listeners": {"*:8080": {"pass": "routes/fall"}}, "routes": { "fall": [ { diff --git a/test/test_static.py b/test/test_static.py index d46247d9..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,22 +13,17 @@ 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( { - "listeners": {"*:7080": {"pass": "routes"}}, + "listeners": {"*:8080": {"pass": "routes"}}, "routes": [{"action": {"share": f'{assets_dir}$uri'}}], "settings": { "http": { @@ -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 6b4dd89a..31e10b4e 100644 --- a/test/test_static_chroot.py +++ b/test/test_static_chroot.py @@ -2,25 +2,27 @@ 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( { - "listeners": {"*:7080": {"pass": "routes"}}, + "listeners": {"*:8080": {"pass": "routes"}}, "routes": [{"action": {"share": f'{temp_dir}/assets$uri'}}], } ) @@ -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 ffc888ab..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) @@ -19,8 +20,8 @@ def setup_method_fixture(temp_dir): assert 'success' in client.conf( { "listeners": { - "*:7080": {"pass": "routes"}, - "*:7081": {"pass": "routes"}, + "*:8080": {"pass": "routes"}, + "*:8081": {"pass": "routes"}, }, "routes": [{"action": {"share": f'{assets_dir}$uri'}}], "applications": {}, @@ -108,13 +109,13 @@ def test_static_fallback_proxy(): assert 'success' in client.conf( [ { - "match": {"destination": "*:7081"}, + "match": {"destination": "*:8081"}, "action": {"return": 200}, }, { "action": { "share": "/blah", - "fallback": {"proxy": "http://127.0.0.1:7081"}, + "fallback": {"proxy": "http://127.0.0.1:8081"}, } }, ], @@ -136,11 +137,11 @@ def test_static_fallback_proxy_loop(skip_alert): ) action_update( - {"share": "/blah", "fallback": {"proxy": "http://127.0.0.1:7080"}} + {"share": "/blah", "fallback": {"proxy": "http://127.0.0.1:8080"}} ) client.get(no_recv=True) - assert 'success' in client.conf_delete('listeners/*:7081') + assert 'success' in client.conf_delete('listeners/*:8081') client.get(read_timeout=1) @@ -152,6 +153,6 @@ def test_static_fallback_invalid(): check_error({"share": "/blah", "fallback": ""}) check_error({"return": 200, "fallback": {"share": "/blah"}}) check_error( - {"proxy": "http://127.0.0.1:7081", "fallback": {"share": "/blah"}} + {"proxy": "http://127.0.0.1:8081", "fallback": {"share": "/blah"}} ) check_error({"fallback": {"share": "/blah"}}) diff --git a/test/test_static_mount.py b/test/test_static_mount.py index ccd18919..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( @@ -38,7 +41,7 @@ def setup_method_fixture(temp_dir): assert 'success' in client.conf( { - "listeners": {"*:7080": {"pass": "routes"}}, + "listeners": {"*:8080": {"pass": "routes"}}, "routes": [{"action": {"share": f'{temp_dir}/assets/dir$uri'}}], } ) diff --git a/test/test_static_share.py b/test/test_static_share.py index ac5afb50..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,12 +13,12 @@ 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( { - "listeners": {"*:7080": {"pass": "routes"}}, + "listeners": {"*:8080": {"pass": "routes"}}, "routes": [{"action": {"share": f'{temp_dir}/assets$uri'}}], "applications": {}, } diff --git a/test/test_static_symlink.py b/test/test_static_symlink.py index 1f7d7907..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,12 +13,14 @@ 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( { - "listeners": {"*:7080": {"pass": "routes"}}, + "listeners": {"*:8080": {"pass": "routes"}}, "routes": [{"action": {"share": f'{temp_dir}/assets$uri'}}], } ) diff --git a/test/test_static_types.py b/test/test_static_types.py index 8cd28ca4..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,15 +11,15 @@ 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( { "listeners": { - "*:7080": {"pass": "routes"}, - "*:7081": {"pass": "routes"}, + "*:8080": {"pass": "routes"}, + "*:8081": {"pass": "routes"}, }, "routes": [{"action": {"share": f'{temp_dir}/assets$uri'}}], "applications": {}, @@ -124,14 +125,14 @@ def test_static_types_fallback(temp_dir): assert 'success' in client.conf( [ { - "match": {"destination": "*:7081"}, + "match": {"destination": "*:8081"}, "action": {"return": 200}, }, { "action": { "share": f'{temp_dir}/assets$uri', "types": ["!application/x-httpd-php"], - "fallback": {"proxy": "http://127.0.0.1:7081"}, + "fallback": {"proxy": "http://127.0.0.1:8081"}, } }, ], @@ -155,7 +156,7 @@ def test_static_types_index(temp_dir): def test_static_types_custom_mime(temp_dir): assert 'success' in client.conf( { - "listeners": {"*:7080": {"pass": "routes"}}, + "listeners": {"*:8080": {"pass": "routes"}}, "routes": [{"action": {"share": f'{temp_dir}/assets$uri'}}], "applications": {}, "settings": { diff --git a/test/test_static_variables.py b/test/test_static_variables.py index bc39e90e..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,13 +12,15 @@ 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( { - "listeners": {"*:7080": {"pass": "routes"}}, + "listeners": {"*:8080": {"pass": "routes"}}, "routes": [{"action": {"share": f'{temp_dir}/assets$uri'}}], } ) diff --git a/test/test_status.py b/test/test_status.py index 11b140cf..a52f7486 100644 --- a/test/test_status.py +++ b/test/test_status.py @@ -39,9 +39,9 @@ def test_status_requests(skip_alert): assert 'success' in client.conf( { "listeners": { - "*:7080": {"pass": "routes"}, - "*:7081": {"pass": "applications/empty"}, - "*:7082": {"pass": "applications/blah"}, + "*:8080": {"pass": "routes"}, + "*:8081": {"pass": "applications/empty"}, + "*:8082": {"pass": "applications/blah"}, }, "routes": [{"action": {"return": 200}}], "applications": { @@ -60,7 +60,7 @@ def test_status_requests(skip_alert): assert client.get()['status'] == 200 assert Status.get('/requests/total') == 1, '2xx' - assert client.get(port=7081)['status'] == 200 + assert client.get(port=8081)['status'] == 200 assert Status.get('/requests/total') == 2, '2xx app' assert ( @@ -69,7 +69,7 @@ def test_status_requests(skip_alert): ) assert Status.get('/requests/total') == 3, '4xx' - assert client.get(port=7082)['status'] == 503 + assert client.get(port=8082)['status'] == 503 assert Status.get('/requests/total') == 4, '5xx' client.http( @@ -85,7 +85,7 @@ Connection: close ) assert Status.get('/requests/total') == 6, 'pipeline' - sock = client.get(port=7081, no_recv=True) + sock = client.get(port=8081, no_recv=True) time.sleep(1) @@ -98,8 +98,8 @@ def test_status_connections(): assert 'success' in client.conf( { "listeners": { - "*:7080": {"pass": "routes"}, - "*:7081": {"pass": "applications/delayed"}, + "*:8080": {"pass": "routes"}, + "*:8081": {"pass": "applications/delayed"}, }, "routes": [{"action": {"return": 200}}], "applications": { @@ -136,7 +136,7 @@ def test_status_connections(): 'X-Delay': '2', 'Connection': 'close', }, - port=7081, + port=8081, start=True, read_timeout=1, ) @@ -194,8 +194,8 @@ def test_status_applications(): assert 'success' in client.conf( { "listeners": { - "*:7080": {"pass": "applications/restart"}, - "*:7081": {"pass": "applications/delayed"}, + "*:8080": {"pass": "applications/restart"}, + "*:8081": {"pass": "applications/delayed"}, }, "routes": [], "applications": { @@ -220,13 +220,13 @@ def test_status_proxy(): assert 'success' in client.conf( { "listeners": { - "*:7080": {"pass": "routes"}, - "*:7081": {"pass": "applications/empty"}, + "*:8080": {"pass": "routes"}, + "*:8081": {"pass": "applications/empty"}, }, "routes": [ { "match": {"uri": "/"}, - "action": {"proxy": "http://127.0.0.1:7081"}, + "action": {"proxy": "http://127.0.0.1:8081"}, } ], "applications": { diff --git a/test/test_status_tls.py b/test/test_status_tls.py index 784b4960..f69f021e 100644 --- a/test/test_status_tls.py +++ b/test/test_status_tls.py @@ -12,8 +12,8 @@ def test_status_tls_requests(): assert 'success' in client.conf( { "listeners": { - "*:7080": {"pass": "routes"}, - "*:7081": { + "*:8080": {"pass": "routes"}, + "*:8081": { "pass": "routes", "tls": {"certificate": "default"}, }, @@ -26,6 +26,6 @@ def test_status_tls_requests(): Status.init() assert client.get()['status'] == 200 - assert client.get_ssl(port=7081)['status'] == 200 + assert client.get_ssl(port=8081)['status'] == 200 assert Status.get('/requests/total') == 2 diff --git a/test/test_tls.py b/test/test_tls.py index 54fdb665..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 @@ -12,7 +14,7 @@ prerequisites = {'modules': {'python': 'any', 'openssl': 'any'}} client = ApplicationTLS() -def add_tls(application='empty', cert='default', port=7080): +def add_tls(application='empty', cert='default', port=8080): assert 'success' in client.conf( { "pass": f"applications/{application}", @@ -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,20 +73,16 @@ 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=7080): +def remove_tls(application='empty', port=8080): assert 'success' in client.conf( {"pass": f"applications/{application}"}, f'listeners/*:{port}' ) @@ -178,12 +175,12 @@ def test_tls_certificate_update(): add_tls() - cert_old = ssl.get_server_certificate(('127.0.0.1', 7080)) + cert_old = ssl.get_server_certificate(('127.0.0.1', 8080)) client.certificate() assert cert_old != ssl.get_server_certificate( - ('127.0.0.1', 7080) + ('127.0.0.1', 8080) ), 'update certificate' @@ -207,12 +204,12 @@ def test_tls_certificate_change(): add_tls() - cert_old = ssl.get_server_certificate(('127.0.0.1', 7080)) + cert_old = ssl.get_server_certificate(('127.0.0.1', 8080)) add_tls(cert='new') assert cert_old != ssl.get_server_certificate( - ('127.0.0.1', 7080) + ('127.0.0.1', 8080) ), 'change certificate' @@ -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( @@ -542,7 +541,7 @@ def test_tls_no_close_notify(): assert 'success' in client.conf( { "listeners": { - "*:7080": { + "*:8080": { "pass": "routes", "tls": {"certificate": "default"}, } @@ -576,7 +575,7 @@ def test_tls_keepalive_certificate_remove(): ) assert 'success' in client.conf( - {"pass": "applications/empty"}, 'listeners/*:7080' + {"pass": "applications/empty"}, 'listeners/*:8080' ) assert 'success' in client.conf_delete('/certificates/default') @@ -697,8 +696,8 @@ def test_tls_multi_listener(): client.certificate() add_tls() - add_tls(port=7081) + add_tls(port=8081) assert client.get_ssl()['status'] == 200, 'listener #1' - assert client.get_ssl(port=7081)['status'] == 200, 'listener #2' + assert client.get_ssl(port=8081)['status'] == 200, 'listener #2' diff --git a/test/test_tls_conf_command.py b/test/test_tls_conf_command.py index 49df7bf3..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'}} @@ -15,7 +16,7 @@ def setup_method_fixture(): assert 'success' in client.conf( { "listeners": { - "*:7080": { + "*:8080": { "pass": "routes", "tls": {"certificate": "default"}, } @@ -55,7 +56,7 @@ def test_tls_conf_command(): "certificate": "default", "conf_commands": {"protocol": f'-{protocol}'}, }, - 'listeners/*:7080/tls', + 'listeners/*:8080/tls', ), 'protocol disabled' sock.close() @@ -84,7 +85,7 @@ def test_tls_conf_command(): "cipherstring": f"{cipher[1]}:!{cipher[0]}", }, }, - 'listeners/*:7080/tls', + 'listeners/*:8080/tls', ), 'cipher disabled' if len(ciphers) > 1: @@ -106,7 +107,7 @@ def test_tls_conf_command_invalid(skip_alert): def check_conf_commands(conf_commands): assert 'error' in client.conf( {"certificate": "default", "conf_commands": conf_commands}, - 'listeners/*:7080/tls', + 'listeners/*:8080/tls', ), 'ivalid conf_commands' check_conf_commands([]) diff --git a/test/test_tls_session.py b/test/test_tls_session.py index 8b2b04fd..8da0306a 100644 --- a/test/test_tls_session.py +++ b/test/test_tls_session.py @@ -26,7 +26,7 @@ def setup_method_fixture(): assert 'success' in client.conf( { "listeners": { - "*:7080": { + "*:8080": { "pass": "routes", "tls": {"certificate": "default", "session": {}}, } @@ -45,11 +45,11 @@ def add_session(cache_size=None, timeout=None): if timeout is not None: session['timeout'] = timeout - return client.conf(session, 'listeners/*:7080/tls/session') + return client.conf(session, 'listeners/*:8080/tls/session') def connect(ctx=None, session=None): - sock = socket.create_connection(('127.0.0.1', 7080)) + sock = socket.create_connection(('127.0.0.1', 8080)) if ctx is None: ctx = Context(TLSv1_2_METHOD) diff --git a/test/test_tls_sni.py b/test/test_tls_sni.py index 253d9813..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 @@ -14,7 +15,7 @@ client = ApplicationTLS() def setup_method_fixture(): assert 'success' in client.conf( { - "listeners": {"*:7080": {"pass": "routes"}}, + "listeners": {"*:8080": {"pass": "routes"}}, "routes": [{"action": {"return": 200}}], "applications": {}, } @@ -24,7 +25,7 @@ def setup_method_fixture(): def add_tls(cert='default'): assert 'success' in client.conf( {"pass": "routes", "tls": {"certificate": cert}}, - 'listeners/*:7080', + 'listeners/*:8080', ) @@ -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('') @@ -141,7 +142,7 @@ def load_certs(bundles): def remove_tls(): - assert 'success' in client.conf({"pass": "routes"}, 'listeners/*:7080') + assert 'success' in client.conf({"pass": "routes"}, 'listeners/*:8080') def test_tls_sni(): @@ -289,7 +290,7 @@ def test_tls_sni_invalid(): def check_certificate(cert): assert 'error' in client.conf( {"pass": "routes", "tls": {"certificate": cert}}, - 'listeners/*:7080', + 'listeners/*:8080', ) check_certificate('') diff --git a/test/test_tls_tickets.py b/test/test_tls_tickets.py index 0d8e4f36..5e899a9b 100644 --- a/test/test_tls_tickets.py +++ b/test/test_tls_tickets.py @@ -36,9 +36,9 @@ def setup_method_fixture(): assert 'success' in client.conf( { "listeners": { - "*:7080": listener_conf, - "*:7081": listener_conf, - "*:7082": listener_conf, + "*:8080": listener_conf, + "*:8081": listener_conf, + "*:8082": listener_conf, }, "routes": [{"action": {"return": 200}}], "applications": {}, @@ -46,7 +46,7 @@ def setup_method_fixture(): ), 'load application configuration' -def connect(ctx=None, session=None, port=7080): +def connect(ctx=None, session=None, port=8080): sock = socket.create_connection(('127.0.0.1', port)) if ctx is None: @@ -72,7 +72,7 @@ def has_ticket(sess): return _lib.SSL_SESSION_has_ticket(sess._session) -def set_tickets(tickets=True, port=7080): +def set_tickets(tickets=True, port=8080): assert 'success' in client.conf( {"cache_size": 0, "tickets": tickets}, f'listeners/*:{port}/tls/session', @@ -98,7 +98,7 @@ def test_tls_ticket(): assert not has_ticket(sess), 'tickets False' assert 'success' in client.conf_delete( - 'listeners/*:7080/tls/session/tickets' + 'listeners/*:8080/tls/session/tickets' ), 'tickets default configure' sess, _, _ = connect() @@ -118,13 +118,13 @@ def test_tls_ticket_string(): assert has_ticket(sess2), 'tickets string reconnect' assert reused, 'tickets string reused' - sess2, _, reused = connect(ctx, sess, port=7081) + sess2, _, reused = connect(ctx, sess, port=8081) assert has_ticket(sess2), 'connect True' assert not reused, 'connect True not reused' - set_tickets(TICKET2, port=7081) + set_tickets(TICKET2, port=8081) - sess2, _, reused = connect(ctx, sess, port=7081) + sess2, _, reused = connect(ctx, sess, port=8081) assert has_ticket(sess2), 'wrong ticket' assert not reused, 'wrong ticket not reused' @@ -137,7 +137,7 @@ def test_tls_ticket_string(): assert has_ticket(sess2), 'tickets string 80 reconnect' assert reused, 'tickets string 80 reused' - sess2, _, reused = connect(ctx, sess, port=7081) + sess2, _, reused = connect(ctx, sess, port=8081) assert has_ticket(sess2), 'wrong ticket 80' assert not reused, 'wrong ticket 80 not reused' @@ -153,34 +153,34 @@ def test_tls_ticket_array(): assert not has_ticket(sess), 'tickets array empty' set_tickets([TICKET, TICKET2]) - set_tickets(TICKET, port=7081) - set_tickets(TICKET2, port=7082) + set_tickets(TICKET, port=8081) + set_tickets(TICKET2, port=8082) sess, ctx, _ = connect() - _, _, reused = connect(ctx, sess, port=7081) + _, _, reused = connect(ctx, sess, port=8081) assert not reused, 'not last ticket' - _, _, reused = connect(ctx, sess, port=7082) + _, _, reused = connect(ctx, sess, port=8082) assert reused, 'last ticket' - sess, ctx, _ = connect(port=7081) + sess, ctx, _ = connect(port=8081) _, _, reused = connect(ctx, sess) assert reused, 'first ticket' - sess, ctx, _ = connect(port=7082) + sess, ctx, _ = connect(port=8082) _, _, reused = connect(ctx, sess) assert reused, 'second ticket' assert 'success' in client.conf_delete( - 'listeners/*:7080/tls/session/tickets/0' + 'listeners/*:8080/tls/session/tickets/0' ), 'removed first ticket' assert 'success' in client.conf_post( - f'"{TICKET}"', 'listeners/*:7080/tls/session/tickets' + f'"{TICKET}"', 'listeners/*:8080/tls/session/tickets' ), 'add new ticket to the end of array' sess, ctx, _ = connect() - _, _, reused = connect(ctx, sess, port=7082) + _, _, reused = connect(ctx, sess, port=8082) assert not reused, 'not last ticket 2' - _, _, reused = connect(ctx, sess, port=7081) + _, _, reused = connect(ctx, sess, port=8081) assert reused, 'last ticket 2' @@ -188,7 +188,7 @@ def test_tls_ticket_invalid(): def check_tickets(tickets): assert 'error' in client.conf( {"tickets": tickets}, - 'listeners/*:7080/tls/session', + 'listeners/*:8080/tls/session', ) check_tickets({}) diff --git a/test/test_unix_abstract.py b/test/test_unix_abstract.py index 7ed2389c..6e304293 100644 --- a/test/test_unix_abstract.py +++ b/test/test_unix_abstract.py @@ -18,7 +18,7 @@ def test_unix_abstract_source(): assert 'success' in client.conf( { "listeners": { - "127.0.0.1:7080": {"pass": "routes"}, + "127.0.0.1:8080": {"pass": "routes"}, f"unix:@{addr[1:]}": {"pass": "routes"}, }, "routes": [ @@ -44,8 +44,8 @@ def test_unix_abstract_source(): def test_unix_abstract_client_ip(): def get_xff(xff, sock_type='ipv4'): address = { - 'ipv4': ('127.0.0.1', 7080), - 'ipv6': ('::1', 7081), + 'ipv4': ('127.0.0.1', 8080), + 'ipv6': ('::1', 8081), 'unix': ('\0sock', None), } (addr, port) = address[sock_type] @@ -61,14 +61,14 @@ def test_unix_abstract_client_ip(): assert 'success' in client.conf( { "listeners": { - "127.0.0.1:7080": { + "127.0.0.1:8080": { "client_ip": { "header": "X-Forwarded-For", "source": "unix", }, "pass": "applications/client_ip", }, - "[::1]:7081": { + "[::1]:8081": { "client_ip": { "header": "X-Forwarded-For", "source": "unix", diff --git a/test/test_upstreams_rr.py b/test/test_upstreams_rr.py index 046b5614..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 @@ -15,23 +16,23 @@ def setup_method_fixture(): assert 'success' in client.conf( { "listeners": { - "*:7080": {"pass": "upstreams/one"}, - "*:7090": {"pass": "upstreams/two"}, - "*:7081": {"pass": "routes/one"}, - "*:7082": {"pass": "routes/two"}, - "*:7083": {"pass": "routes/three"}, + "*:8080": {"pass": "upstreams/one"}, + "*:8090": {"pass": "upstreams/two"}, + "*:8081": {"pass": "routes/one"}, + "*:8082": {"pass": "routes/two"}, + "*:8083": {"pass": "routes/three"}, }, "upstreams": { "one": { "servers": { - "127.0.0.1:7081": {}, - "127.0.0.1:7082": {}, + "127.0.0.1:8081": {}, + "127.0.0.1:8082": {}, }, }, "two": { "servers": { - "127.0.0.1:7081": {}, - "127.0.0.1:7082": {}, + "127.0.0.1:8081": {}, + "127.0.0.1:8082": {}, }, }, }, @@ -47,7 +48,7 @@ def setup_method_fixture(): client.cpu_count = os.cpu_count() -def get_resps(req=100, port=7080): +def get_resps(req=100, port=8080): resps = [0] for _ in range(req): @@ -64,7 +65,7 @@ def get_resps(req=100, port=7080): return resps -def get_resps_sc(req=100, port=7080): +def get_resps_sc(req=100, port=8080): to_send = b"""GET / HTTP/1.1 Host: localhost @@ -96,14 +97,14 @@ def test_upstreams_rr_no_weight(): assert abs(resps[0] - resps[1]) <= client.cpu_count, 'no weight' assert 'success' in client.conf_delete( - 'upstreams/one/servers/127.0.0.1:7081' + 'upstreams/one/servers/127.0.0.1:8081' ), 'no weight server remove' resps = get_resps(req=50) assert resps[1] == 50, 'no weight 2' assert 'success' in client.conf( - {}, 'upstreams/one/servers/127.0.0.1:7081' + {}, 'upstreams/one/servers/127.0.0.1:8081' ), 'no weight server revert' resps = get_resps() @@ -111,7 +112,7 @@ def test_upstreams_rr_no_weight(): assert abs(resps[0] - resps[1]) <= client.cpu_count, 'no weight 3' assert 'success' in client.conf( - {}, 'upstreams/one/servers/127.0.0.1:7083' + {}, 'upstreams/one/servers/127.0.0.1:8083' ), 'no weight server new' resps = get_resps() @@ -126,7 +127,7 @@ def test_upstreams_rr_no_weight(): def test_upstreams_rr_weight(): assert 'success' in client.conf( - {"weight": 3}, 'upstreams/one/servers/127.0.0.1:7081' + {"weight": 3}, 'upstreams/one/servers/127.0.0.1:8081' ), 'configure weight' resps = get_resps_sc() @@ -134,14 +135,14 @@ def test_upstreams_rr_weight(): assert resps[1] == 25, 'weight 3 1' assert 'success' in client.conf_delete( - 'upstreams/one/servers/127.0.0.1:7081/weight' + 'upstreams/one/servers/127.0.0.1:8081/weight' ), 'configure weight remove' resps = get_resps_sc(req=10) assert resps[0] == 5, 'weight 0 0' assert resps[1] == 5, 'weight 0 1' assert 'success' in client.conf( - '1', 'upstreams/one/servers/127.0.0.1:7081/weight' + '1', 'upstreams/one/servers/127.0.0.1:8081/weight' ), 'configure weight 1' resps = get_resps_sc() @@ -150,8 +151,8 @@ def test_upstreams_rr_weight(): assert 'success' in client.conf( { - "127.0.0.1:7081": {"weight": 3}, - "127.0.0.1:7083": {"weight": 2}, + "127.0.0.1:8081": {"weight": 3}, + "127.0.0.1:8083": {"weight": 2}, }, 'upstreams/one/servers', ), 'configure weight 2' @@ -165,8 +166,8 @@ def test_upstreams_rr_weight_rational(): def set_weights(w1, w2): assert 'success' in client.conf( { - "127.0.0.1:7081": {"weight": w1}, - "127.0.0.1:7082": {"weight": w2}, + "127.0.0.1:8081": {"weight": w1}, + "127.0.0.1:8082": {"weight": w2}, }, 'upstreams/one/servers', ), 'configure weights' @@ -195,15 +196,15 @@ def test_upstreams_rr_weight_rational(): set_weights(0.25, 0.25) assert 'success' in client.conf_delete( - 'upstreams/one/servers/127.0.0.1:7081/weight' + 'upstreams/one/servers/127.0.0.1:8081/weight' ), 'delete weight' check_reqs(1, 0.25) assert 'success' in client.conf( { - "127.0.0.1:7081": {"weight": 0.1}, - "127.0.0.1:7082": {"weight": 1}, - "127.0.0.1:7083": {"weight": 0.9}, + "127.0.0.1:8081": {"weight": 0.1}, + "127.0.0.1:8082": {"weight": 1}, + "127.0.0.1:8083": {"weight": 0.9}, }, 'upstreams/one/servers', ), 'configure weights' @@ -221,7 +222,7 @@ def test_upstreams_rr_independent(): return sum_r - resps = get_resps_sc(req=30, port=7090) + resps = get_resps_sc(req=30, port=8090) assert resps[0] == 15, 'dep two before 0' assert resps[1] == 15, 'dep two before 1' @@ -230,10 +231,10 @@ def test_upstreams_rr_independent(): assert resps[1] == 15, 'dep one before 1' assert 'success' in client.conf( - '2', 'upstreams/two/servers/127.0.0.1:7081/weight' + '2', 'upstreams/two/servers/127.0.0.1:8081/weight' ), 'configure dep weight' - resps = get_resps_sc(req=30, port=7090) + resps = get_resps_sc(req=30, port=8090) assert resps[0] == 20, 'dep two 0' assert resps[1] == 10, 'dep two 1' @@ -242,13 +243,13 @@ def test_upstreams_rr_independent(): assert resps[1] == 15, 'dep one 1' assert 'success' in client.conf( - '1', 'upstreams/two/servers/127.0.0.1:7081/weight' + '1', 'upstreams/two/servers/127.0.0.1:8081/weight' ), 'configure dep weight 1' r_one, r_two = [0, 0], [0, 0] for _ in range(10): r_one = sum_resps(r_one, get_resps(req=10)) - r_two = sum_resps(r_two, get_resps(req=10, port=7090)) + r_two = sum_resps(r_two, get_resps(req=10, port=8090)) assert sum(r_one) == 100, 'dep one mix sum' assert abs(r_one[0] - r_one[1]) <= client.cpu_count, 'dep one mix' @@ -261,25 +262,25 @@ def test_upstreams_rr_delay(): assert 'success' in client.conf( { "listeners": { - "*:7080": {"pass": "upstreams/one"}, - "*:7081": {"pass": "routes"}, - "*:7082": {"pass": "routes"}, + "*:8080": {"pass": "upstreams/one"}, + "*:8081": {"pass": "routes"}, + "*:8082": {"pass": "routes"}, }, "upstreams": { "one": { "servers": { - "127.0.0.1:7081": {}, - "127.0.0.1:7082": {}, + "127.0.0.1:8081": {}, + "127.0.0.1:8082": {}, }, }, }, "routes": [ { - "match": {"destination": "*:7081"}, + "match": {"destination": "*:8081"}, "action": {"pass": "applications/delayed"}, }, { - "match": {"destination": "*:7082"}, + "match": {"destination": "*:8082"}, "action": {"return": 201}, }, ], @@ -351,14 +352,14 @@ Connection: close assert client.get()['body'] == '' assert 'success' in client.conf( - {"127.0.0.1:7083": {"weight": 2}}, + {"127.0.0.1:8083": {"weight": 2}}, 'upstreams/one/servers', ), 'active req new server' assert 'success' in client.conf_delete( - 'upstreams/one/servers/127.0.0.1:7083' + 'upstreams/one/servers/127.0.0.1:8083' ), 'active req server remove' assert 'success' in client.conf_delete( - 'listeners/*:7080' + 'listeners/*:8080' ), 'delete listener' assert 'success' in client.conf_delete( 'upstreams/one' @@ -377,7 +378,7 @@ Connection: close def test_upstreams_rr_bad_server(): assert 'success' in client.conf( - {"weight": 1}, 'upstreams/one/servers/127.0.0.1:7084' + {"weight": 1}, 'upstreams/one/servers/127.0.0.1:8084' ), 'configure bad server' resps = get_resps_sc(req=30) @@ -409,7 +410,7 @@ def test_upstreams_rr_unix(temp_dir): assert 'success' in client.conf( { - "*:7080": {"pass": "upstreams/one"}, + "*:8080": {"pass": "upstreams/one"}, f"unix:{addr_0}": {"pass": "routes/one"}, f"unix:{addr_1}": {"pass": "routes/two"}, }, @@ -430,15 +431,15 @@ def test_upstreams_rr_unix(temp_dir): def test_upstreams_rr_ipv6(): assert 'success' in client.conf( { - "*:7080": {"pass": "upstreams/one"}, - "[::1]:7081": {"pass": "routes/one"}, - "[::1]:7082": {"pass": "routes/two"}, + "*:8080": {"pass": "upstreams/one"}, + "[::1]:8081": {"pass": "routes/one"}, + "[::1]:8082": {"pass": "routes/two"}, }, 'listeners', ), 'configure listeners ipv6' assert 'success' in client.conf( - {"[::1]:7081": {}, "[::1]:7082": {}}, 'upstreams/one/servers' + {"[::1]:8081": {}, "[::1]:8082": {}}, 'upstreams/one/servers' ), 'configure servers ipv6' resps = get_resps_sc() @@ -454,13 +455,13 @@ def test_upstreams_rr_servers_empty(): assert client.get()['status'] == 502, 'servers empty' assert 'success' in client.conf( - {"127.0.0.1:7081": {"weight": 0}}, 'upstreams/one/servers' + {"127.0.0.1:8081": {"weight": 0}}, 'upstreams/one/servers' ), 'configure servers empty one' assert client.get()['status'] == 502, 'servers empty one' assert 'success' in client.conf( { - "127.0.0.1:7081": {"weight": 0}, - "127.0.0.1:7082": {"weight": 0}, + "127.0.0.1:8081": {"weight": 0}, + "127.0.0.1:8082": {"weight": 0}, }, 'upstreams/one/servers', ), 'configure servers empty two' @@ -474,12 +475,12 @@ def test_upstreams_rr_invalid(): {}, 'upstreams/one/servers/127.0.0.1' ), 'invalid address' assert 'error' in client.conf( - {}, 'upstreams/one/servers/127.0.0.1:7081/blah' + {}, 'upstreams/one/servers/127.0.0.1:8081/blah' ), 'invalid server option' def check_weight(w): assert 'error' in client.conf( - w, 'upstreams/one/servers/127.0.0.1:7081/weight' + w, 'upstreams/one/servers/127.0.0.1:8081/weight' ), 'invalid weight option' check_weight({}) 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 c9b173fa..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() @@ -16,17 +16,17 @@ client_python = ApplicationPython() def setup_method_fixture(): assert 'success' in client.conf( { - "listeners": {"*:7080": {"pass": "routes"}}, + "listeners": {"*:8080": {"pass": "routes"}}, "routes": [{"action": {"return": 200}}], }, ), '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,12 +127,12 @@ 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( { - "listeners": {"*:7080": {"pass": "routes"}}, + "listeners": {"*:8080": {"pass": "routes"}}, "routes": [ { "action": { @@ -163,7 +163,7 @@ def test_variables_host(search_in_file, wait_for_record): check_host('localhost') check_host('localhost1.', 'localhost1') - check_host('localhost2:7080', 'localhost2') + check_host('localhost2:8080', 'localhost2') check_host('.localhost') check_host('www.localhost') @@ -175,7 +175,7 @@ def test_variables_remote_addr(search_in_file, wait_for_record): assert wait_for_record(r'^127\.0\.0\.1$', 'access.log') is not None assert 'success' in client.conf( - {"[::1]:7080": {"pass": "routes"}}, 'listeners' + {"[::1]:8080": {"pass": "routes"}}, 'listeners' ) reg = r'^::1$' @@ -211,6 +211,26 @@ def test_variables_request_line(search_in_file, wait_for_record): assert wait_for_record(reg, 'access.log') is not None +def test_variables_request_id(search_in_file, wait_for_record, findall): + set_format('$uri $request_id $request_id') + + assert search_in_file(r'/request_id', 'access.log') is None + assert client.get(url='/request_id_1')['status'] == 200 + assert client.get(url='/request_id_2')['status'] == 200 + assert wait_for_record(r'/request_id_2', 'access.log') is not None + + id1 = findall( + r'^\/request_id_1 ([0-9a-f]{32}) ([0-9a-f]{32})$', 'access.log' + )[0] + id2 = findall( + r'^\/request_id_2 ([0-9a-f]{32}) ([0-9a-f]{32})$', 'access.log' + )[0] + + assert id1[0] == id1[1], 'same ids first' + assert id2[0] == id2[1], 'same ids second' + assert id1[0] != id2[0], 'first id != second id' + + def test_variables_status(search_in_file, wait_for_record): set_format('$status') @@ -423,11 +443,11 @@ 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( { - "listeners": {"*:7080": {"pass": "routes"}}, + "listeners": {"*:8080": {"pass": "routes"}}, "routes": [ { "action": { @@ -494,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 93e0738b..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 @@ -91,7 +91,7 @@ replace unit.nginx.org/go => {replace_path} ApplicationGo.prepare_env(script, name, static=static_build) conf = { - "listeners": {"*:7080": {"pass": f"applications/{script}"}}, + "listeners": {"*:8080": {"pass": f"applications/{script}"}}, "applications": { script: { "type": "external", diff --git a/test/unit/applications/lang/java.py b/test/unit/applications/lang/java.py index dc6d2bfc..351d04ce 100644 --- a/test/unit/applications/lang/java.py +++ b/test/unit/applications/lang/java.py @@ -53,7 +53,7 @@ class ApplicationJava(ApplicationProto): os.makedirs(classes_path) classpath = ( - f'{option.current_dir}/build/tomcat-servlet-api-9.0.82.jar' + f'{option.current_dir}/build/tomcat-servlet-api-9.0.86.jar' ) ws_jars = glob.glob( @@ -97,7 +97,7 @@ class ApplicationJava(ApplicationProto): script_path = f'{option.test_dir}/java/{script}/' self._load_conf( { - "listeners": {"*:7080": {"pass": f"applications/{script}"}}, + "listeners": {"*:8080": {"pass": f"applications/{script}"}}, "applications": { script: { "unit_jars": f'{option.current_dir}/build', diff --git a/test/unit/applications/lang/node.py b/test/unit/applications/lang/node.py index 4f18c780..ff95fbd5 100644 --- a/test/unit/applications/lang/node.py +++ b/test/unit/applications/lang/node.py @@ -44,7 +44,7 @@ class ApplicationNode(ApplicationProto): self._load_conf( { "listeners": { - "*:7080": {"pass": f"applications/{quote(script, '')}"} + "*:8080": {"pass": f"applications/{quote(script, '')}"} }, "applications": { script: { diff --git a/test/unit/applications/lang/perl.py b/test/unit/applications/lang/perl.py index 037e98e8..e99c2aca 100644 --- a/test/unit/applications/lang/perl.py +++ b/test/unit/applications/lang/perl.py @@ -11,7 +11,7 @@ class ApplicationPerl(ApplicationProto): self._load_conf( { - "listeners": {"*:7080": {"pass": f"applications/{script}"}}, + "listeners": {"*:8080": {"pass": f"applications/{script}"}}, "applications": { script: { "type": self.get_application_type(), diff --git a/test/unit/applications/lang/php.py b/test/unit/applications/lang/php.py index b9b6dbf1..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}' @@ -42,7 +41,7 @@ class ApplicationPHP(ApplicationProto): self._load_conf( { - "listeners": {"*:7080": {"pass": f"applications/{script}"}}, + "listeners": {"*:8080": {"pass": f"applications/{script}"}}, "applications": {script: app}, }, **kwargs, diff --git a/test/unit/applications/lang/python.py b/test/unit/applications/lang/python.py index 4e1fd897..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}' @@ -59,7 +58,7 @@ class ApplicationPython(ApplicationProto): self._load_conf( { "listeners": { - "*:7080": {"pass": f"applications/{quote(name, '')}"} + "*:8080": {"pass": f"applications/{quote(name, '')}"} }, "applications": {name: app}, }, diff --git a/test/unit/applications/lang/ruby.py b/test/unit/applications/lang/ruby.py index f6c4f6c3..1268f8c7 100644 --- a/test/unit/applications/lang/ruby.py +++ b/test/unit/applications/lang/ruby.py @@ -37,7 +37,7 @@ class ApplicationRuby(ApplicationProto): self._load_conf( { - "listeners": {"*:7080": {"pass": f"applications/{script}"}}, + "listeners": {"*:8080": {"pass": f"applications/{script}"}}, "applications": {script: app}, }, **kwargs, diff --git a/test/unit/applications/tls.py b/test/unit/applications/tls.py index e9bcc514..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 @@ -97,7 +97,7 @@ distinguished_name = req_distinguished_name script_path = f'{option.test_dir}/python/{script}' self._load_conf( { - "listeners": {"*:7080": {"pass": f"applications/{name}"}}, + "listeners": {"*:8080": {"pass": f"applications/{name}"}}, "applications": { name: { "type": "python", 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/chroot.py b/test/unit/check/chroot.py index b749fab6..466b6ba4 100644 --- a/test/unit/check/chroot.py +++ b/test/unit/check/chroot.py @@ -15,7 +15,7 @@ def check_chroot(): addr=f'{option.temp_dir}/control.unit.sock', body=json.dumps( { - "listeners": {"*:7080": {"pass": "routes"}}, + "listeners": {"*:8080": {"pass": "routes"}}, "routes": [ { "action": { diff --git a/test/unit/check/discover_available.py b/test/unit/check/discover_available.py index 0942581b..1383a0c3 100644 --- a/test/unit/check/discover_available.py +++ b/test/unit/check/discover_available.py @@ -18,6 +18,8 @@ def discover_available(unit): [unit['unitd'], '--version'], stderr=subprocess.STDOUT ).decode() + option.configure_flag['asan'] = '-fsanitize=address' in output_version + # wait for controller start if Log.wait_for_record(r'controller started') is None: diff --git a/test/unit/check/isolation.py b/test/unit/check/isolation.py index e4674f4d..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 @@ -21,7 +21,7 @@ def check_isolation(): ApplicationGo().prepare_env('empty', 'app') conf = { - "listeners": {"*:7080": {"pass": "applications/empty"}}, + "listeners": {"*:8080": {"pass": "applications/empty"}}, "applications": { "empty": { "type": "external", @@ -35,7 +35,7 @@ def check_isolation(): elif 'python' in available['modules']: conf = { - "listeners": {"*:7080": {"pass": "applications/empty"}}, + "listeners": {"*:8080": {"pass": "applications/empty"}}, "applications": { "empty": { "type": "python", @@ -50,7 +50,7 @@ def check_isolation(): elif 'php' in available['modules']: conf = { - "listeners": {"*:7080": {"pass": "applications/phpinfo"}}, + "listeners": {"*:8080": {"pass": "applications/phpinfo"}}, "applications": { "phpinfo": { "type": "php", @@ -67,7 +67,7 @@ def check_isolation(): ApplicationRuby().prepare_env('empty') conf = { - "listeners": {"*:7080": {"pass": "applications/empty"}}, + "listeners": {"*:8080": {"pass": "applications/empty"}}, "applications": { "empty": { "type": "ruby", @@ -83,7 +83,7 @@ def check_isolation(): ApplicationJava().prepare_env('empty') conf = { - "listeners": {"*:7080": {"pass": "applications/empty"}}, + "listeners": {"*:8080": {"pass": "applications/empty"}}, "applications": { "empty": { "unit_jars": f"{option.current_dir}/build", @@ -100,7 +100,7 @@ def check_isolation(): ApplicationNode().prepare_env('basic') conf = { - "listeners": {"*:7080": {"pass": "applications/basic"}}, + "listeners": {"*:8080": {"pass": "applications/basic"}}, "applications": { "basic": { "type": "external", @@ -114,7 +114,7 @@ def check_isolation(): elif 'perl' in available['modules']: conf = { - "listeners": {"*:7080": {"pass": "applications/body_empty"}}, + "listeners": {"*:8080": {"pass": "applications/body_empty"}}, "applications": { "body_empty": { "type": "perl", @@ -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 347382f5..9401501b 100644 --- a/test/unit/http.py +++ b/test/unit/http.py @@ -7,13 +7,14 @@ import select import socket import pytest + from unit.option import option class HTTP1: def http(self, start_str, **kwargs): sock_type = kwargs.get('sock_type', 'ipv4') - port = kwargs.get('port', 7080) + port = kwargs.get('port', 8080) url = kwargs.get('url', '/') http = 'HTTP/1.0' if 'http_10' in kwargs else 'HTTP/1.1' @@ -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/option.py b/test/unit/option.py index ee1f46dd..7c66c619 100644 --- a/test/unit/option.py +++ b/test/unit/option.py @@ -6,6 +6,7 @@ class Options: _options = { 'architecture': platform.architecture()[0], 'available': {'modules': {}, 'features': {}}, + 'configure_flag': {}, 'is_privileged': os.geteuid() == 0, 'skip_alerts': [], 'skip_sanitizer': False, 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 |