changeset 952:e9064d691790

Tests: converted tests to run in parallel.
author Andrey Zelenkov <zelenkov@nginx.com>
date Tue, 21 Jun 2016 16:39:13 +0300
parents 9361c7eddfc1
children 2bbab9bd73e5
files access.t access_log.t access_log_variables.t addition.t auth_basic.t auth_request.t auth_request_satisfy.t auth_request_set.t autoindex.t autoindex_format.t body.t body_chunked.t charset.t charset_gzip_static.t config_dump.t dav.t dav_chunked.t debug_connection.t debug_connection_syslog.t debug_connection_unix.t empty_gif.t error_log.t fastcgi.t fastcgi_body.t fastcgi_body2.t fastcgi_buffering.t fastcgi_cache.t fastcgi_header_params.t fastcgi_keepalive.t fastcgi_merge_params.t fastcgi_merge_params2.t fastcgi_request_buffering.t fastcgi_request_buffering_chunked.t fastcgi_split.t fastcgi_unix.t fastcgi_variables.t geo.t gunzip.t gunzip_memcached.t gunzip_perl.t gunzip_ssi.t gunzip_static.t gzip.t gzip_flush.t h2.t h2_cache.t h2_fastcgi_request_buffering.t h2_headers.t h2_limit_conn.t h2_limit_req.t h2_priority.t h2_proxy_protocol.t h2_proxy_request_buffering.t h2_proxy_request_buffering_ssl.t h2_proxy_ssl.t h2_request_body.t h2_server_tokens.t h2_ssl.t h2_ssl_verify_client.t h2_variables.t headers.t http_disable_symlinks.t http_error_page.t http_expect_100_continue.t http_host.t http_location.t http_location_auto.t http_location_win32.t http_resolver.t http_resolver_aaaa.t http_resolver_cname.t http_server_name.t http_try_files.t http_variables.t image_filter.t image_filter_finalize.t index.t js.t limit_conn.t limit_conn_complex.t limit_req.t mail_error_log.t mail_imap.t mail_imap_ssl.t mail_pop3.t mail_resolver.t mail_smtp.t mail_smtp_greeting_delay.t mail_smtp_xclient.t map.t map_complex.t memcached.t memcached_fake.t memcached_keepalive.t memcached_keepalive_stale.t mp4.t not_modified.t not_modified_proxy.t perl.t perl_gzip.t post_action.t proxy.t proxy_bind.t proxy_bind_transparent.t proxy_cache.t proxy_cache_bypass.t proxy_cache_chunked.t proxy_cache_convert_head.t proxy_cache_lock.t proxy_cache_lock_age.t proxy_cache_lock_ssi.t proxy_cache_path.t proxy_cache_range.t proxy_cache_revalidate.t proxy_cache_variables.t proxy_cache_vary.t proxy_chunked.t proxy_cookie.t proxy_force_ranges.t proxy_if.t proxy_keepalive.t proxy_limit_rate.t proxy_merge_headers.t proxy_next_upstream.t proxy_next_upstream_tries.t proxy_noclose.t proxy_non_idempotent.t proxy_pass_request.t proxy_protocol.t proxy_protocol_ipv6.t proxy_protocol_port.t proxy_redirect.t proxy_request_buffering.t proxy_request_buffering_chunked.t proxy_request_buffering_keepalive.t proxy_request_buffering_ssl.t proxy_set_body.t proxy_ssi_body.t proxy_ssl.t proxy_ssl_certificate.t proxy_ssl_keepalive.t proxy_ssl_name.t proxy_ssl_verify.t proxy_store.t proxy_unfinished.t proxy_unix.t proxy_upgrade.t proxy_upstream_cookie.t proxy_variables.t proxy_websocket.t proxy_xar.t random_index.t range.t range_charset.t range_flv.t range_if_range.t range_mp4.t realip.t realip_remote_addr.t realip_remote_port.t referer.t request_id.t rewrite.t rewrite_set.t rewrite_unescape.t scgi.t scgi_body.t scgi_cache.t scgi_gzip.t scgi_merge_params.t secure_link.t server_tokens.t slice.t split_clients.t ssi.t ssi_if.t ssi_include_big.t ssi_waited.t ssl.t ssl_certificate_chain.t ssl_certificates.t ssl_engine_keys.t ssl_password_file.t ssl_proxy_protocol.t ssl_proxy_upgrade.t ssl_sni.t ssl_sni_reneg.t ssl_sni_sessions.t ssl_verify_client.t stream_access.t stream_error_log.t stream_limit_conn.t stream_limit_rate.t stream_proxy.t stream_proxy_bind.t stream_proxy_next_upstream.t stream_proxy_protocol.t stream_proxy_protocol_ipv6.t stream_proxy_protocol_ssl.t stream_proxy_ssl.t stream_proxy_ssl_certificate.t stream_proxy_ssl_name.t stream_proxy_ssl_verify.t stream_ssl.t stream_tcp_nodelay.t stream_udp_limit_conn.t stream_udp_proxy.t stream_udp_upstream.t stream_udp_upstream_hash.t stream_udp_upstream_least_conn.t stream_unix.t stream_upstream.t stream_upstream_hash.t stream_upstream_least_conn.t stream_upstream_zone_ssl.t stub_status.t sub_filter.t sub_filter_merge.t sub_filter_multi.t sub_filter_multi2.t sub_filter_perl.t sub_filter_ssi.t syslog.t upstream.t upstream_hash.t upstream_hash_memcached.t upstream_ip_hash.t upstream_least_conn.t upstream_zone_ssl.t userid.t uwsgi.t xslt.t xslt_params.t
diffstat 233 files changed, 1661 insertions(+), 1627 deletions(-) [+]
line wrap: on
line diff
--- a/access.t
+++ b/access.t
@@ -38,15 +38,15 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         location /inet/ {
-            proxy_pass http://127.0.0.1:8081/;
+            proxy_pass http://127.0.0.1:%%PORT_1%%/;
         }
 
         location /inet6/ {
-            proxy_pass http://[::1]:8081/;
+            proxy_pass http://[::1]:%%PORT_1%%/;
         }
 
         location /unix/ {
@@ -56,8 +56,8 @@ http {
     }
 
     server {
-        listen       127.0.0.1:8081;
-        listen       [::1]:8081;
+        listen       127.0.0.1:%%PORT_1%%;
+        listen       [::1]:%%PORT_1%%;
         listen       unix:%%TESTDIR%%/unix.sock;
 
         location /allow_all {
--- a/access_log.t
+++ b/access_log.t
@@ -38,7 +38,7 @@ http {
     log_format binary $binary_remote_addr;
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         location /combined {
--- a/access_log_variables.t
+++ b/access_log_variables.t
@@ -43,7 +43,7 @@ http {
     log_format pipe          '$uri $pipe';
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         location /iso8601 {
--- a/addition.t
+++ b/addition.t
@@ -37,7 +37,7 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         location /regular {
--- a/auth_basic.t
+++ b/auth_basic.t
@@ -37,7 +37,7 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         location / {
--- a/auth_request.t
+++ b/auth_request.t
@@ -44,7 +44,7 @@ http {
                        keys_zone=NAME:1m;
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         location / {
@@ -94,7 +94,7 @@ http {
             auth_request /auth-proxy;
         }
         location = /auth-proxy {
-            proxy_pass http://127.0.0.1:8080/auth-basic;
+            proxy_pass http://127.0.0.1:%%PORT_0%%/auth-basic;
             proxy_pass_request_body off;
             proxy_set_header Content-Length "";
         }
@@ -104,17 +104,17 @@ http {
         }
 
         location = /proxy-double {
-            proxy_pass http://127.0.0.1:8080/auth-error;
+            proxy_pass http://127.0.0.1:%%PORT_0%%/auth-error;
             proxy_intercept_errors on;
             error_page 404 = /proxy-double-fallback;
             client_body_buffer_size 4k;
         }
         location = /proxy-double-fallback {
             auth_request /auth-proxy-double;
-            proxy_pass http://127.0.0.1:8080/auth-open;
+            proxy_pass http://127.0.0.1:%%PORT_0%%/auth-open;
         }
         location = /auth-proxy-double {
-            proxy_pass http://127.0.0.1:8080/auth-open;
+            proxy_pass http://127.0.0.1:%%PORT_0%%/auth-open;
             proxy_pass_request_body off;
             proxy_set_header Content-Length "";
         }
@@ -123,7 +123,7 @@ http {
             auth_request /auth-proxy-cache;
         }
         location = /auth-proxy-cache {
-            proxy_pass http://127.0.0.1:8080/auth-basic;
+            proxy_pass http://127.0.0.1:%%PORT_0%%/auth-basic;
             proxy_pass_request_body off;
             proxy_set_header Content-Length "";
             proxy_cache NAME;
@@ -134,7 +134,7 @@ http {
             auth_request /auth-fastcgi;
         }
         location = /auth-fastcgi {
-            fastcgi_pass 127.0.0.1:8081;
+            fastcgi_pass 127.0.0.1:%%PORT_1%%;
             fastcgi_pass_request_body off;
         }
     }
@@ -194,7 +194,7 @@ SKIP: {
 	skip 'win32', 2 if $^O eq 'MSWin32';
 
 	$t->run_daemon(\&fastcgi_daemon);
-	$t->waitforsocket('127.0.0.1:8081');
+	$t->waitforsocket('127.0.0.1:' . port(1));
 
 	like(http_get('/fastcgi'), qr/ 404 /, 'fastcgi auth open');
 	unlike(http_get('/fastcgi'), qr/INVISIBLE/, 'fastcgi auth no content');
@@ -239,7 +239,7 @@ sub http_post_big {
 ###############################################################################
 
 sub fastcgi_daemon {
-	my $socket = FCGI::OpenSocket('127.0.0.1:8081', 5);
+	my $socket = FCGI::OpenSocket('127.0.0.1:' . port(1), 5);
 	my $request = FCGI::Request(\*STDIN, \*STDOUT, \*STDERR, \%ENV,
 		$socket);
 
--- a/auth_request_satisfy.t
+++ b/auth_request_satisfy.t
@@ -38,7 +38,7 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         location / {
--- a/auth_request_set.t
+++ b/auth_request_set.t
@@ -37,7 +37,7 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         location = /t1.html {
@@ -80,7 +80,7 @@ http {
         location = /t5.html {
             auth_request /auth;
             auth_request_set $args "setargs";
-            proxy_pass http://127.0.0.1:8081/t5.html;
+            proxy_pass http://127.0.0.1:%%PORT_1%%/t5.html;
         }
 
         location = /t6.html {
@@ -89,15 +89,15 @@ http {
         }
 
         location = /auth {
-            proxy_pass http://127.0.0.1:8081;
+            proxy_pass http://127.0.0.1:%%PORT_1%%;
         }
         location = /auth2 {
-            proxy_pass http://127.0.0.1:8081;
+            proxy_pass http://127.0.0.1:%%PORT_1%%;
         }
     }
 
     server {
-        listen       127.0.0.1:8081;
+        listen       127.0.0.1:%%PORT_1%%;
         server_name  localhost;
 
         location = /auth {
--- a/autoindex.t
+++ b/autoindex.t
@@ -35,7 +35,7 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         location / {
--- a/autoindex_format.t
+++ b/autoindex_format.t
@@ -37,7 +37,7 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         autoindex on;
--- a/body.t
+++ b/body.t
@@ -37,12 +37,12 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     upstream u {
-        server 127.0.0.1:8082;
-        server 127.0.0.1:8080 backup;
+        server 127.0.0.1:%%PORT_2%%;
+        server 127.0.0.1:%%PORT_0%% backup;
     }
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         client_header_buffer_size 1k;
@@ -51,25 +51,25 @@ http {
             client_body_buffer_size 2k;
             add_header X-Body "$request_body";
             add_header X-Body-File "$request_body_file";
-            proxy_pass http://127.0.0.1:8081;
+            proxy_pass http://127.0.0.1:%%PORT_1%%;
         }
         location /b {
             client_body_buffer_size 2k;
             client_body_in_file_only on;
             add_header X-Body "$request_body";
             add_header X-Body-File "$request_body_file";
-            proxy_pass http://127.0.0.1:8081;
+            proxy_pass http://127.0.0.1:%%PORT_1%%;
         }
         location /small {
             client_body_in_file_only on;
             add_header X-Original-Uri "$request_uri";
-            proxy_pass http://127.0.0.1:8080/;
+            proxy_pass http://127.0.0.1:%%PORT_0%%/;
         }
         location /single {
             client_body_in_single_buffer on;
             add_header X-Body "$request_body";
             add_header X-Body-File "$request_body_file";
-            proxy_pass http://127.0.0.1:8081;
+            proxy_pass http://127.0.0.1:%%PORT_1%%;
         }
         location /discard {
             return 200 "TEST\n";
@@ -80,7 +80,7 @@ http {
     }
 
     server {
-        listen       127.0.0.1:8081;
+        listen       127.0.0.1:%%PORT_1%%;
         server_name  localhost;
 
         location / {
@@ -89,7 +89,7 @@ http {
     }
 
     server {
-        listen       127.0.0.1:8082;
+        listen       127.0.0.1:%%PORT_2%%;
         server_name  localhost;
 
         location / {
--- a/body_chunked.t
+++ b/body_chunked.t
@@ -37,12 +37,12 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     upstream u {
-        server 127.0.0.1:8082;
-        server 127.0.0.1:8080 backup;
+        server 127.0.0.1:%%PORT_2%%;
+        server 127.0.0.1:%%PORT_0%% backup;
     }
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         client_header_buffer_size 1k;
@@ -51,20 +51,20 @@ http {
             client_body_buffer_size 2k;
             add_header X-Body "$request_body";
             add_header X-Body-File "$request_body_file";
-            proxy_pass http://127.0.0.1:8081;
+            proxy_pass http://127.0.0.1:%%PORT_1%%;
         }
         location /b {
             client_body_buffer_size 2k;
             client_body_in_file_only on;
             add_header X-Body "$request_body";
             add_header X-Body-File "$request_body_file";
-            proxy_pass http://127.0.0.1:8081;
+            proxy_pass http://127.0.0.1:%%PORT_1%%;
         }
         location /single {
             client_body_in_single_buffer on;
             add_header X-Body "$request_body";
             add_header X-Body-File "$request_body_file";
-            proxy_pass http://127.0.0.1:8081;
+            proxy_pass http://127.0.0.1:%%PORT_1%%;
         }
         location /discard {
             return 200 "TEST\n";
@@ -75,7 +75,7 @@ http {
     }
 
     server {
-        listen       127.0.0.1:8081;
+        listen       127.0.0.1:%%PORT_1%%;
         server_name  localhost;
 
         location / {
@@ -84,7 +84,7 @@ http {
     }
 
     server {
-        listen       127.0.0.1:8082;
+        listen       127.0.0.1:%%PORT_2%%;
         server_name  localhost;
 
         location / {
--- a/charset.t
+++ b/charset.t
@@ -45,7 +45,7 @@ http {
     }
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         location / {
@@ -74,7 +74,7 @@ http {
         location /proxy/ {
             charset B;
             override_charset on;
-            proxy_pass http://127.0.0.1:8080/;
+            proxy_pass http://127.0.0.1:%%PORT_0%%/;
         }
     }
 }
--- a/charset_gzip_static.t
+++ b/charset_gzip_static.t
@@ -44,7 +44,7 @@ http {
     }
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         location /t1 {
@@ -64,21 +64,21 @@ http {
 
         location /p/ {
             charset utf-8;
-            proxy_pass http://127.0.0.1:8080/;
+            proxy_pass http://127.0.0.1:%%PORT_0%%/;
             proxy_http_version 1.1;
         }
 
         location /p.ab/ {
             charset A;
             source_charset B;
-            proxy_pass http://127.0.0.1:8080/;
+            proxy_pass http://127.0.0.1:%%PORT_0%%/;
             proxy_http_version 1.1;
         }
 
         location /p.aa/ {
             charset A;
             source_charset A;
-            proxy_pass http://127.0.0.1:8080/;
+            proxy_pass http://127.0.0.1:%%PORT_0%%/;
             proxy_http_version 1.1;
         }
     }
--- a/config_dump.t
+++ b/config_dump.t
@@ -48,11 +48,11 @@ http {
     }
 
     upstream u {
-        server 127.0.0.1:8081;
+        server 127.0.0.1:%%PORT_1%%;
     }
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         location / { }
--- a/dav.t
+++ b/dav.t
@@ -36,7 +36,7 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         location / {
--- a/dav_chunked.t
+++ b/dav_chunked.t
@@ -37,7 +37,7 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         client_header_buffer_size 1k;
--- a/debug_connection.t
+++ b/debug_connection.t
@@ -40,12 +40,12 @@ http {
     error_log %%TESTDIR%%/debug2.log alert;
 
     server {
-        listen       127.0.0.1:8080;
-        listen       [::1]:8080;
+        listen       127.0.0.1:%%PORT_0%%;
+        listen       [::1]:%%PORT_0%%;
         server_name  localhost;
 
         location /debug {
-            proxy_pass http://[::1]:8080/;
+            proxy_pass http://[::1]:%%PORT_0%%/;
         }
     }
 }
--- a/debug_connection_syslog.t
+++ b/debug_connection_syslog.t
@@ -36,16 +36,16 @@ events {
 http {
     %%TEST_GLOBALS_HTTP%%
 
-    error_log syslog:server=127.0.0.1:8080 alert;
-    error_log syslog:server=127.0.0.1:8081 alert;
+    error_log syslog:server=127.0.0.1:%%PORT_1_UDP%% alert;
+    error_log syslog:server=127.0.0.1:%%PORT_2_UDP%% alert;
 
     server {
-        listen       127.0.0.1:8080;
-        listen       [::1]:8080;
+        listen       127.0.0.1:%%PORT_0%%;
+        listen       [::1]:%%PORT_0%%;
         server_name  localhost;
 
         location /debug {
-            proxy_pass http://[::1]:8080/;
+            proxy_pass http://[::1]:%%PORT_0%%/;
         }
     }
 }
@@ -63,10 +63,10 @@ plan(skip_all => 'no inet6 support') if 
 
 ###############################################################################
 
-is(get_syslog('/', 8080), '', 'no debug_connection syslog 1');
-is(get_syslog('/', 8081), '', 'no debug_connection syslog 2');
+is(get_syslog('/', port(1)), '', 'no debug_connection syslog 1');
+is(get_syslog('/', port(2)), '', 'no debug_connection syslog 2');
 
-my @msgs = get_syslog('/debug', 8080, 8081);
+my @msgs = get_syslog('/debug', port(1), port(2));
 like($msgs[0], qr/\[debug\]/, 'debug_connection syslog 1');
 like($msgs[1], qr/\[debug\]/, 'debug_connection syslog 2');
 is($msgs[0], $msgs[1], 'debug_connection syslog1 syslog2 match');
--- a/debug_connection_unix.t
+++ b/debug_connection_unix.t
@@ -40,7 +40,7 @@ http {
     error_log %%TESTDIR%%/debug2.log alert;
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         listen       unix:%%TESTDIR%%/unix.sock;
         server_name  localhost;
 
--- a/empty_gif.t
+++ b/empty_gif.t
@@ -38,7 +38,7 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         location / {
--- a/error_log.t
+++ b/error_log.t
@@ -41,7 +41,7 @@ http {
     limit_req zone=one;
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         location /debug {
--- a/fastcgi.t
+++ b/fastcgi.t
@@ -39,15 +39,15 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     upstream u {
-        server 127.0.0.1:8081;
+        server 127.0.0.1:%%PORT_1%%;
     }
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         location / {
-            fastcgi_pass 127.0.0.1:8081;
+            fastcgi_pass 127.0.0.1:%%PORT_1%%;
             fastcgi_param REQUEST_URI $request_uri;
         }
 
@@ -61,7 +61,7 @@ http {
 EOF
 
 $t->run_daemon(\&fastcgi_daemon);
-$t->run()->waitforsocket('127.0.0.1:8081');
+$t->run()->waitforsocket('127.0.0.1:' . port(1));
 
 ###############################################################################
 
@@ -73,13 +73,14 @@ unlike(http_head('/'), qr/SEE-THIS/, 'no
 
 like(http_get('/stderr'), qr/SEE-THIS/, 'large stderr handled');
 
-like(http_get('/var?b=127.0.0.1:8081'), qr/SEE-THIS/, 'fastcgi with variables');
+like(http_get('/var?b=127.0.0.1:' . port(1)), qr/SEE-THIS/,
+	'fastcgi with variables');
 like(http_get('/var?b=u'), qr/SEE-THIS/, 'fastcgi with variables to upstream');
 
 ###############################################################################
 
 sub fastcgi_daemon {
-	my $socket = FCGI::OpenSocket('127.0.0.1:8081', 5);
+	my $socket = FCGI::OpenSocket('127.0.0.1:' . port(1), 5);
 	my $request = FCGI::Request(\*STDIN, \*STDOUT, \*STDERR, \%ENV,
 		$socket);
 
@@ -92,7 +93,7 @@ sub fastcgi_daemon {
 		}
 
 		print <<EOF;
-Location: http://127.0.0.1:8080/redirect
+Location: http://localhost/redirect
 Content-Type: text/html
 
 SEE-THIS
--- a/fastcgi_body.t
+++ b/fastcgi_body.t
@@ -35,11 +35,11 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         location / {
-            fastcgi_pass 127.0.0.1:8081;
+            fastcgi_pass 127.0.0.1:%%PORT_1%%;
             fastcgi_param REQUEST_URI $request_uri;
             fastcgi_param CONTENT_LENGTH $content_length;
         }
@@ -49,7 +49,7 @@ http {
 EOF
 
 $t->run_daemon(\&fastcgi_daemon);
-$t->run()->waitforsocket('127.0.0.1:8081');
+$t->run()->waitforsocket('127.0.0.1:' . port(1));
 
 ###############################################################################
 
@@ -141,7 +141,7 @@ sub fastcgi_respond($$$$) {
 sub fastcgi_daemon {
 	my $server = IO::Socket::INET->new(
 		Proto => 'tcp',
-		LocalAddr => '127.0.0.1:8081',
+		LocalAddr => '127.0.0.1:' . port(1),
 		Listen => 5,
 		Reuse => 1
 	)
@@ -176,7 +176,7 @@ sub fastcgi_daemon {
 
 		# respond
 		fastcgi_respond($client, $version, $id, <<EOF);
-Location: http://127.0.0.1:8080/redirect
+Location: http://localhost/redirect
 Content-Type: text/html
 X-Body: $body
 
--- a/fastcgi_body2.t
+++ b/fastcgi_body2.t
@@ -42,12 +42,12 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     upstream u {
-        server 127.0.0.1:8081 max_fails=0;
-        server 127.0.0.1:8082;
+        server 127.0.0.1:%%PORT_1%% max_fails=0;
+        server 127.0.0.1:%%PORT_2%%;
     }
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         location / {
@@ -71,12 +71,12 @@ http {
 
 EOF
 
-$t->run_daemon(\&fastcgi_daemon, 8081);
-$t->run_daemon(\&fastcgi_daemon, 8082);
+$t->run_daemon(\&fastcgi_daemon, port(1));
+$t->run_daemon(\&fastcgi_daemon, port(2));
 $t->run();
 
-$t->waitforsocket('127.0.0.1:8081');
-$t->waitforsocket('127.0.0.1:8082');
+$t->waitforsocket('127.0.0.1:' . port(1));
+$t->waitforsocket('127.0.0.1:' . port(2));
 
 ###############################################################################
 
@@ -116,10 +116,10 @@ sub fastcgi_daemon {
 		read(STDIN, my $body, $ENV{'CONTENT_LENGTH'});
 		my $len = length $body;
 
-		sleep 3 if $port == 8081;
+		sleep 3 if $port == port(1);
 
 		print <<EOF;
-Location: http://127.0.0.1:8080/redirect
+Location: http://localhost/redirect
 Content-Type: text/html
 X-Length: $len
 
--- a/fastcgi_buffering.t
+++ b/fastcgi_buffering.t
@@ -41,11 +41,11 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         location / {
-            fastcgi_pass 127.0.0.1:8081;
+            fastcgi_pass 127.0.0.1:%%PORT_1%%;
             fastcgi_param REQUEST_URI $request_uri;
             fastcgi_buffering off;
         }
@@ -64,7 +64,7 @@ EOF
 
 $t->run()->plan(2);
 
-$t->run_daemon(\&fastcgi_daemon)->waitforsocket('127.0.0.1:8081');
+$t->run_daemon(\&fastcgi_daemon)->waitforsocket('127.0.0.1:' . port(1));
 
 ###############################################################################
 
@@ -74,7 +74,7 @@ like(http_get('/inmemory.html'), qr/set:
 ###############################################################################
 
 sub fastcgi_daemon {
-	my $socket = FCGI::OpenSocket('127.0.0.1:8081', 5);
+	my $socket = FCGI::OpenSocket('127.0.0.1:' . port(1), 5);
 	my $request = FCGI::Request(\*STDIN, \*STDOUT, \*STDERR, \%ENV,
 		$socket);
 
--- a/fastcgi_cache.t
+++ b/fastcgi_cache.t
@@ -42,11 +42,11 @@ http {
                          keys_zone=NAME:1m;
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         location / {
-            fastcgi_pass 127.0.0.1:8081;
+            fastcgi_pass 127.0.0.1:%%PORT_1%%;
             fastcgi_param REQUEST_URI $request_uri;
             fastcgi_cache NAME;
             fastcgi_cache_key $request_uri;
@@ -58,7 +58,7 @@ http {
 EOF
 
 $t->run_daemon(\&fastcgi_daemon);
-$t->run()->waitforsocket('127.0.0.1:8081');
+$t->run()->waitforsocket('127.0.0.1:' . port(1));
 
 ###############################################################################
 
@@ -79,7 +79,7 @@ like(http_get('/stderr'), qr/SEE-THIS.*^
 ###############################################################################
 
 sub fastcgi_daemon {
-	my $socket = FCGI::OpenSocket('127.0.0.1:8081', 5);
+	my $socket = FCGI::OpenSocket('127.0.0.1:' . port(1), 5);
 	my $request = FCGI::Request(\*STDIN, \*STDOUT, \*STDERR, \%ENV,
 		$socket);
 
@@ -92,7 +92,7 @@ sub fastcgi_daemon {
 		}
 
 		print <<EOF;
-Location: http://127.0.0.1:8080/redirect
+Location: http://localhost/redirect
 Content-Type: text/html
 
 SEE-THIS
--- a/fastcgi_header_params.t
+++ b/fastcgi_header_params.t
@@ -39,11 +39,11 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         location / {
-            fastcgi_pass 127.0.0.1:8081;
+            fastcgi_pass 127.0.0.1:%%PORT_1%%;
             fastcgi_param HTTP_X_BLAH "blah";
         }
     }
@@ -52,7 +52,7 @@ http {
 EOF
 
 $t->run_daemon(\&fastcgi_daemon);
-$t->run()->waitforsocket('127.0.0.1:8081');
+$t->run()->waitforsocket('127.0.0.1:' . port(1));
 
 ###############################################################################
 
@@ -92,7 +92,7 @@ EOF
 ###############################################################################
 
 sub fastcgi_daemon {
-	my $socket = FCGI::OpenSocket('127.0.0.1:8081', 5);
+	my $socket = FCGI::OpenSocket('127.0.0.1:' . port(1), 5);
 	my $request = FCGI::Request(\*STDIN, \*STDOUT, \*STDERR, \%ENV,
 		$socket);
 
@@ -101,7 +101,7 @@ sub fastcgi_daemon {
 		$count++;
 
 		print <<EOF;
-Location: http://127.0.0.1:8080/redirect
+Location: http://localhost/redirect
 Content-Type: text/html
 
 SEE-THIS
--- a/fastcgi_keepalive.t
+++ b/fastcgi_keepalive.t
@@ -35,12 +35,12 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     upstream backend {
-        server 127.0.0.1:8081;
+        server 127.0.0.1:%%PORT_1%%;
         keepalive 1;
     }
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         location / {
@@ -53,7 +53,7 @@ http {
 EOF
 
 $t->run_daemon(\&fastcgi_test_daemon);
-$t->run()->waitforsocket('127.0.0.1:8081');
+$t->run()->waitforsocket('127.0.0.1:' . port(1));
 
 ###############################################################################
 
@@ -138,7 +138,7 @@ sub fastcgi_respond($$) {
 sub fastcgi_test_daemon {
 	my $server = IO::Socket::INET->new(
 		Proto => 'tcp',
-		LocalAddr => '127.0.0.1:8081',
+		LocalAddr => '127.0.0.1:' . port(1),
 		Listen => 5,
 		Reuse => 1
 	)
@@ -167,7 +167,7 @@ sub fastcgi_test_daemon {
 
 			# respond
 			fastcgi_respond($h, <<EOF);
-Location: http://localhost:8080/redirect
+Location: http://localhost/redirect
 Content-Type: text/html
 
 SEE-THIS
--- a/fastcgi_merge_params.t
+++ b/fastcgi_merge_params.t
@@ -46,22 +46,22 @@ http {
     fastcgi_param       HTTP_X_BLAH  "blah";
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         fastcgi_cache  NAME;
 
         location / {
-            fastcgi_pass    127.0.0.1:8081;
+            fastcgi_pass    127.0.0.1:%%PORT_1%%;
         }
 
         location /no/ {
-            fastcgi_pass    127.0.0.1:8081;
+            fastcgi_pass    127.0.0.1:%%PORT_1%%;
             fastcgi_cache   off;
         }
 
         location /custom/ {
-            fastcgi_pass    127.0.0.1:8081;
+            fastcgi_pass    127.0.0.1:%%PORT_1%%;
             fastcgi_param   HTTP_X_BLAH  "custom";
         }
     }
@@ -70,7 +70,7 @@ http {
 EOF
 
 $t->run_daemon(\&fastcgi_daemon);
-$t->run()->waitforsocket('127.0.0.1:8081');
+$t->run()->waitforsocket('127.0.0.1:' . port(1));
 
 ###############################################################################
 
@@ -112,7 +112,7 @@ EOF
 ###############################################################################
 
 sub fastcgi_daemon {
-	my $socket = FCGI::OpenSocket('127.0.0.1:8081', 5);
+	my $socket = FCGI::OpenSocket('127.0.0.1:' . port(1), 5);
 	my $request = FCGI::Request(\*STDIN, \*STDOUT, \*STDERR, \%ENV,
 		$socket);
 
@@ -125,7 +125,7 @@ sub fastcgi_daemon {
 		my $blah = $ENV{HTTP_X_BLAH};
 
 		print <<EOF;
-Location: http://127.0.0.1:8080/redirect
+Location: http://localhost/redirect
 Content-Type: text/html
 
 ims=$ims;iums=$iums;blah=$blah;
--- a/fastcgi_merge_params2.t
+++ b/fastcgi_merge_params2.t
@@ -46,17 +46,17 @@ http {
     # no fastcgi_param at all, cache switched on at server level
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         fastcgi_cache  NAME;
 
         location / {
-            fastcgi_pass    127.0.0.1:8081;
+            fastcgi_pass    127.0.0.1:%%PORT_1%%;
         }
 
         location /no/ {
-            fastcgi_pass    127.0.0.1:8081;
+            fastcgi_pass    127.0.0.1:%%PORT_1%%;
             fastcgi_cache   off;
         }
     }
@@ -65,7 +65,7 @@ http {
 EOF
 
 $t->run_daemon(\&fastcgi_daemon);
-$t->run()->waitforsocket('127.0.0.1:8081');
+$t->run()->waitforsocket('127.0.0.1:' . port(1));
 
 ###############################################################################
 
@@ -96,7 +96,7 @@ EOF
 ###############################################################################
 
 sub fastcgi_daemon {
-	my $socket = FCGI::OpenSocket('127.0.0.1:8081', 5);
+	my $socket = FCGI::OpenSocket('127.0.0.1:' . port(1), 5);
 	my $request = FCGI::Request(\*STDIN, \*STDOUT, \*STDERR, \%ENV,
 		$socket);
 
@@ -109,7 +109,7 @@ sub fastcgi_daemon {
 		my $blah = $ENV{HTTP_X_BLAH};
 
 		print <<EOF;
-Location: http://127.0.0.1:8080/redirect
+Location: http://localhost/redirect
 Content-Type: text/html
 
 ims=$ims;iums=$iums;blah=$blah;
--- a/fastcgi_request_buffering.t
+++ b/fastcgi_request_buffering.t
@@ -43,7 +43,7 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         client_header_buffer_size 1k;
@@ -53,17 +53,17 @@ http {
 
         location / {
             client_body_buffer_size 2k;
-            fastcgi_pass 127.0.0.1:8081;
+            fastcgi_pass 127.0.0.1:%%PORT_1%%;
         }
         location /single {
             client_body_in_single_buffer on;
-            fastcgi_pass 127.0.0.1:8081;
+            fastcgi_pass 127.0.0.1:%%PORT_1%%;
         }
         location /preread {
-            fastcgi_pass 127.0.0.1:8082;
+            fastcgi_pass 127.0.0.1:%%PORT_2%%;
         }
         location /error_page {
-            fastcgi_pass 127.0.0.1:8081;
+            fastcgi_pass 127.0.0.1:%%PORT_1%%;
             error_page 404 /404;
             fastcgi_intercept_errors on;
         }
@@ -76,7 +76,7 @@ http {
 EOF
 
 $t->run_daemon(\&fastcgi_daemon);
-$t->run()->waitforsocket('127.0.0.1:8081');
+$t->run()->waitforsocket('127.0.0.1:' . port(1));
 
 ###############################################################################
 
@@ -103,7 +103,7 @@ like(http_get_body('/', '0123456789' x 1
 
 # interactive tests
 
-my $s = get_body('/preread', 8082, 10);
+my $s = get_body('/preread', port(2), 10);
 ok($s, 'no preread');
 
 SKIP: {
@@ -116,7 +116,7 @@ like($s->{http_end}(), qr/200 OK/, 'no p
 
 }
 
-$s = get_body('/preread', 8082, 10, '01234');
+$s = get_body('/preread', port(2), 10, '01234');
 ok($s, 'preread');
 
 SKIP: {
@@ -341,7 +341,7 @@ sub log2c { Test::Nginx::log_core('||', 
 ###############################################################################
 
 sub fastcgi_daemon {
-	my $socket = FCGI::OpenSocket('127.0.0.1:8081', 5);
+	my $socket = FCGI::OpenSocket('127.0.0.1:' . port(1), 5);
 	my $request = FCGI::Request(\*STDIN, \*STDOUT, \*STDERR, \%ENV,
 		$socket);
 
@@ -358,7 +358,7 @@ sub fastcgi_daemon {
 		}
 
 		print <<EOF;
-Location: http://127.0.0.1:8080/redirect
+Location: http://localhost/redirect
 Content-Type: text/html
 X-Body: $body
 
--- a/fastcgi_request_buffering_chunked.t
+++ b/fastcgi_request_buffering_chunked.t
@@ -44,7 +44,7 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         client_header_buffer_size 1k;
@@ -53,17 +53,17 @@ http {
 
         location / {
             client_body_buffer_size 2k;
-            fastcgi_pass 127.0.0.1:8081;
+            fastcgi_pass 127.0.0.1:%%PORT_1%%;
         }
         location /single {
             client_body_in_single_buffer on;
-            fastcgi_pass 127.0.0.1:8081;
+            fastcgi_pass 127.0.0.1:%%PORT_1%%;
         }
         location /preread {
-            fastcgi_pass 127.0.0.1:8082;
+            fastcgi_pass 127.0.0.1:%%PORT_2%%;
         }
         location /error_page {
-            fastcgi_pass 127.0.0.1:8081;
+            fastcgi_pass 127.0.0.1:%%PORT_1%%;
             error_page 404 /404;
             fastcgi_intercept_errors on;
         }
@@ -76,7 +76,7 @@ http {
 EOF
 
 $t->run_daemon(\&fastcgi_daemon);
-$t->run()->waitforsocket('127.0.0.1:8081');
+$t->run()->waitforsocket('127.0.0.1:' . port(1));
 
 ###############################################################################
 
@@ -103,7 +103,7 @@ like(http_get_body('/', '0123456789' x 1
 
 # interactive tests
 
-my $s = get_body('/preread', 8082);
+my $s = get_body('/preread', port(2));
 ok($s, 'no preread');
 
 SKIP: {
@@ -116,7 +116,7 @@ like($s->{http_end}(), qr/200 OK/, 'no p
 
 }
 
-$s = get_body('/preread', 8082, '01234');
+$s = get_body('/preread', port(2), '01234');
 ok($s, 'preread');
 
 SKIP: {
@@ -129,7 +129,7 @@ like($s->{http_end}(), qr/200 OK/, 'prer
 
 }
 
-$s = get_body('/preread', 8082, '01234', many => 1);
+$s = get_body('/preread', port(2), '01234', many => 1);
 ok($s, 'chunks');
 
 SKIP: {
@@ -386,7 +386,7 @@ sub log2c { Test::Nginx::log_core('||', 
 ###############################################################################
 
 sub fastcgi_daemon {
-	my $socket = FCGI::OpenSocket('127.0.0.1:8081', 5);
+	my $socket = FCGI::OpenSocket('127.0.0.1:' . port(1), 5);
 	my $request = FCGI::Request(\*STDIN, \*STDOUT, \*STDERR, \%ENV,
 		$socket);
 
@@ -408,7 +408,7 @@ sub fastcgi_daemon {
 		}
 
 		print <<EOF;
-Location: http://127.0.0.1:8080/redirect
+Location: http://localhost/redirect
 Content-Type: text/html
 X-Body: $body
 
--- a/fastcgi_split.t
+++ b/fastcgi_split.t
@@ -42,12 +42,12 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     upstream u {
-        server 127.0.0.1:8081;
-        server 127.0.0.1:8082;
+        server 127.0.0.1:%%PORT_1%%;
+        server 127.0.0.1:%%PORT_2%%;
     }
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         location / {
@@ -60,13 +60,13 @@ http {
 
 EOF
 
-$t->run_daemon(\&fastcgi_daemon, 8081);
-$t->run_daemon(\&fastcgi_daemon, 8082);
+$t->run_daemon(\&fastcgi_daemon, port(1));
+$t->run_daemon(\&fastcgi_daemon, port(2));
 
 $t->run();
 
-$t->waitforsocket('127.0.0.1:8081');
-$t->waitforsocket('127.0.0.1:8082');
+$t->waitforsocket('127.0.0.1:' . port(1));
+$t->waitforsocket('127.0.0.1:' . port(2));
 
 ###############################################################################
 
@@ -84,10 +84,10 @@ sub fastcgi_daemon {
 	while( $request->Accept() >= 0 ) {
 		$count++;
 
-		if ($port == 8081) {
+		if ($port == port(1)) {
 			print 'BAD';
 		}
-		if ($port == 8082) {
+		if ($port == port(2)) {
 			print 'Good: header' . CRLF . CRLF;
 		}
 	}
--- a/fastcgi_unix.t
+++ b/fastcgi_unix.t
@@ -44,11 +44,11 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     upstream u {
-        server 127.0.0.1:8081;
+        server 127.0.0.1:%%PORT_1%%;
     }
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         location / {
@@ -105,7 +105,7 @@ sub fastcgi_daemon {
 		}
 
 		print <<EOF;
-Location: http://127.0.0.1:8080/redirect
+Location: http://localhost/redirect
 Content-Type: text/html
 
 SEE-THIS
--- a/fastcgi_variables.t
+++ b/fastcgi_variables.t
@@ -42,19 +42,19 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         add_header X-Script-Name $fastcgi_script_name;
         add_header X-Path-Info $fastcgi_path_info;
 
         location / {
-            fastcgi_pass 127.0.0.1:8081;
+            fastcgi_pass 127.0.0.1:%%PORT_1%%;
             fastcgi_index index.php;
         }
 
         location /info {
-            fastcgi_pass 127.0.0.1:8081;
+            fastcgi_pass 127.0.0.1:%%PORT_1%%;
             fastcgi_split_path_info ^(.+\.php)(.*)$;
         }
     }
@@ -63,7 +63,7 @@ http {
 EOF
 
 $t->run_daemon(\&fastcgi_daemon);
-$t->run()->waitforsocket('127.0.0.1:8081');
+$t->run()->waitforsocket('127.0.0.1:' . port(1));
 
 ###############################################################################
 
@@ -76,7 +76,7 @@ like(http_get('/info.php/path/info'), qr
 ###############################################################################
 
 sub fastcgi_daemon {
-	my $socket = FCGI::OpenSocket('127.0.0.1:8081', 5);
+	my $socket = FCGI::OpenSocket('127.0.0.1:' . port(1), 5);
 	my $request = FCGI::Request(\*STDIN, \*STDOUT, \*STDERR, \%ENV,
 		$socket);
 
--- a/geo.t
+++ b/geo.t
@@ -71,7 +71,7 @@ http {
     }
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         location / {
--- a/gunzip.t
+++ b/gunzip.t
@@ -40,12 +40,12 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
         location / {
             gunzip on;
             gzip_vary on;
-            proxy_pass http://127.0.0.1:8081/;
+            proxy_pass http://127.0.0.1:%%PORT_1%%/;
             proxy_set_header Accept-Encoding gzip;
         }
         location /error {
@@ -55,7 +55,7 @@ http {
     }
 
     server {
-        listen       127.0.0.1:8081;
+        listen       127.0.0.1:%%PORT_1%%;
         server_name  localhost;
 
         location / {
--- a/gunzip_memcached.t
+++ b/gunzip_memcached.t
@@ -42,14 +42,14 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         gunzip on;
 
         location / {
             set $memcached_key $uri;
-            memcached_pass 127.0.0.1:8081;
+            memcached_pass 127.0.0.1:%%PORT_1%%;
             memcached_gzip_flag 2;
         }
     }
@@ -62,24 +62,24 @@ my @memopts = ();
 
 if ($memhelp =~ /repcached/) {
 	# repcached patch adds additional listen socket
-	push @memopts, '-X', '8082';
+	push @memopts, '-X', port(2);
 }
 if ($memhelp =~ /-U/) {
 	# UDP port is on by default in memcached 1.2.7+
 	push @memopts, '-U', '0';
 }
 
-$t->run_daemon('memcached', '-l', '127.0.0.1', '-p', '8081', @memopts);
+$t->run_daemon('memcached', '-l', '127.0.0.1', '-p', port(1), @memopts);
 
 $t->run()->plan(2);
 
-$t->waitforsocket('127.0.0.1:8081')
+$t->waitforsocket('127.0.0.1:' . port(1))
 	or die "Can't start memcached";
 
 # Put compressed value into memcached.  This requires compress_threshold to be
 # set and compressed value to be at least 20% less than original one.
 
-my $memd = Cache::Memcached->new(servers => [ '127.0.0.1:8081' ],
+my $memd = Cache::Memcached->new(servers => [ '127.0.0.1:' . port(1) ],
 	compress_threshold => 1, connect_timeout => 1.0);
 $memd->set('/', 'TEST' x 10)
 	or die "can't put value into memcached: $!";
--- a/gunzip_perl.t
+++ b/gunzip_perl.t
@@ -38,7 +38,7 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         gunzip on;
--- a/gunzip_ssi.t
+++ b/gunzip_ssi.t
@@ -40,13 +40,13 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         location / {
             gunzip on;
             gzip_vary on;
-            proxy_pass http://127.0.0.1:8081/;
+            proxy_pass http://127.0.0.1:%%PORT_1%%/;
             proxy_set_header Accept-Encoding gzip;
         }
 
@@ -56,7 +56,7 @@ http {
     }
 
     server {
-        listen       127.0.0.1:8081;
+        listen       127.0.0.1:%%PORT_1%%;
         server_name  localhost;
 
         location / {
--- a/gunzip_static.t
+++ b/gunzip_static.t
@@ -40,7 +40,7 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
         location / {
             gunzip on;
--- a/gzip.t
+++ b/gzip.t
@@ -36,14 +36,14 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
         location / {
             gzip on;
         }
         location /proxy/ {
             gzip on;
-            proxy_pass http://127.0.0.1:8080/local/;
+            proxy_pass http://127.0.0.1:%%PORT_0%%/local/;
         }
         location /local/ {
             gzip off;
--- a/gzip_flush.t
+++ b/gzip_flush.t
@@ -35,7 +35,7 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         gzip on;
--- a/h2.t
+++ b/h2.t
@@ -44,8 +44,8 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen       127.0.0.1:8080 http2;
-        listen       127.0.0.1:8081;
+        listen       127.0.0.1:%%PORT_0%% http2;
+        listen       127.0.0.1:%%PORT_1%%;
         server_name  localhost;
 
         location / {
@@ -91,26 +91,26 @@ http {
     }
 
     server {
-        listen       127.0.0.1:8085 http2;
+        listen       127.0.0.1:%%PORT_2%% http2;
         server_name  localhost;
         return 200   first;
     }
 
     server {
-        listen       127.0.0.1:8085 http2;
+        listen       127.0.0.1:%%PORT_2%% http2;
         server_name  localhost2;
         return 200   second;
     }
 
     server {
-        listen       127.0.0.1:8086 http2;
+        listen       127.0.0.1:%%PORT_3%% http2;
         server_name  localhost;
 
         http2_max_concurrent_streams 1;
     }
 
     server {
-        listen       127.0.0.1:8089 http2;
+        listen       127.0.0.1:%%PORT_4%% http2;
         server_name  localhost;
 
         http2_recv_timeout 1s;
@@ -119,7 +119,7 @@ http {
     }
 
     server {
-        listen       127.0.0.1:8090 http2;
+        listen       127.0.0.1:%%PORT_5%% http2;
         server_name  localhost;
 
         http2_idle_timeout 1s;
@@ -127,26 +127,26 @@ http {
 
         location /proxy2/ {
             add_header X-Body $request_body;
-            proxy_pass http://127.0.0.1:8081/;
+            proxy_pass http://127.0.0.1:%%PORT_1%%/;
         }
     }
 
     server {
-        listen       127.0.0.1:8091 http2;
+        listen       127.0.0.1:%%PORT_6%% http2;
         server_name  localhost;
 
         send_timeout 1s;
     }
 
     server {
-        listen       127.0.0.1:8093 http2;
+        listen       127.0.0.1:%%PORT_7%% http2;
         server_name  localhost;
 
         client_header_timeout 1s;
         client_body_timeout 1s;
 
         location /proxy/ {
-            proxy_pass http://127.0.0.1:8081/;
+            proxy_pass http://127.0.0.1:%%PORT_1%%/;
         }
     }
 }
@@ -187,7 +187,7 @@ like($r, qr!Upgrade: h2c!, 'upgrade - to
 
 # SETTINGS
 
-my $s = Test::Nginx::HTTP2->new(8080, pure => 1);
+my $s = Test::Nginx::HTTP2->new(port(0), pure => 1);
 my $frames = $s->read(all => [
 	{ type => 'WINDOW_UPDATE' },
 	{ type => 'SETTINGS'}
@@ -229,11 +229,11 @@ is($frame->{sid}, 0, 'PING stream');
 SKIP: {
 skip 'long tests', 6 unless $ENV{TEST_NGINX_UNSAFE};
 
-push my @s, Test::Nginx::HTTP2->new(8089, pure => 1);
-push @s, Test::Nginx::HTTP2->new(8089, pure => 1);
+push my @s, Test::Nginx::HTTP2->new(port(4), pure => 1);
+push @s, Test::Nginx::HTTP2->new(port(4), pure => 1);
 $s[-1]->h2_ping('SEE-THIS');
-push @s, Test::Nginx::HTTP2->new(8090, pure => 1);
-push @s, Test::Nginx::HTTP2->new(8090, pure => 1);
+push @s, Test::Nginx::HTTP2->new(port(5), pure => 1);
+push @s, Test::Nginx::HTTP2->new(port(5), pure => 1);
 $s[-1]->h2_ping('SEE-THIS');
 
 select undef, undef, undef, 2.1;
@@ -497,7 +497,7 @@ is($frame->{headers}->{'location'}, 'tex
 
 ($frame) = grep { $_->{type} eq "HEADERS" } @$frames;
 is($frame->{headers}->{':status'}, 301, 'return 301 relative - status');
-is($frame->{headers}->{'location'}, 'http://localhost:8080/',
+is($frame->{headers}->{'location'}, 'http://localhost:' . port(0) . '/',
 	'return 301 relative - location');
 
 # return 301 with relative URI and ':authority' request header field
@@ -513,7 +513,7 @@ is($frame->{headers}->{'location'}, 'htt
 ($frame) = grep { $_->{type} eq "HEADERS" } @$frames;
 is($frame->{headers}->{':status'}, 301,
 	'return 301 relative - authority - status');
-is($frame->{headers}->{'location'}, 'http://localhost:8080/',
+is($frame->{headers}->{'location'}, 'http://localhost:' . port(0) . '/',
 	'return 301 relative - authority - location');
 
 # return 301 with relative URI and 'host' request header field
@@ -529,12 +529,12 @@ is($frame->{headers}->{'location'}, 'htt
 ($frame) = grep { $_->{type} eq "HEADERS" } @$frames;
 is($frame->{headers}->{':status'}, 301,
 	'return 301 relative - host - status');
-is($frame->{headers}->{'location'}, 'http://localhost:8080/',
+is($frame->{headers}->{'location'}, 'http://localhost:' . port(0) . '/',
 	'return 301 relative - host - location');
 
 # virtual host
 
-$s = Test::Nginx::HTTP2->new(8085);
+$s = Test::Nginx::HTTP2->new(port(2));
 $sid = $s->new_stream({ headers => [
 	{ name => ':method', value => 'GET', mode => 0 },
 	{ name => ':scheme', value => 'http', mode => 0 },
@@ -626,7 +626,7 @@ is($frame->{headers}->{'content-type'}, 
 TODO: {
 local $TODO = 'not yet' unless $t->has_version('1.9.12');
 
-$s = Test::Nginx::HTTP2->new(8093);
+$s = Test::Nginx::HTTP2->new(port(7));
 $sid = $s->new_stream({ path => '/t2.html', split => [35],
 	split_delay => 2.1 });
 $frames = $s->read(all => [{ type => 'RST_STREAM' }]);
@@ -648,7 +648,7 @@ ok($frame, 'client header timeout - PING
 TODO: {
 local $TODO = 'not yet' unless $t->has_version('1.9.12');
 
-$s = Test::Nginx::HTTP2->new(8093);
+$s = Test::Nginx::HTTP2->new(port(7));
 $sid = $s->new_stream({ path => '/proxy/t2.html', body_more => 1 });
 $s->h2_body('TEST', { split => [10], split_delay => 2.1 });
 $frames = $s->read(all => [{ type => 'RST_STREAM' }]);
@@ -829,7 +829,7 @@ is($frame->{headers}->{':status'}, 200, 
 
 # write event send timeout
 
-$s = Test::Nginx::HTTP2->new(8091);
+$s = Test::Nginx::HTTP2->new(port(6));
 $sid = $s->new_stream({ path => '/tbig.html' });
 $s->h2_window(2**30, $sid);
 $s->h2_window(2**30);
@@ -916,7 +916,7 @@ is($sum, 2**16 + 80, 'multiple - stream2
 
 # http2_max_concurrent_streams
 
-$s = Test::Nginx::HTTP2->new(8086, pure => 1);
+$s = Test::Nginx::HTTP2->new(port(3), pure => 1);
 $frames = $s->read(all => [{ type => 'SETTINGS' }]);
 
 ($frame) = grep { $_->{type} eq 'SETTINGS' } @$frames;
@@ -994,7 +994,7 @@ is($frame->{headers}->{':status'}, 200, 
 
 # invalid connection preface
 
-$s = Test::Nginx::HTTP2->new(8080, preface => 'x' x 16, pure => 1);
+$s = Test::Nginx::HTTP2->new(port(0), preface => 'x' x 16, pure => 1);
 $frames = $s->read(all => [{ type => 'GOAWAY' }]);
 
 ($frame) = grep { $_->{type} eq "GOAWAY" } @$frames;
@@ -1002,7 +1002,7 @@ ok($frame, 'invalid preface - GOAWAY fra
 is($frame->{code}, 1, 'invalid preface - error code');
 
 my $preface = 'PRI * HTTP/2.0' . CRLF . CRLF . 'x' x 8;
-$s = Test::Nginx::HTTP2->new(8080, preface => $preface, pure => 1);
+$s = Test::Nginx::HTTP2->new(port(0), preface => $preface, pure => 1);
 $frames = $s->read(all => [{ type => 'GOAWAY' }]);
 
 ($frame) = grep { $_->{type} eq "GOAWAY" } @$frames;
@@ -1073,24 +1073,24 @@ is($frame->{value}, 'SEE-THIS', 'unknown
 
 # graceful shutdown with stream waiting on HEADERS payload
 
-my $grace = Test::Nginx::HTTP2->new(8089);
+my $grace = Test::Nginx::HTTP2->new(port(4));
 $grace->new_stream({ split => [ 9 ], abort => 1 });
 
 # graceful shutdown with stream waiting on WINDOW_UPDATE
 
-my $grace2 = Test::Nginx::HTTP2->new(8089);
+my $grace2 = Test::Nginx::HTTP2->new(port(4));
 $sid = $grace2->new_stream({ path => '/t1.html' });
 $grace2->read(all => [{ sid => $sid, length => 2**16 - 1 }]);
 
 # graceful shutdown waiting on incomplete request body DATA frames
 
-my $grace3 = Test::Nginx::HTTP2->new(8090);
+my $grace3 = Test::Nginx::HTTP2->new(port(5));
 $sid = $grace3->new_stream({ path => '/proxy2/t2.html', body_more => 1 });
 $grace3->h2_body('TEST', { body_more => 1 });
 
 # partial request body data frame with connection close after body timeout
 
-my $grace4 = Test::Nginx::HTTP2->new(8093);
+my $grace4 = Test::Nginx::HTTP2->new(port(7));
 $sid = $grace4->new_stream({ path => '/proxy/t2.html', body_more => 1 });
 $grace4->h2_body('TEST', { split => [ 12 ], abort => 1 });
 
--- a/h2_cache.t
+++ b/h2_cache.t
@@ -39,17 +39,17 @@ http {
     proxy_cache_path %%TESTDIR%%/cache    keys_zone=NAME:1m;
 
     server {
-        listen       127.0.0.1:8080 http2;
-        listen       127.0.0.1:8081;
+        listen       127.0.0.1:%%PORT_0%% http2;
+        listen       127.0.0.1:%%PORT_1%%;
         server_name  localhost;
 
         location /cache {
-            proxy_pass http://127.0.0.1:8081/;
+            proxy_pass http://127.0.0.1:%%PORT_1%%/;
             proxy_cache NAME;
             proxy_cache_valid 1m;
         }
         location /proxy_buffering_off {
-            proxy_pass http://127.0.0.1:8081/;
+            proxy_pass http://127.0.0.1:%%PORT_1%%/;
             proxy_cache NAME;
             proxy_cache_valid 1m;
             proxy_buffering off;
--- a/h2_fastcgi_request_buffering.t
+++ b/h2_fastcgi_request_buffering.t
@@ -38,12 +38,12 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen       127.0.0.1:8080 http2;
+        listen       127.0.0.1:%%PORT_0%% http2;
         server_name  localhost;
 
         location / {
             fastcgi_request_buffering off;
-            fastcgi_pass 127.0.0.1:8081;
+            fastcgi_pass 127.0.0.1:%%PORT_1%%;
             fastcgi_param REQUEST_URI $request_uri;
             client_body_buffer_size 1k;
         }
@@ -190,7 +190,7 @@ sub get_body {
 	$server = IO::Socket::INET->new(
 		Proto => 'tcp',
 		LocalHost => '127.0.0.1',
-		LocalPort => 8081,
+		LocalPort => port(1),
 		Listen => 5,
 		Timeout => 3,
 		Reuse => 1
--- a/h2_headers.t
+++ b/h2_headers.t
@@ -38,9 +38,9 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen       127.0.0.1:8080 http2;
-        listen       127.0.0.1:8081;
-        listen       127.0.0.1:8082 http2 sndbuf=128;
+        listen       127.0.0.1:%%PORT_0%% http2;
+        listen       127.0.0.1:%%PORT_1%%;
+        listen       127.0.0.1:%%PORT_2%% http2 sndbuf=128;
         server_name  localhost;
 
         http2_max_field_size 128k;
@@ -70,12 +70,12 @@ http {
         location /proxy/ {
             add_header X-UC-a $upstream_cookie_a;
             add_header X-UC-c $upstream_cookie_c;
-            proxy_pass http://127.0.0.1:8083/;
+            proxy_pass http://127.0.0.1:%%PORT_3%%/;
             proxy_set_header X-Cookie-a $cookie_a;
             proxy_set_header X-Cookie-c $cookie_c;
         }
         location /proxy2/ {
-            proxy_pass http://127.0.0.1:8081/;
+            proxy_pass http://127.0.0.1:%%PORT_1%%/;
         }
         location /set-cookie {
             add_header Set-Cookie a=b;
@@ -91,14 +91,14 @@ http {
     }
 
     server {
-        listen       127.0.0.1:8084 http2;
+        listen       127.0.0.1:%%PORT_4%% http2;
         server_name  localhost;
 
         http2_max_field_size 22;
     }
 
     server {
-        listen       127.0.0.1:8085 http2;
+        listen       127.0.0.1:%%PORT_5%% http2;
         server_name  localhost;
 
         http2_max_header_size 64;
@@ -113,7 +113,7 @@ open OLDERR, ">&", \*STDERR; close STDER
 $t->run();
 open STDERR, ">&", \*OLDERR;
 
-$t->waitforsocket('127.0.0.1:8083');
+$t->waitforsocket('127.0.0.1:' . port(3));
 
 # file size is slightly beyond initial window size: 2**16 + 80 bytes
 
@@ -660,7 +660,7 @@ cmp_ok($data[-1], '<=', 2**14, 'response
 TODO: {
 local $TODO = 'not yet' unless $t->has_version('1.9.7');
 
-$s = Test::Nginx::HTTP2->new(8082);
+$s = Test::Nginx::HTTP2->new(port(2));
 $s->h2_settings(0, 0x5 => 2**17);
 
 $sid = $s->new_stream({ path => '/frame_size?h=' . 'x' x 2**15 });
@@ -679,7 +679,7 @@ is(length join('', @{$frame->{headers}->
 
 # response header block split and sent in parts
 
-$s = Test::Nginx::HTTP2->new(8082);
+$s = Test::Nginx::HTTP2->new(port(2));
 $sid = $s->new_stream({ path => '/continuation?h=' . 'x' x 2**15 });
 $frames = $s->read(all => [{ sid => $sid, fin => 0x4 }]);
 
@@ -694,7 +694,7 @@ is(length join('', @{@$frames[-1]->{head
 
 # max_field_size - header field name
 
-$s = Test::Nginx::HTTP2->new(8084);
+$s = Test::Nginx::HTTP2->new(port(4));
 $sid = $s->new_stream({ headers => [
 	{ name => ':method', value => 'GET', mode => 0 },
 	{ name => ':scheme', value => 'http', mode => 0 },
@@ -717,7 +717,7 @@ ok($frame, 'field name size less');
 ($frame) = grep { $_->{type} eq 'DATA' } @$frames;
 ok($frame, 'field name size second');
 
-$s = Test::Nginx::HTTP2->new(8084);
+$s = Test::Nginx::HTTP2->new(port(4));
 $sid = $s->new_stream({ headers => [
 	{ name => ':method', value => 'GET', mode => 0 },
 	{ name => ':scheme', value => 'http', mode => 0 },
@@ -729,7 +729,7 @@ ok($frame, 'field name size second');
 ($frame) = grep { $_->{type} eq 'DATA' } @$frames;
 ok($frame, 'field name size equal');
 
-$s = Test::Nginx::HTTP2->new(8084);
+$s = Test::Nginx::HTTP2->new(port(4));
 $sid = $s->new_stream({ headers => [
 	{ name => ':method', value => 'GET', mode => 0 },
 	{ name => ':scheme', value => 'http', mode => 0 },
@@ -743,7 +743,7 @@ is($frame, undef, 'field name size great
 
 # max_field_size - header field value
 
-$s = Test::Nginx::HTTP2->new(8084);
+$s = Test::Nginx::HTTP2->new(port(4));
 $sid = $s->new_stream({ headers => [
 	{ name => ':method', value => 'GET', mode => 0 },
 	{ name => ':scheme', value => 'http', mode => 0 },
@@ -755,7 +755,7 @@ is($frame, undef, 'field name size great
 ($frame) = grep { $_->{type} eq 'DATA' } @$frames;
 ok($frame, 'field value size less');
 
-$s = Test::Nginx::HTTP2->new(8084);
+$s = Test::Nginx::HTTP2->new(port(4));
 $sid = $s->new_stream({ headers => [
 	{ name => ':method', value => 'GET', mode => 0 },
 	{ name => ':scheme', value => 'http', mode => 0 },
@@ -767,7 +767,7 @@ ok($frame, 'field value size less');
 ($frame) = grep { $_->{type} eq 'DATA' } @$frames;
 ok($frame, 'field value size equal');
 
-$s = Test::Nginx::HTTP2->new(8084);
+$s = Test::Nginx::HTTP2->new(port(4));
 $sid = $s->new_stream({ headers => [
 	{ name => ':method', value => 'GET', mode => 0 },
 	{ name => ':scheme', value => 'http', mode => 0 },
@@ -781,7 +781,7 @@ is($frame, undef, 'field value size grea
 
 # max_header_size
 
-$s = Test::Nginx::HTTP2->new(8085);
+$s = Test::Nginx::HTTP2->new(port(5));
 $sid = $s->new_stream({ headers => [
 	{ name => ':method', value => 'GET', mode => 0 },
 	{ name => ':scheme', value => 'http', mode => 0 },
@@ -804,7 +804,7 @@ ok($frame, 'header size less');
 ($frame) = grep { $_->{type} eq 'DATA' } @$frames;
 ok($frame, 'header size second');
 
-$s = Test::Nginx::HTTP2->new(8085);
+$s = Test::Nginx::HTTP2->new(port(5));
 $sid = $s->new_stream({ headers => [
 	{ name => ':method', value => 'GET', mode => 0 },
 	{ name => ':scheme', value => 'http', mode => 0 },
@@ -816,7 +816,7 @@ ok($frame, 'header size second');
 ($frame) = grep { $_->{type} eq 'DATA' } @$frames;
 ok($frame, 'header size equal');
 
-$s = Test::Nginx::HTTP2->new(8085);
+$s = Test::Nginx::HTTP2->new(port(5));
 $sid = $s->new_stream({ headers => [
 	{ name => ':method', value => 'GET', mode => 0 },
 	{ name => ':scheme', value => 'http', mode => 0 },
@@ -831,7 +831,7 @@ is($frame, undef, 'header size greater')
 # header size is based on (decompressed) header list
 # two extra 1-byte indices would otherwise fit in max_header_size
 
-$s = Test::Nginx::HTTP2->new(8085);
+$s = Test::Nginx::HTTP2->new(port(5));
 $sid = $s->new_stream({ headers => [
 	{ name => ':method', value => 'GET', mode => 0 },
 	{ name => ':scheme', value => 'http', mode => 0 },
@@ -1013,7 +1013,7 @@ sub http_daemon {
 	my $server = IO::Socket::INET->new(
 		Proto => 'tcp',
 		LocalHost => '127.0.0.1',
-		LocalPort => 8083,
+		LocalPort => port(3),
 		Listen => 5,
 		Reuse => 1
 	)
--- a/h2_limit_conn.t
+++ b/h2_limit_conn.t
@@ -39,7 +39,7 @@ http {
     limit_conn_zone  $binary_remote_addr  zone=conn:1m;
 
     server {
-        listen       127.0.0.1:8080 http2;
+        listen       127.0.0.1:%%PORT_0%% http2;
         server_name  localhost;
 
         location /t.html {
--- a/h2_limit_req.t
+++ b/h2_limit_req.t
@@ -43,8 +43,8 @@ http {
     limit_req_zone   $binary_remote_addr  zone=req:1m rate=1r/s;
 
     server {
-        listen       127.0.0.1:8080 http2;
-        listen       127.0.0.1:8081;
+        listen       127.0.0.1:%%PORT_0%% http2;
+        listen       127.0.0.1:%%PORT_1%%;
         server_name  localhost;
 
         location / { }
@@ -56,7 +56,7 @@ http {
             add_header X-Body $request_body;
             add_header X-Body-File $request_body_file;
             client_body_in_file_only on;
-            proxy_pass http://127.0.0.1:8081/;
+            proxy_pass http://127.0.0.1:%%PORT_1%%/;
             limit_req  zone=req burst=2;
         }
     }
--- a/h2_priority.t
+++ b/h2_priority.t
@@ -37,7 +37,7 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen       127.0.0.1:8080 http2;
+        listen       127.0.0.1:%%PORT_0%% http2;
         server_name  localhost;
     }
 }
--- a/h2_proxy_protocol.t
+++ b/h2_proxy_protocol.t
@@ -39,7 +39,7 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen       127.0.0.1:8081 proxy_protocol http2;
+        listen       127.0.0.1:%%PORT_0%% proxy_protocol http2;
         server_name  localhost;
 
         location /pp {
@@ -59,7 +59,7 @@ EOF
 ###############################################################################
 
 my $proxy = 'PROXY TCP4 192.0.2.1 192.0.2.2 1234 5678' . CRLF;
-my $s = Test::Nginx::HTTP2->new(8081, proxy => $proxy);
+my $s = Test::Nginx::HTTP2->new(port(0), proxy => $proxy);
 my $sid = $s->new_stream({ path => '/pp' });
 my $frames = $s->read(all => [{ sid => $sid, fin => 1 }]);
 
@@ -70,7 +70,7 @@ is($frame->{headers}->{'x-pp'}, '192.0.2
 # invalid PROXY protocol string
 
 $proxy = 'BOGUS TCP4 192.0.2.1 192.0.2.2 1234 5678' . CRLF;
-$s = Test::Nginx::HTTP2->new(8081, preface => $proxy, pure => 1);
+$s = Test::Nginx::HTTP2->new(port(0), preface => $proxy, pure => 1);
 $frames = $s->read(all => [{ type => 'GOAWAY' }]);
 
 ($frame) = grep { $_->{type} eq "GOAWAY" } @$frames;
--- a/h2_proxy_request_buffering.t
+++ b/h2_proxy_request_buffering.t
@@ -40,18 +40,18 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen       127.0.0.1:8080 http2;
+        listen       127.0.0.1:%%PORT_0%% http2;
         server_name  localhost;
 
         location / {
             proxy_request_buffering off;
-            proxy_pass http://127.0.0.1:8081/;
+            proxy_pass http://127.0.0.1:%%PORT_1%%/;
             client_body_buffer_size 1k;
         }
         location /chunked {
             proxy_request_buffering off;
             proxy_http_version 1.1;
-            proxy_pass http://127.0.0.1:8081/;
+            proxy_pass http://127.0.0.1:%%PORT_1%%/;
             client_body_buffer_size 1k;
         }
     }
@@ -169,7 +169,7 @@ sub get_body {
 	$server = IO::Socket::INET->new(
 		Proto => 'tcp',
 		LocalHost => '127.0.0.1',
-		LocalPort => 8081,
+		LocalPort => port(1),
 		Listen => 5,
 		Timeout => 3,
 		Reuse => 1
--- a/h2_proxy_request_buffering_ssl.t
+++ b/h2_proxy_request_buffering_ssl.t
@@ -41,24 +41,24 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen       127.0.0.1:8080 http2;
+        listen       127.0.0.1:%%PORT_0%% http2;
         server_name  localhost;
 
         location / {
             proxy_request_buffering off;
-            proxy_pass https://127.0.0.1:8082;
+            proxy_pass https://127.0.0.1:%%PORT_2%%;
             client_body_buffer_size 512;
         }
         location /chunked {
             proxy_request_buffering off;
             proxy_http_version 1.1;
-            proxy_pass https://127.0.0.1:8082;
+            proxy_pass https://127.0.0.1:%%PORT_2%%;
             client_body_buffer_size 512;
         }
     }
 
     server {
-        listen       127.0.0.1:8082 ssl;
+        listen       127.0.0.1:%%PORT_2%% ssl;
         server_name  localhost;
 
         ssl_certificate_key localhost.key;
@@ -66,13 +66,13 @@ http {
 
         location / {
             proxy_request_buffering off;
-            proxy_pass http://127.0.0.1:8081/;
+            proxy_pass http://127.0.0.1:%%PORT_1%%/;
             client_body_buffer_size 1k;
         }
         location /chunked {
             proxy_request_buffering off;
             proxy_http_version 1.1;
-            proxy_pass http://127.0.0.1:8081/;
+            proxy_pass http://127.0.0.1:%%PORT_1%%/;
             client_body_buffer_size 1k;
         }
     }
@@ -194,7 +194,7 @@ sub get_body {
 	$server = IO::Socket::INET->new(
 		Proto => 'tcp',
 		LocalHost => '127.0.0.1',
-		LocalPort => 8081,
+		LocalPort => port(1),
 		Listen => 5,
 		Timeout => 3,
 		Reuse => 1
--- a/h2_proxy_ssl.t
+++ b/h2_proxy_ssl.t
@@ -41,8 +41,8 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen       127.0.0.1:8080 http2;
-        listen       127.0.0.1:8081 ssl;
+        listen       127.0.0.1:%%PORT_0%% http2;
+        listen       127.0.0.1:%%PORT_1%% ssl;
         server_name  localhost;
 
         ssl_certificate_key localhost.key;
@@ -50,7 +50,7 @@ http {
 
         location / { }
         location /proxy_ssl/ {
-            proxy_pass https://127.0.0.1:8081/;
+            proxy_pass https://127.0.0.1:%%PORT_1%%/;
         }
     }
 }
--- a/h2_request_body.t
+++ b/h2_request_body.t
@@ -40,8 +40,8 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen       127.0.0.1:8080 http2;
-        listen       127.0.0.1:8081;
+        listen       127.0.0.1:%%PORT_0%% http2;
+        listen       127.0.0.1:%%PORT_1%%;
         server_name  localhost;
 
         location / { }
@@ -49,14 +49,14 @@ http {
             add_header X-Body $request_body;
             add_header X-Body-File $request_body_file;
             client_body_in_file_only on;
-            proxy_pass http://127.0.0.1:8081/;
+            proxy_pass http://127.0.0.1:%%PORT_1%%/;
         }
         location /client_max_body_size {
             add_header X-Body $request_body;
             add_header X-Body-File $request_body_file;
             client_body_in_single_buffer on;
             client_body_in_file_only on;
-            proxy_pass http://127.0.0.1:8081/;
+            proxy_pass http://127.0.0.1:%%PORT_1%%/;
             client_max_body_size 10;
         }
     }
--- a/h2_server_tokens.t
+++ b/h2_server_tokens.t
@@ -37,7 +37,7 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen       127.0.0.1:8080 http2;
+        listen       127.0.0.1:%%PORT_0%% http2;
         server_name  localhost;
 
         location /200 {
--- a/h2_ssl.t
+++ b/h2_ssl.t
@@ -44,7 +44,7 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen       127.0.0.1:8081 http2 ssl;
+        listen       127.0.0.1:%%PORT_0%% http2 ssl;
         server_name  localhost;
 
         ssl_certificate_key localhost.key;
@@ -99,7 +99,7 @@ SKIP: {
 eval { IO::Socket::SSL->can_npn() or die; };
 skip 'OpenSSL NPN support required', 1 if $@;
 
-$s = Test::Nginx::HTTP2->new(8081, SSL => 1, npn => 'h2');
+$s = Test::Nginx::HTTP2->new(port(0), SSL => 1, npn => 'h2');
 $sid = $s->new_stream({ path => '/h2' });
 $frames = $s->read(all => [{ sid => $sid, fin => 1 }]);
 
@@ -114,7 +114,7 @@ SKIP: {
 eval { IO::Socket::SSL->can_alpn() or die; };
 skip 'OpenSSL ALPN support required', 1 if $@;
 
-$s = Test::Nginx::HTTP2->new(8081, SSL => 1, alpn => 'h2');
+$s = Test::Nginx::HTTP2->new(port(0), SSL => 1, alpn => 'h2');
 $sid = $s->new_stream({ path => '/h2' });
 $frames = $s->read(all => [{ sid => $sid, fin => 1 }]);
 
@@ -129,7 +129,7 @@ SKIP: {
 eval { IO::Socket::SSL->can_npn() or die; };
 skip 'OpenSSL NPN support required', 1 if $@;
 
-$s = Test::Nginx::HTTP2->new(8081, SSL => 1, npn => 'h2');
+$s = Test::Nginx::HTTP2->new(port(0), SSL => 1, npn => 'h2');
 $sid = $s->new_stream({ path => '/sp' });
 $frames = $s->read(all => [{ sid => $sid, fin => 1 }]);
 
@@ -144,7 +144,7 @@ SKIP: {
 eval { IO::Socket::SSL->can_alpn() or die; };
 skip 'OpenSSL ALPN support required', 1 if $@;
 
-$s = Test::Nginx::HTTP2->new(8081, SSL => 1, alpn => 'h2');
+$s = Test::Nginx::HTTP2->new(port(0), SSL => 1, alpn => 'h2');
 $sid = $s->new_stream({ path => '/sp' });
 $frames = $s->read(all => [{ sid => $sid, fin => 1 }]);
 
@@ -159,7 +159,7 @@ SKIP: {
 eval { IO::Socket::SSL->can_npn() or die; };
 skip 'OpenSSL NPN support required', 1 if $@;
 
-$s = Test::Nginx::HTTP2->new(8081, SSL => 1, npn => 'h2');
+$s = Test::Nginx::HTTP2->new(port(0), SSL => 1, npn => 'h2');
 $sid = $s->new_stream({ path => '/scheme' });
 $frames = $s->read(all => [{ sid => $sid, fin => 1 }]);
 
@@ -174,7 +174,7 @@ SKIP: {
 eval { IO::Socket::SSL->can_alpn() or die; };
 skip 'OpenSSL ALPN support required', 1 if $@;
 
-$s = Test::Nginx::HTTP2->new(8081, SSL => 1, alpn => 'h2');
+$s = Test::Nginx::HTTP2->new(port(0), SSL => 1, alpn => 'h2');
 $sid = $s->new_stream({ path => '/scheme' });
 $frames = $s->read(all => [{ sid => $sid, fin => 1 }]);
 
@@ -189,7 +189,7 @@ SKIP: {
 eval { IO::Socket::SSL->can_npn() or die; };
 skip 'OpenSSL NPN support required', 1 if $@;
 
-$s = Test::Nginx::HTTP2->new(8081, SSL => 1, npn => 'h2');
+$s = Test::Nginx::HTTP2->new(port(0), SSL => 1, npn => 'h2');
 $sid = $s->new_stream({ path => '/https' });
 $frames = $s->read(all => [{ sid => $sid, fin => 1 }]);
 
@@ -204,7 +204,7 @@ SKIP: {
 eval { IO::Socket::SSL->can_alpn() or die; };
 skip 'OpenSSL ALPN support required', 1 if $@;
 
-$s = Test::Nginx::HTTP2->new(8081, SSL => 1, alpn => 'h2');
+$s = Test::Nginx::HTTP2->new(port(0), SSL => 1, alpn => 'h2');
 $sid = $s->new_stream({ path => '/https' });
 $frames = $s->read(all => [{ sid => $sid, fin => 1 }]);
 
--- a/h2_ssl_verify_client.t
+++ b/h2_ssl_verify_client.t
@@ -53,7 +53,7 @@ http {
     add_header X-Verify $ssl_client_verify;
 
     server {
-        listen       127.0.0.1:8443 ssl http2;
+        listen       127.0.0.1:%%PORT_0%% ssl http2;
         server_name  localhost;
 
         ssl_client_certificate client.crt;
@@ -62,7 +62,7 @@ http {
     }
 
     server {
-        listen       127.0.0.1:8443 ssl http2;
+        listen       127.0.0.1:%%PORT_0%% ssl http2;
         server_name  example.com;
 
         location / { }
@@ -122,7 +122,7 @@ sub get {
 		$s = IO::Socket::SSL->new(
 			Proto => 'tcp',
 			PeerAddr => '127.0.0.1',
-			PeerPort => 8443,
+			PeerPort => port(0),
 			SSL_verify_mode => IO::Socket::SSL::SSL_VERIFY_NONE(),
 			SSL_alpn_protocols => [ 'h2' ],
 			SSL_hostname => $sni,
@@ -139,7 +139,7 @@ sub get {
 		return undef;
 	}
 
-	my $sess = Test::Nginx::HTTP2->new(8443, socket => $s);
+	my $sess = Test::Nginx::HTTP2->new(port(0), socket => $s);
 	my $sid = $sess->new_stream({ headers => [
 		{ name => ':method', value => 'GET', mode => 0 },
 		{ name => ':scheme', value => 'http', mode => 0 },
--- a/h2_variables.t
+++ b/h2_variables.t
@@ -37,7 +37,7 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen       127.0.0.1:8080 http2;
+        listen       127.0.0.1:%%PORT_0%% http2;
         server_name  localhost;
 
         location /h2 {
--- a/headers.t
+++ b/headers.t
@@ -37,7 +37,7 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         add_header   X-URI $uri;
--- a/http_disable_symlinks.t
+++ b/http_disable_symlinks.t
@@ -37,7 +37,7 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  s1;
 
         location /on/ {
@@ -123,7 +123,7 @@ http {
     }
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  s2;
 
         open_file_cache max=16 inactive=60s;
--- a/http_error_page.t
+++ b/http_error_page.t
@@ -35,7 +35,7 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         location /redirect200 {
@@ -86,7 +86,7 @@ http {
         }
 
         location /auto/ {
-            proxy_pass http://127.0.0.1:8081;
+            proxy_pass http://127.0.0.1:%%PORT_1%%;
         }
     }
 }
--- a/http_expect_100_continue.t
+++ b/http_expect_100_continue.t
@@ -36,10 +36,10 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
         location / {
-            proxy_pass http://127.0.0.1:8080/local;
+            proxy_pass http://127.0.0.1:%%PORT_0%%/local;
         }
         location /local {
         }
--- a/http_host.t
+++ b/http_host.t
@@ -37,7 +37,7 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen  127.0.0.1:8080;
+        listen  127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         location / {
@@ -55,7 +55,7 @@ EOF
 
 is(http_host_header('www.abcd-ef.g02.xyz'), 'www.abcd-ef.g02.xyz',
 	'domain w/o port (host header)');
-is(http_host_header('abcd-ef.g02.xyz:8080'), 'abcd-ef.g02.xyz',
+is(http_host_header('abcd-ef.g02.xyz:' . port(0)), 'abcd-ef.g02.xyz',
 	'domain w/port (host header)');
 
 is(http_absolute_path('abcd-ef.g02.xyz'), 'abcd-ef.g02.xyz',
--- a/http_location.t
+++ b/http_location.t
@@ -35,7 +35,7 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         location = / {
--- a/http_location_auto.t
+++ b/http_location_auto.t
@@ -35,7 +35,7 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         proxy_hide_header X-Location;
@@ -53,7 +53,7 @@ http {
         #
         # Key factor is that "-" is less than "/".
 
-        location /a/  { proxy_pass http://127.0.0.1:8080/a-a; }
+        location /a/  { proxy_pass http://127.0.0.1:%%PORT_0%%/a-a; }
         location /a-a { add_header X-Location a-a; return 204; }
         location /a-b { add_header X-Location a-b; return 204; }
     }
--- a/http_location_win32.t
+++ b/http_location_win32.t
@@ -38,7 +38,7 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         location / {
--- a/http_resolver.t
+++ b/http_resolver.t
@@ -39,13 +39,13 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         location / {
-            resolver    127.0.0.1:8081;
+            resolver    127.0.0.1:%%PORT_1_UDP%%;
             resolver_timeout 1s;
-            proxy_pass  http://$host:8080/backend;
+            proxy_pass  http://$host:%%PORT_0%%/backend;
 
             proxy_next_upstream http_504 timeout error;
             proxy_intercept_errors on;
@@ -53,46 +53,46 @@ http {
             error_page 504 502 /50x;
         }
         location /two {
-            resolver    127.0.0.1:8081 127.0.0.1:8082;
-            proxy_pass  http://$host:8080/backend;
+            resolver    127.0.0.1:%%PORT_1_UDP%% 127.0.0.1:%%PORT_2_UDP%%;
+            proxy_pass  http://$host:%%PORT_0%%/backend;
         }
         location /valid {
-            resolver    127.0.0.1:8081 valid=5s;
-            proxy_pass  http://$host:8080/backend;
+            resolver    127.0.0.1:%%PORT_1_UDP%% valid=5s;
+            proxy_pass  http://$host:%%PORT_0%%/backend;
         }
         location /case {
-            resolver    127.0.0.1:8081;
-            proxy_pass  http://$http_x_name:8080/backend;
+            resolver    127.0.0.1:%%PORT_1_UDP%%;
+            proxy_pass  http://$http_x_name:%%PORT_0%%/backend;
         }
         location /invalid {
-            proxy_pass  http://$host:8080/backend;
+            proxy_pass  http://$host:%%PORT_0%%/backend;
         }
         location /long {
-            resolver    127.0.0.1:8081;
+            resolver    127.0.0.1:%%PORT_1_UDP%%;
             resolver_timeout 4s;
-            proxy_pass  http://$host:8080/backend;
+            proxy_pass  http://$host:%%PORT_0%%/backend;
         }
         location /resend {
-            resolver    127.0.0.1:8081;
+            resolver    127.0.0.1:%%PORT_1_UDP%%;
             resolver_timeout 8s;
-            proxy_pass  http://$host:8080/backend;
+            proxy_pass  http://$host:%%PORT_0%%/backend;
         }
         location /bad {
-            resolver    127.0.0.1:8089;
+            resolver    127.0.0.1:%%PORT_4_UDP%%;
             resolver_timeout 1s;
-            proxy_pass  http://$host:8080/backend;
+            proxy_pass  http://$host:%%PORT_0%%/backend;
         }
         location /tcp {
-            resolver    127.0.0.1:8083 127.0.0.1:8082;
+            resolver    127.0.0.1:%%PORT_3_UDP%% 127.0.0.1:%%PORT_2_UDP%%;
             resolver_timeout 1s;
-            proxy_pass  http://$host:8080/backend;
+            proxy_pass  http://$host:%%PORT_0%%/backend;
             proxy_connect_timeout 1s;
             add_header X-IP $upstream_addr;
             error_page 504 502 /50x;
 
             location /tcp2 {
                 resolver_timeout 8s;
-                proxy_pass  http://$host:8080/backend;
+                proxy_pass  http://$host:%%PORT_0%%/backend;
             }
         }
 
@@ -107,20 +107,22 @@ http {
 
 EOF
 
-$t->run_daemon(\&dns_daemon, 8081, $t);
-$t->run_daemon(\&dns_daemon, 8082, $t);
-$t->run_daemon(\&dns_daemon, 8083, $t, tcp => 1);
-$t->run_daemon(\&dns_daemon, 8089, $t);
+$t->run_daemon(\&dns_daemon, port(1), $t);
+$t->run_daemon(\&dns_daemon, port(2), $t);
+$t->run_daemon(\&dns_daemon, port(3), $t, tcp => 1);
+$t->run_daemon(\&dns_daemon, port(4), $t);
 
 $t->run()->plan(38);
 
-$t->waitforfile($t->testdir . '/8081');
-$t->waitforfile($t->testdir . '/8082');
-$t->waitforfile($t->testdir . '/8083');
-$t->waitforfile($t->testdir . '/8089');
+$t->waitforfile($t->testdir . '/' . port(1));
+$t->waitforfile($t->testdir . '/' . port(2));
+$t->waitforfile($t->testdir . '/' . port(3));
+$t->waitforfile($t->testdir . '/' . port(4));
 
 ###############################################################################
 
+my $p0 = port(0);
+
 # schedule resend test, which takes about 5 seconds to complete
 
 my $s = http_host_header('id.example.net', '/resend', start => 1);
@@ -163,11 +165,11 @@ like(http_host_header('alias.example.com
 # nonexisting IPs enumerated with proxy_next_upstream
 
 like(http_host_header('many.example.net', '/'),
-	qr/^127.0.0.20(1:8080, 127.0.0.202:8080|2:8080, 127.0.0.201:8080)$/m,
+	qr/^127.0.0.20(1:$p0, 127.0.0.202:$p0|2:$p0, 127.0.0.201:$p0)$/m,
 	'A many');
 
 like(http_host_header('many.example.net', '/'),
-	qr/^127.0.0.20(1:8080, 127.0.0.202:8080|2:8080, 127.0.0.201:8080)$/m,
+	qr/^127.0.0.20(1:$p0, 127.0.0.202:$p0|2:$p0, 127.0.0.201:$p0)$/m,
 	'A many cached');
 
 # tests for several resolvers specified in directive
@@ -483,7 +485,7 @@ sub reply_handler {
 		push @rdata, rd_addr(0, '127.0.0.1');
 
 	} elsif ($name eq '2.example.net') {
-		if ($port == 8081) {
+		if ($port == port(1)) {
 			$state->{twocnt}++;
 		}
 		if ($state->{twocnt} & 1) {
@@ -495,7 +497,7 @@ sub reply_handler {
 		}
 
 	} elsif ($name =~ /tcp2?.example.net/) {
-		$rcode = FORMERR if $port == 8082;
+		$rcode = FORMERR if $port == port(2);
 		$hdr |= 0x0300 unless $extra{tcp};
 		push @rdata, rd_addr($ttl, $extra{tcp}
 			? '127.0.0.1' : '127.0.0.201') if $type == A;
@@ -531,14 +533,7 @@ sub dns_daemon {
 	my $tcp = 0;
 
 	if ($extra{tcp}) {
-		$tcp = IO::Socket::INET->new(
-			Proto => 'tcp',
-			LocalHost => "127.0.0.1:$port",
-			Listen => 5,
-			Reuse => 1
-		)
-			or die "Can't create listening socket: $!\n";
-
+		$tcp = port(3, socket => 1)->listen();
 		$sel->add($tcp);
 	}
 
--- a/http_resolver_aaaa.t
+++ b/http_resolver_aaaa.t
@@ -37,13 +37,13 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen       127.0.0.1:8080;
-        listen       [::1]:8080;
+        listen       127.0.0.1:%%PORT_0%%;
+        listen       [::1]:%%PORT_0%%;
         server_name  localhost;
 
         location / {
-            resolver    127.0.0.1:8081;
-            proxy_pass  http://$host:8080/backend;
+            resolver    127.0.0.1:%%PORT_1_UDP%%;
+            proxy_pass  http://$host:%%PORT_0%%/backend;
 
             proxy_next_upstream http_504 timeout error;
             proxy_intercept_errors on;
@@ -52,8 +52,8 @@ http {
             add_header X-Host $upstream_addr;
         }
         location /two {
-            resolver    127.0.0.1:8081 127.0.0.1:8082;
-            proxy_pass  http://$host:8080/backend;
+            resolver    127.0.0.1:%%PORT_1_UDP%% 127.0.0.1:%%PORT_2_UDP%%;
+            proxy_pass  http://$host:%%PORT_0%%/backend;
         }
 
         location /backend {
@@ -69,16 +69,18 @@ EOF
 
 $t->try_run('no inet6 support')->plan(72);
 
-$t->run_daemon(\&dns_daemon, 8081, $t);
-$t->run_daemon(\&dns_daemon, 8082, $t);
+$t->run_daemon(\&dns_daemon, port(1), $t);
+$t->run_daemon(\&dns_daemon, port(2), $t);
 
-$t->waitforfile($t->testdir . '/8081');
-$t->waitforfile($t->testdir . '/8082');
+$t->waitforfile($t->testdir . '/' . port(1));
+$t->waitforfile($t->testdir . '/' . port(2));
 
 ###############################################################################
 
 my (@n, $response);
 
+my $p0 = port(0);
+
 like(http_host_header('aaaa.example.net', '/'), qr/\[fe80::1\]/, 'AAAA');
 like(http_host_header('cname.example.net', '/'), qr/\[fe80::1\]/, 'CNAME');
 like(http_host_header('cname.example.net', '/'), qr/\[fe80::1\]/,
@@ -93,11 +95,11 @@ like(http_host_header('cname_a.example.n
 # nonexisting IPs enumerated with proxy_next_upstream
 
 like(http_host_header('many.example.net', '/'),
-	qr/^\[fe80::(1\]:8080, \[fe80::2\]:8080|2\]:8080, \[fe80::1\]:8080)$/m,
+	qr/^\[fe80::(1\]:$p0, \[fe80::2\]:$p0|2\]:$p0, \[fe80::1\]:$p0)$/m,
 	'AAAA many');
 
 like(http_host_header('many.example.net', '/'),
-	qr/^\[fe80::(1\]:8080, \[fe80::2\]:8080|2\]:8080, \[fe80::1\]:8080)$/m,
+	qr/^\[fe80::(1\]:$p0, \[fe80::2\]:$p0|2\]:$p0, \[fe80::1\]:$p0)$/m,
 	'AAAA many cached');
 
 # tests for several resolvers specified in directive
@@ -116,118 +118,118 @@ like(http_host_header('2.example.net', '
 # various ipv4/ipv6 combinations
 
 $response = http_host_header('z_z.example.net', '/');
-is(@n = $response =~ /8080/g, 0, 'zero zero responses');
+is(@n = $response =~ /$p0/g, 0, 'zero zero responses');
 like($response, qr/502 Bad/, 'zero zero');
 
-like(http_host_header('z_n.example.net', '/'), qr/^\[fe80::1\]:8080$/ms,
+like(http_host_header('z_n.example.net', '/'), qr/^\[fe80::1\]:$p0$/ms,
 	'zero AAAA');
 
 $response = http_host_header('z_c.example.net', '/');
-is(@n = $response =~ /8080/g, 2, 'zero CNAME responses');
-like($response, qr/127.0.0.201:8080/, 'zero CNAME 1');
-like($response, qr/\[fe80::1\]:8080/, 'zero CNAME 2');
+is(@n = $response =~ /$p0/g, 2, 'zero CNAME responses');
+like($response, qr/127.0.0.201:$p0/, 'zero CNAME 1');
+like($response, qr/\[fe80::1\]:$p0/, 'zero CNAME 2');
 
 $response = http_host_header('z_cn.example.net', '/');
-is(@n = $response =~ /8080/g, 2, 'zero CNAME+AAAA responses');
-like($response, qr/\[fe80::1\]:8080/, 'zero CNAME+AAAA 1');
-like($response, qr/\[fe80::2\]:8080/, 'zero CNAME+AAAA 2');
+is(@n = $response =~ /$p0/g, 2, 'zero CNAME+AAAA responses');
+like($response, qr/\[fe80::1\]:$p0/, 'zero CNAME+AAAA 1');
+like($response, qr/\[fe80::2\]:$p0/, 'zero CNAME+AAAA 2');
 
 $response = http_host_header('z_e.example.net', '/');
-is(@n = $response =~ /8080/g, 0, 'zero error responses');
+is(@n = $response =~ /$p0/g, 0, 'zero error responses');
 like($response, qr/502 Bad/, 'zero error');
 
-like(http_host_header('n_z.example.net', '/'), qr/^127.0.0.201:8080$/ms,
+like(http_host_header('n_z.example.net', '/'), qr/^127.0.0.201:$p0$/ms,
 	'A zero');
 
 $response = http_host_header('n_n.example.net', '/');
-is(@n = $response =~ /8080/g, 2, 'A AAAA responses');
-like($response, qr/127.0.0.201:8080/, 'A AAAA 1');
-like($response, qr/\[fe80::1\]:8080/, 'A AAAA 2');
+is(@n = $response =~ /$p0/g, 2, 'A AAAA responses');
+like($response, qr/127.0.0.201:$p0/, 'A AAAA 1');
+like($response, qr/\[fe80::1\]:$p0/, 'A AAAA 2');
 
-like(http_host_header('n_c.example.net', '/'), qr/^127.0.0.201:8080$/ms,
+like(http_host_header('n_c.example.net', '/'), qr/^127.0.0.201:$p0$/ms,
 	'A CNAME');
 
 $response = http_host_header('n_cn.example.net', '/');
-is(@n = $response =~ /8080/g, 4, 'A CNAME+AAAA responses');
-like($response, qr/127.0.0.201:8080/, 'A CNAME+AAAA 1');
-like($response, qr/127.0.0.202:8080/, 'A CNAME+AAAA 2');
-like($response, qr/\[fe80::1\]:8080/, 'A CNAME+AAAA 3');
-like($response, qr/\[fe80::2\]:8080/, 'A CNAME+AAAA 4');
+is(@n = $response =~ /$p0/g, 4, 'A CNAME+AAAA responses');
+like($response, qr/127.0.0.201:$p0/, 'A CNAME+AAAA 1');
+like($response, qr/127.0.0.202:$p0/, 'A CNAME+AAAA 2');
+like($response, qr/\[fe80::1\]:$p0/, 'A CNAME+AAAA 3');
+like($response, qr/\[fe80::2\]:$p0/, 'A CNAME+AAAA 4');
 
 $response = http_host_header('n_e.example.net', '/');
-is(@n = $response =~ /8080/g, 0, 'A error responses');
+is(@n = $response =~ /$p0/g, 0, 'A error responses');
 like($response, qr/502 Bad/, 'A error');
 
 $response = http_host_header('c_z.example.net', '/');
-is(@n = $response =~ /8080/g, 0, 'CNAME zero responses');
+is(@n = $response =~ /$p0/g, 0, 'CNAME zero responses');
 like($response, qr/502 Bad/, 'CNAME zero');
 
-like(http_host_header('c_n.example.net', '/'), qr/^\[fe80::1\]:8080$/ms,
+like(http_host_header('c_n.example.net', '/'), qr/^\[fe80::1\]:$p0$/ms,
 	'CNAME AAAA');
 
 $response = http_host_header('c_c.example.net', '/');
-is(@n = $response =~ /8080/g, 2, 'CNAME CNAME responses');
-like($response, qr/127.0.0.201:8080/, 'CNAME CNAME 1');
-like($response, qr/\[fe80::1\]:8080/, 'CNAME CNAME 2');
+is(@n = $response =~ /$p0/g, 2, 'CNAME CNAME responses');
+like($response, qr/127.0.0.201:$p0/, 'CNAME CNAME 1');
+like($response, qr/\[fe80::1\]:$p0/, 'CNAME CNAME 2');
 
-like(http_host_header('c1_c2.example.net', '/'), qr/^\[fe80::1\]:8080$/ms,
+like(http_host_header('c1_c2.example.net', '/'), qr/^\[fe80::1\]:$p0$/ms,
 	'CNAME1 CNAME2');
 
 $response = http_host_header('c_cn.example.net', '/');
-is(@n = $response =~ /8080/g, 2, 'CNAME CNAME+AAAA responses');
-like($response, qr/\[fe80::1\]:8080/, 'CNAME CNAME+AAAA 1');
-like($response, qr/\[fe80::2\]:8080/, 'CNAME CNAME+AAAA 1');
+is(@n = $response =~ /$p0/g, 2, 'CNAME CNAME+AAAA responses');
+like($response, qr/\[fe80::1\]:$p0/, 'CNAME CNAME+AAAA 1');
+like($response, qr/\[fe80::2\]:$p0/, 'CNAME CNAME+AAAA 1');
 
 $response = http_host_header('c_e.example.net', '/');
-is(@n = $response =~ /8080/g, 0, 'CNAME error responses');
+is(@n = $response =~ /$p0/g, 0, 'CNAME error responses');
 like($response, qr/502 Bad/, 'CNAME error');
 
 $response = http_host_header('cn_z.example.net', '/');
-is(@n = $response =~ /8080/g, 2, 'CNAME+A zero responses');
-like($response, qr/127.0.0.201:8080/, 'CNAME+A zero 1');
-like($response, qr/127.0.0.202:8080/, 'CNAME+A zero 2');
+is(@n = $response =~ /$p0/g, 2, 'CNAME+A zero responses');
+like($response, qr/127.0.0.201:$p0/, 'CNAME+A zero 1');
+like($response, qr/127.0.0.202:$p0/, 'CNAME+A zero 2');
 
 $response = http_host_header('cn_n.example.net', '/');
-is(@n = $response =~ /8080/g, 4, 'CNAME+A AAAA responses');
-like($response, qr/127.0.0.201:8080/, 'CNAME+A AAAA 1');
-like($response, qr/127.0.0.202:8080/, 'CNAME+A AAAA 2');
-like($response, qr/\[fe80::1\]:8080/, 'CNAME+A AAAA 3');
-like($response, qr/\[fe80::2\]:8080/, 'CNAME+A AAAA 4');
+is(@n = $response =~ /$p0/g, 4, 'CNAME+A AAAA responses');
+like($response, qr/127.0.0.201:$p0/, 'CNAME+A AAAA 1');
+like($response, qr/127.0.0.202:$p0/, 'CNAME+A AAAA 2');
+like($response, qr/\[fe80::1\]:$p0/, 'CNAME+A AAAA 3');
+like($response, qr/\[fe80::2\]:$p0/, 'CNAME+A AAAA 4');
 
 $response = http_host_header('cn_c.example.net', '/');
-is(@n = $response =~ /8080/g, 2, 'CNAME+A CNAME responses');
-like($response, qr/127.0.0.201:8080/, 'CNAME+A CNAME 1');
-like($response, qr/127.0.0.202:8080/, 'CNAME+A CNAME 2');
+is(@n = $response =~ /$p0/g, 2, 'CNAME+A CNAME responses');
+like($response, qr/127.0.0.201:$p0/, 'CNAME+A CNAME 1');
+like($response, qr/127.0.0.202:$p0/, 'CNAME+A CNAME 2');
 
 $response = http_host_header('cn_cn.example.net', '/');
-is(@n = $response =~ /8080/g, 4, 'CNAME+A CNAME+AAAA responses');
-like($response, qr/127.0.0.201:8080/, 'CNAME+A CNAME+AAAA 1');
-like($response, qr/127.0.0.202:8080/, 'CNAME+A CNAME+AAAA 2');
-like($response, qr/\[fe80::1\]:8080/, 'CNAME+A CNAME+AAAA 3');
-like($response, qr/\[fe80::2\]:8080/, 'CNAME+A CNAME+AAAA 4');
+is(@n = $response =~ /$p0/g, 4, 'CNAME+A CNAME+AAAA responses');
+like($response, qr/127.0.0.201:$p0/, 'CNAME+A CNAME+AAAA 1');
+like($response, qr/127.0.0.202:$p0/, 'CNAME+A CNAME+AAAA 2');
+like($response, qr/\[fe80::1\]:$p0/, 'CNAME+A CNAME+AAAA 3');
+like($response, qr/\[fe80::2\]:$p0/, 'CNAME+A CNAME+AAAA 4');
 
 $response = http_host_header('cn_e.example.net', '/');
-is(@n = $response =~ /8080/g, 0, 'CNAME+A error responses');
+is(@n = $response =~ /$p0/g, 0, 'CNAME+A error responses');
 like($response, qr/502 Bad/, 'CNAME+A error');
 
 $response = http_host_header('e_z.example.net', '/');
-is(@n = $response =~ /8080/g, 0, 'error zero responses');
+is(@n = $response =~ /$p0/g, 0, 'error zero responses');
 like($response, qr/502 Bad/, 'error zero');
 
 $response = http_host_header('e_n.example.net', '/');
-is(@n = $response =~ /8080/g, 0, 'error AAAA responses');
+is(@n = $response =~ /$p0/g, 0, 'error AAAA responses');
 like($response, qr/502 Bad/, 'error AAAA');
 
 $response = http_host_header('e_c.example.net', '/');
-is(@n = $response =~ /8080/g, 0, 'error CNAME responses');
+is(@n = $response =~ /$p0/g, 0, 'error CNAME responses');
 like($response, qr/502 Bad/, 'error CNAME');
 
 $response = http_host_header('e_cn.example.net', '/');
-is(@n = $response =~ /8080/g, 0, 'error CNAME+AAAA responses');
+is(@n = $response =~ /$p0/g, 0, 'error CNAME+AAAA responses');
 like($response, qr/502 Bad/, 'error CNAME+AAAA');
 
 $response = http_host_header('e_e.example.net', '/');
-is(@n = $response =~ /8080/g, 0, 'error error responses');
+is(@n = $response =~ /$p0/g, 0, 'error error responses');
 like($response, qr/502 Bad/, 'error error');
 
 ###############################################################################
@@ -330,7 +332,7 @@ sub reply_handler {
 		}
 
 	} elsif ($name eq '2.example.net') {
-		if ($port == 8081) {
+		if ($port == port(1)) {
 			$state->{twocnt}++;
 		}
 		if ($state->{twocnt} & 1) {
--- a/http_resolver_cname.t
+++ b/http_resolver_cname.t
@@ -37,21 +37,21 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         location /short {
-            resolver    127.0.0.1:8081;
+            resolver    127.0.0.1:%%PORT_1_UDP%%;
             resolver_timeout 2s;
 
-            proxy_pass  http://$host:8080/t;
+            proxy_pass  http://$host:%%PORT_0%%/t;
         }
 
         location /long {
-            resolver    127.0.0.1:8081;
+            resolver    127.0.0.1:%%PORT_1_UDP%%;
             resolver_timeout 5s;
 
-            proxy_pass  http://$host:8080/t;
+            proxy_pass  http://$host:%%PORT_0%%/t;
         }
 
         location / { }
@@ -60,12 +60,12 @@ http {
 
 EOF
 
-$t->run_daemon(\&dns_daemon, 8081, $t);
+$t->run_daemon(\&dns_daemon, port(1), $t);
 
 $t->write_file('t', '');
 $t->run();
 
-$t->waitforfile($t->testdir . '/8081');
+$t->waitforfile($t->testdir . '/' . port(1));
 
 ###############################################################################
 
--- a/http_server_name.t
+++ b/http_server_name.t
@@ -43,7 +43,7 @@ http {
     server_names_hash_bucket_size 64;
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         location / {
@@ -52,7 +52,7 @@ http {
     }
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  "";
 
         location / {
@@ -61,7 +61,7 @@ http {
     }
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  www.example.com;
 
         location / {
@@ -70,7 +70,7 @@ http {
     }
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  ~^EXAMPLE\.COM$;
 
         location / {
@@ -79,7 +79,7 @@ http {
     }
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  ~^(?P<name>.+)\Q.example.com\E$;
 
         location / {
@@ -89,7 +89,7 @@ http {
     }
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  "~^(?P<name>www\p{N}+)\.example\.com$";
 
         location / {
@@ -99,7 +99,7 @@ http {
     }
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  many.example.com many2.example.com;
 
         location / {
@@ -108,7 +108,7 @@ http {
     }
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  many3.example.com;
         server_name  many4.example.com;
 
@@ -118,7 +118,7 @@ http {
     }
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  *.wc.example.com;
 
         location / {
@@ -127,7 +127,7 @@ http {
     }
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  *.pref.wc.example.com;
 
         location / {
@@ -136,7 +136,7 @@ http {
     }
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  wc2.example.*;
 
         location / {
@@ -145,7 +145,7 @@ http {
     }
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  wc2.example.com.*;
 
         location / {
@@ -154,7 +154,7 @@ http {
     }
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  .dot.example.com;
 
         location / {
--- a/http_try_files.t
+++ b/http_try_files.t
@@ -35,7 +35,7 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         location / {
@@ -79,15 +79,15 @@ http {
         }
 
         location /fallback {
-            proxy_pass http://127.0.0.1:8081/fallback;
+            proxy_pass http://127.0.0.1:%%PORT_1%%/fallback;
         }
         location /fallback-nouri {
-            proxy_pass http://127.0.0.1:8081;
+            proxy_pass http://127.0.0.1:%%PORT_1%%;
         }
     }
 
     server {
-        listen       127.0.0.1:8081;
+        listen       127.0.0.1:%%PORT_1%%;
         server_name  localhost;
 
         location / {
--- a/http_variables.t
+++ b/http_variables.t
@@ -39,7 +39,7 @@ http {
     log_format cc "$uri: $sent_http_cache_control";
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         access_log %%TESTDIR%%/cc.log cc;
@@ -57,7 +57,7 @@ http {
 
         location /redefine {
             expires epoch;
-            proxy_pass http://127.0.0.1:8080/set;
+            proxy_pass http://127.0.0.1:%%PORT_0%%/set;
         }
     }
 }
--- a/image_filter.t
+++ b/image_filter.t
@@ -50,7 +50,7 @@ http {
     }
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         location /size {
@@ -154,7 +154,7 @@ http {
         location /proxy_buffer {
             image_filter rotate 90;
             image_filter_buffer 20;
-            proxy_pass http://127.0.0.1:8081/;
+            proxy_pass http://127.0.0.1:%%PORT_1%%/;
             proxy_buffering off;
             proxy_buffer_size 512;
         }
@@ -177,7 +177,7 @@ my $black = $im->colorAllocate(0, 0, 0);
 $t->write_file('txt', 'SEE-THIS');
 
 $t->run_daemon(\&http_daemon, $t);
-$t->run()->waitforsocket('127.0.0.1:8081');
+$t->run()->waitforsocket('127.0.0.1:' . port(1));
 
 ###############################################################################
 
@@ -303,7 +303,7 @@ sub http_daemon {
 	my $server = IO::Socket::INET->new(
 		Proto => 'tcp',
 		LocalHost => '127.0.0.1',
-		LocalPort => 8081,
+		LocalPort => port(1),
 		Listen => 5,
 		Reuse => 1
 	)
--- a/image_filter_finalize.t
+++ b/image_filter_finalize.t
@@ -43,22 +43,22 @@ http {
     access_log time.log time;
 
     upstream u {
-        server 127.0.0.1:8081;
-        server 127.0.0.1:8081;
-        server 127.0.0.1:8081;
-        server 127.0.0.1:8081;
-        server 127.0.0.1:8080;
+        server 127.0.0.1:%%PORT_1%%;
+        server 127.0.0.1:%%PORT_1%%;
+        server 127.0.0.1:%%PORT_1%%;
+        server 127.0.0.1:%%PORT_1%%;
+        server 127.0.0.1:%%PORT_0%%;
     }
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         # this used to cause a segmentation fault before 07f028df3879 (1.3.1)
         # http://nginx.org/pipermail/nginx/2011-January/024703.html
 
         location /t1 {
-            proxy_pass http://127.0.0.1:8080/bad;
+            proxy_pass http://127.0.0.1:%%PORT_0%%/bad;
             proxy_cache cache;
             proxy_cache_valid any 1h;
 
@@ -78,7 +78,7 @@ http {
         # fixed in 07f028df3879 (1.3.1)
 
         location /t2 {
-            proxy_pass http://127.0.0.1:8080/big;
+            proxy_pass http://127.0.0.1:%%PORT_0%%/big;
             proxy_store on;
 
             image_filter_buffer 10m;
@@ -111,7 +111,7 @@ http {
         }
 
         location /upstream {
-            proxy_pass http://127.0.0.1:8080/empty;
+            proxy_pass http://127.0.0.1:%%PORT_0%%/empty;
         }
 
         location /time.log {
@@ -120,7 +120,7 @@ http {
     }
 
     server {
-        listen       127.0.0.1:8081;
+        listen       127.0.0.1:%%PORT_1%%;
         server_name  localhost;
         return 444;
     }
--- a/index.t
+++ b/index.t
@@ -36,7 +36,7 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
         add_header   X-URI $uri;
 
--- a/js.t
+++ b/js.t
@@ -58,7 +58,7 @@ http {
                           s;";
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         location /req_method {
--- a/limit_conn.t
+++ b/limit_conn.t
@@ -42,7 +42,7 @@ http {
     limit_conn_zone  $binary_remote_addr  zone=custom:1m;
 
     server {
-        listen       127.0.0.1:8081;
+        listen       127.0.0.1:%%PORT_1%%;
         server_name  localhost;
 
         location /w {
@@ -51,11 +51,11 @@ http {
     }
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         location / {
-            proxy_pass http://127.0.0.1:8081;
+            proxy_pass http://127.0.0.1:%%PORT_1%%;
             limit_conn zone 1;
         }
 
@@ -72,7 +72,7 @@ http {
         }
 
         location /custom {
-            proxy_pass http://127.0.0.1:8081/;
+            proxy_pass http://127.0.0.1:%%PORT_1%%/;
             limit_conn_log_level info;
             limit_conn_status 501;
             limit_conn custom 1;
--- a/limit_conn_complex.t
+++ b/limit_conn_complex.t
@@ -44,7 +44,7 @@ http {
     limit_conn_zone  $binary_remote_addr$arg_c  zone=conn:1m;
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         location / {
@@ -53,7 +53,7 @@ http {
 
         location /w {
             limit_conn conn 1;
-            proxy_pass http://127.0.0.1:8080/req2;
+            proxy_pass http://127.0.0.1:%%PORT_0%%/req2;
         }
 
         location /req {
--- a/limit_req.t
+++ b/limit_req.t
@@ -40,7 +40,7 @@ http {
     limit_req_zone  $binary_remote_addr  zone=fast:1m  rate=1000r/s;
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
         location / {
             limit_req    zone=one  burst=1  nodelay;
--- a/mail_error_log.t
+++ b/mail_error_log.t
@@ -28,7 +28,7 @@ select STDOUT; $| = 1;
 plan(skip_all => 'win32') if $^O eq 'MSWin32';
 
 my $t = Test::Nginx->new()->has(qw/mail imap http rewrite/)
-	->run_daemon(\&Test::Nginx::IMAP::imap_test_daemon);
+	->run_daemon(\&Test::Nginx::IMAP::imap_test_daemon, port(4));
 
 plan(skip_all => 'no error_log') unless $t->has_version('1.9.0');
 
@@ -38,7 +38,7 @@ plan(skip_all => 'no error_log') unless 
 
 error_log %%TESTDIR%%/e_glob.log info;
 error_log %%TESTDIR%%/e_glob2.log info;
-error_log syslog:server=127.0.0.1:8081 info;
+error_log syslog:server=127.0.0.1:%%PORT_1_UDP%% info;
 
 daemon off;
 
@@ -46,23 +46,23 @@ events {
 }
 
 mail {
-    auth_http  http://127.0.0.1:8080/mail/auth;
+    auth_http  http://127.0.0.1:%%PORT_0%%/mail/auth;
 
     server {
-        listen     127.0.0.1:8143;
+        listen     127.0.0.1:%%PORT_3%%;
         protocol   imap;
 
         error_log %%TESTDIR%%/e_debug.log debug;
         error_log %%TESTDIR%%/e_info.log info;
-        error_log syslog:server=127.0.0.1:8082 info;
+        error_log syslog:server=127.0.0.1:%%PORT_2_UDP%%  info;
         error_log stderr info;
     }
 
     server {
-        listen     127.0.0.1:8145;
+        listen     127.0.0.1:%%PORT_5%%;
         protocol   imap;
 
-        error_log syslog:server=127.0.0.1:8080 info;
+        error_log syslog:server=127.0.0.1:%%PORT_6_UDP%% info;
     }
 }
 
@@ -70,13 +70,13 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         location = /mail/auth {
             add_header Auth-Status OK;
             add_header Auth-Server 127.0.0.1;
-            add_header Auth-Port 8144;
+            add_header Auth-Port %%PORT_4%%;
             add_header Auth-Wait 1;
             return 204;
         }
@@ -90,8 +90,8 @@ open STDERR, '>', $t->testdir() . '/stde
 open my $stderr, '<', $t->testdir() . '/stderr'
 	or die "Can't open stderr file: $!";
 
-$t->run_daemon(\&syslog_daemon, 8081, $t, 's_glob.log');
-$t->run_daemon(\&syslog_daemon, 8082, $t, 's_info.log');
+$t->run_daemon(\&syslog_daemon, port(1), $t, 's_glob.log');
+$t->run_daemon(\&syslog_daemon, port(2), $t, 's_info.log');
 
 $t->waitforfile($t->testdir . '/s_glob.log');
 $t->waitforfile($t->testdir . '/s_info.log');
@@ -102,7 +102,7 @@ open STDERR, ">&", \*OLDERR;
 
 ###############################################################################
 
-my $s = Test::Nginx::IMAP->new();
+my $s = Test::Nginx::IMAP->new(PeerAddr => '127.0.0.1:' . port(3));
 $s->ok('greeting');
 
 # error_log levels
@@ -128,7 +128,7 @@ is_deeply(levels($t, 'e_glob.log'), leve
 
 # syslog
 
-parse_syslog_message('syslog', get_syslog());
+parse_syslog_message('syslog', get_syslog(port(6)));
 
 is_deeply(levels($t, 's_glob.log'), levels($t, 'e_glob.log'),
 	'global syslog messages');
@@ -165,8 +165,6 @@ sub get_syslog {
 	my $data = '';
 	my ($s);
 
-	$port = 8080 unless defined $port;
-
 	eval {
 		local $SIG{ALRM} = sub { die "timeout\n" };
 		local $SIG{PIPE} = sub { die "sigpipe\n" };
@@ -183,7 +181,7 @@ sub get_syslog {
 		return undef;
 	}
 
-	Test::Nginx::IMAP->new(PeerAddr => "127.0.0.1:8145")->read();
+	Test::Nginx::IMAP->new(PeerAddr => '127.0.0.1:' . port(5))->read();
 
 	IO::Select->new($s)->can_read(1.5);
 	while (IO::Select->new($s)->can_read(0.1)) {
--- a/mail_imap.t
+++ b/mail_imap.t
@@ -28,7 +28,7 @@ local $SIG{PIPE} = 'IGNORE';
 
 my $t = Test::Nginx->new()
 	->has(qw/mail imap http rewrite/)->plan(9)
-	->run_daemon(\&Test::Nginx::IMAP::imap_test_daemon)
+	->run_daemon(\&Test::Nginx::IMAP::imap_test_daemon, port(2))
 	->write_file_expand('nginx.conf', <<'EOF')->run();
 
 %%TEST_GLOBALS%%
@@ -40,10 +40,10 @@ events {
 
 mail {
     proxy_pass_error_message  on;
-    auth_http  http://127.0.0.1:8080/mail/auth;
+    auth_http  http://127.0.0.1:%%PORT_0%%/mail/auth;
 
     server {
-        listen     127.0.0.1:8143;
+        listen     127.0.0.1:%%PORT_1%%;
         protocol   imap;
     }
 }
@@ -52,7 +52,7 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         location = /mail/auth {
@@ -69,7 +69,7 @@ http {
 
             add_header Auth-Status $reply;
             add_header Auth-Server 127.0.0.1;
-            add_header Auth-Port 8144;
+            add_header Auth-Port %%PORT_2%%;
             add_header Auth-Wait 1;
             return 204;
         }
@@ -80,7 +80,7 @@ EOF
 
 ###############################################################################
 
-my $s = Test::Nginx::IMAP->new();
+my $s = Test::Nginx::IMAP->new(PeerAddr => '127.0.0.1:' . port(1));
 $s->ok('greeting');
 
 # bad auth
@@ -98,7 +98,7 @@ my $s = Test::Nginx::IMAP->new();
 
 # auth login simple
 
-$s = Test::Nginx::IMAP->new();
+$s = Test::Nginx::IMAP->new(PeerAddr => '127.0.0.1:' . port(1));
 $s->read();
 
 $s->send('1 AUTHENTICATE LOGIN');
@@ -112,7 +112,7 @@ my $s = Test::Nginx::IMAP->new();
 
 # auth login with username
 
-$s = Test::Nginx::IMAP->new();
+$s = Test::Nginx::IMAP->new(PeerAddr => '127.0.0.1:' . port(1));
 $s->read();
 
 $s->send('1 AUTHENTICATE LOGIN ' . encode_base64('test@example.com', ''));
--- a/mail_imap_ssl.t
+++ b/mail_imap_ssl.t
@@ -35,7 +35,7 @@ local $SIG{PIPE} = 'IGNORE';
 
 my $t = Test::Nginx->new()
 	->has(qw/mail mail_ssl imap http rewrite/)->has_daemon('openssl')
-	->run_daemon(\&Test::Nginx::IMAP::imap_test_daemon)->plan(12);
+	->run_daemon(\&Test::Nginx::IMAP::imap_test_daemon, port(6))->plan(12);
 
 $t->write_file_expand('nginx.conf', <<'EOF');
 
@@ -48,19 +48,19 @@ events {
 
 mail {
     proxy_pass_error_message  on;
-    auth_http  http://127.0.0.1:8080/mail/auth;
+    auth_http  http://127.0.0.1:%%PORT_0%%/mail/auth;
     auth_http_pass_client_cert on;
 
     ssl_certificate_key 1.example.com.key;
     ssl_certificate 1.example.com.crt;
 
     server {
-        listen     127.0.0.1:8142;
+        listen     127.0.0.1:%%PORT_1%%;
         protocol   imap;
     }
 
     server {
-        listen     127.0.0.1:8143 ssl;
+        listen     127.0.0.1:%%PORT_2%% ssl;
         protocol   imap;
 
         ssl_verify_client on;
@@ -68,7 +68,7 @@ mail {
     }
 
     server {
-        listen     127.0.0.1:8145 ssl;
+        listen     127.0.0.1:%%PORT_3%% ssl;
         protocol   imap;
 
         ssl_verify_client optional;
@@ -76,7 +76,7 @@ mail {
     }
 
     server {
-        listen     127.0.0.1:8146 ssl;
+        listen     127.0.0.1:%%PORT_4%% ssl;
         protocol   imap;
 
         ssl_verify_client optional;
@@ -85,7 +85,7 @@ mail {
     }
 
     server {
-        listen     127.0.0.1:8147 ssl;
+        listen     127.0.0.1:%%PORT_5%% ssl;
         protocol   imap;
 
         ssl_verify_client optional_no_ca;
@@ -102,7 +102,7 @@ http {
                       '$http_auth_ssl_cert:$http_auth_pass';
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         location = /mail/auth {
@@ -110,7 +110,7 @@ http {
 
             add_header Auth-Status OK;
             add_header Auth-Server 127.0.0.1;
-            add_header Auth-Port 8144;
+            add_header Auth-Port %%PORT_6%%;
             add_header Auth-Wait 1;
             return 204;
         }
@@ -150,25 +150,25 @@ my %ssl = (
 
 # no ssl connection
 
-my $s = Test::Nginx::IMAP->new(PeerAddr => '127.0.0.1:8142');
+my $s = Test::Nginx::IMAP->new(PeerAddr => '127.0.0.1:' . port(1));
 $s->ok('plain connection');
 $s->send('1 AUTHENTICATE PLAIN ' . $cred->("s1"));
 
 # no cert
 
-$s = Test::Nginx::IMAP->new(PeerAddr => '127.0.0.1:8143', %ssl);
+$s = Test::Nginx::IMAP->new(PeerAddr => '127.0.0.1:' . port(2), %ssl);
 $s->check(qr/BYE No required SSL certificate/, 'no cert');
 
 # no cert with ssl_verify_client optional
 
-$s = Test::Nginx::IMAP->new(PeerAddr => '127.0.0.1:8145', %ssl);
+$s = Test::Nginx::IMAP->new(PeerAddr => '127.0.0.1:' . port(3), %ssl);
 $s->ok('no optional cert');
 $s->send('1 AUTHENTICATE PLAIN ' . $cred->("s2"));
 
 # wrong cert with ssl_verify_client optional
 
 $s = Test::Nginx::IMAP->new(
-	PeerAddr => '127.0.0.1:8145',
+	PeerAddr => '127.0.0.1:' . port(3),
 	SSL_cert_file => "$d/1.example.com.crt",
 	SSL_key_file => "$d/1.example.com.key",
 	%ssl,
@@ -178,7 +178,7 @@ my $s = Test::Nginx::IMAP->new(PeerAddr 
 # wrong cert with ssl_verify_client optional_no_ca
 
 $s = Test::Nginx::IMAP->new(
-	PeerAddr => '127.0.0.1:8147',
+	PeerAddr => '127.0.0.1:'  . port(5),
 	SSL_cert_file => "$d/1.example.com.crt",
 	SSL_key_file => "$d/1.example.com.key",
 	%ssl,
@@ -189,7 +189,7 @@ my $s = Test::Nginx::IMAP->new(PeerAddr 
 # matching cert with ssl_verify_client optional
 
 $s = Test::Nginx::IMAP->new(
-	PeerAddr => '127.0.0.1:8145',
+	PeerAddr => '127.0.0.1:' . port(3),
 	SSL_cert_file => "$d/2.example.com.crt",
 	SSL_key_file => "$d/2.example.com.key",
 	%ssl,
@@ -200,7 +200,7 @@ my $s = Test::Nginx::IMAP->new(PeerAddr 
 # trusted cert with ssl_verify_client optional
 
 $s = Test::Nginx::IMAP->new(
-	PeerAddr => '127.0.0.1:8146',
+	PeerAddr => '127.0.0.1:' . port(4),
 	SSL_cert_file => "$d/3.example.com.crt",
 	SSL_key_file => "$d/3.example.com.key",
 	%ssl,
--- a/mail_pop3.t
+++ b/mail_pop3.t
@@ -28,7 +28,7 @@ local $SIG{PIPE} = 'IGNORE';
 
 my $t = Test::Nginx->new()
 	->has(qw/mail pop3 http rewrite/)->plan(8)
-	->run_daemon(\&Test::Nginx::POP3::pop3_test_daemon)
+	->run_daemon(\&Test::Nginx::POP3::pop3_test_daemon, port(2))
 	->write_file_expand('nginx.conf', <<'EOF')->run();
 
 %%TEST_GLOBALS%%
@@ -40,10 +40,10 @@ events {
 
 mail {
     proxy_pass_error_message  on;
-    auth_http  http://127.0.0.1:8080/mail/auth;
+    auth_http  http://127.0.0.1:%%PORT_0%%/mail/auth;
 
     server {
-        listen     127.0.0.1:8110;
+        listen     127.0.0.1:%%PORT_1%%;
         protocol   pop3;
     }
 }
@@ -52,7 +52,7 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         location = /mail/auth {
@@ -69,7 +69,7 @@ http {
 
             add_header Auth-Status $reply;
             add_header Auth-Server 127.0.0.1;
-            add_header Auth-Port 8111;
+            add_header Auth-Port %%PORT_2%%;
             add_header Auth-Wait 1;
             return 204;
         }
@@ -80,7 +80,7 @@ EOF
 
 ###############################################################################
 
-my $s = Test::Nginx::POP3->new();
+my $s = Test::Nginx::POP3->new(PeerAddr => '127.0.0.1:' . port(1));
 $s->ok('greeting');
 
 # auth plain
@@ -93,7 +93,7 @@ my $s = Test::Nginx::POP3->new();
 
 # auth login simple
 
-$s = Test::Nginx::POP3->new();
+$s = Test::Nginx::POP3->new(PeerAddr => '127.0.0.1:' . port(1));
 $s->read();
 
 $s->send('AUTH LOGIN');
@@ -107,7 +107,7 @@ my $s = Test::Nginx::POP3->new();
 
 # auth login with username
 
-$s = Test::Nginx::POP3->new();
+$s = Test::Nginx::POP3->new(PeerAddr => '127.0.0.1:' . port(1));
 $s->read();
 
 $s->send('AUTH LOGIN ' . encode_base64('test@example.com', ''));
--- a/mail_resolver.t
+++ b/mail_resolver.t
@@ -26,7 +26,7 @@ select STDOUT; $| = 1;
 local $SIG{PIPE} = 'IGNORE';
 
 my $t = Test::Nginx->new()->has(qw/mail smtp http rewrite/)
-	->run_daemon(\&Test::Nginx::SMTP::smtp_test_daemon);
+	->run_daemon(\&Test::Nginx::SMTP::smtp_test_daemon, port(15));
 
 $t->write_file_expand('nginx.conf', <<'EOF');
 
@@ -38,7 +38,7 @@ events {
 }
 
 mail {
-    auth_http    http://127.0.0.1:8080/mail/auth;
+    auth_http    http://127.0.0.1:%%PORT_0%%/mail/auth;
     smtp_auth    none;
     server_name  locahost;
 
@@ -46,46 +46,47 @@ mail {
     resolver_timeout 2s;
 
     server {
-        listen    127.0.0.1:8025;
+        listen    127.0.0.1:%%PORT_1%%;
         protocol  smtp;
-        resolver  127.0.0.1:8081 127.0.0.1:8082 127.0.0.1:8083;
+        resolver  127.0.0.1:%%PORT_8_UDP%% 127.0.0.1:%%PORT_9_UDP%%
+                  127.0.0.1:%%PORT_10_UDP%%;
     }
 
     server {
-        listen    127.0.0.1:8027;
+        listen    127.0.0.1:%%PORT_2%%;
         protocol  smtp;
-        resolver  127.0.0.1:8082;
+        resolver  127.0.0.1:%%PORT_9_UDP%%;
     }
 
     server {
-        listen    127.0.0.1:8028;
+        listen    127.0.0.1:%%PORT_3%%;
         protocol  smtp;
-        resolver  127.0.0.1:8083;
+        resolver  127.0.0.1:%%PORT_10_UDP%%;
 
     }
 
     server {
-        listen    127.0.0.1:8029;
+        listen    127.0.0.1:%%PORT_4%%;
         protocol  smtp;
-        resolver  127.0.0.1:8084;
+        resolver  127.0.0.1:%%PORT_11_UDP%%;
     }
 
     server {
-        listen    127.0.0.1:8030;
+        listen    127.0.0.1:%%PORT_5%%;
         protocol  smtp;
-        resolver  127.0.0.1:8085;
+        resolver  127.0.0.1:%%PORT_12_UDP%%;
     }
 
     server {
-        listen    127.0.0.1:8031;
+        listen    127.0.0.1:%%PORT_6%%;
         protocol  smtp;
-        resolver  127.0.0.1:8086;
+        resolver  127.0.0.1:%%PORT_13_UDP%%;
     }
 
     server {
-        listen    127.0.0.1:8032;
+        listen    127.0.0.1:%%PORT_7%%;
         protocol  smtp;
-        resolver  127.0.0.1:8087;
+        resolver  127.0.0.1:%%PORT_14_UDP%%;
     }
 
 }
@@ -94,7 +95,7 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         location = /mail/auth {
@@ -106,7 +107,7 @@ http {
 
             add_header Auth-Status $reply;
             add_header Auth-Server 127.0.0.1;
-            add_header Auth-Port 8026;
+            add_header Auth-Port %%PORT_15%%;
             return 204;
         }
     }
@@ -114,13 +115,13 @@ http {
 
 EOF
 
-for (8081 .. 8087) {
-	$t->run_daemon(\&dns_daemon, $_, $t);
+for (8 .. 14) {
+	$t->run_daemon(\&dns_daemon, port($_), $t);
 }
 $t->run();
 
-for (8081 .. 8087) {
-	$t->waitforfile($t->testdir . "/$_");
+for (8 .. 14) {
+	$t->waitforfile($t->testdir . '/' . port($_));
 }
 
 $t->plan(8);
@@ -129,7 +130,7 @@ for (8081 .. 8087) {
 
 # PTR
 
-my $s = Test::Nginx::SMTP->new();
+my $s = Test::Nginx::SMTP->new(PeerAddr => '127.0.0.1:' . port(1));
 $s->read();
 $s->send('EHLO example.com');
 $s->read();
@@ -142,9 +143,9 @@ my $s = Test::Nginx::SMTP->new();
 $s->send('QUIT');
 $s->read();
 
-# Cached PTR prevents from querying bad ns on port 8083
+# Cached PTR prevents from querying bad ns on the first port
 
-$s = Test::Nginx::SMTP->new();
+$s = Test::Nginx::SMTP->new(PeerAddr => '127.0.0.1:' . port(1));
 $s->read();
 $s->send('EHLO example.com');
 $s->read();
@@ -159,7 +160,7 @@ my $s = Test::Nginx::SMTP->new();
 
 # SERVFAIL
 
-$s = Test::Nginx::SMTP->new(PeerAddr => "127.0.0.1:8027");
+$s = Test::Nginx::SMTP->new(PeerAddr => '127.0.0.1:' . port(2));
 $s->read();
 $s->send('EHLO example.com');
 $s->read();
@@ -174,7 +175,7 @@ my $s = Test::Nginx::SMTP->new();
 
 # PTR with zero length RDATA
 
-$s = Test::Nginx::SMTP->new(PeerAddr => "127.0.0.1:8028");
+$s = Test::Nginx::SMTP->new(PeerAddr => '127.0.0.1:' . port(3));
 $s->read();
 $s->send('EHLO example.com');
 $s->read();
@@ -192,7 +193,7 @@ my $s = Test::Nginx::SMTP->new();
 TODO: {
 local $TODO = 'support for CNAME RR';
 
-$s = Test::Nginx::SMTP->new(PeerAddr => "127.0.0.1:8029");
+$s = Test::Nginx::SMTP->new(PeerAddr => '127.0.0.1:' . port(4));
 $s->read();
 $s->send('EHLO example.com');
 $s->read();
@@ -213,7 +214,7 @@ TODO: {
 local $TODO = 'support for uncompressed name in PTR'
 	unless $t->has_version('1.9.11');
 
-$s = Test::Nginx::SMTP->new(PeerAddr => "127.0.0.1:8030");
+$s = Test::Nginx::SMTP->new(PeerAddr => '127.0.0.1:' . port(5));
 $s->read();
 $s->send('EHLO example.com');
 $s->read();
@@ -231,7 +232,7 @@ local $TODO = 'support for uncompressed 
 TODO: {
 local $TODO = 'PTR type checking' unless $t->has_version('1.9.11');
 
-$s = Test::Nginx::SMTP->new(PeerAddr => "127.0.0.1:8031");
+$s = Test::Nginx::SMTP->new(PeerAddr => '127.0.0.1:' . port(6));
 $s->read();
 $s->send('EHLO example.com');
 $s->read();
@@ -251,7 +252,7 @@ local $TODO = 'PTR type checking' unless
 TODO: {
 local $TODO = 'not yet' unless $t->has_version('1.9.11');
 
-$s = Test::Nginx::SMTP->new(PeerAddr => "127.0.0.1:8032");
+$s = Test::Nginx::SMTP->new(PeerAddr => '127.0.0.1:' . port(7));
 $s->read();
 $s->send('EHLO example.com');
 $s->read();
@@ -307,34 +308,34 @@ sub reply_handler {
 		push @rdata, rd_addr($ttl, '127.0.0.1');
 
 	} elsif ($name eq '1.0.0.127.in-addr.arpa' && $type == PTR) {
-		if ($port == 8081) {
+		if ($port == port(8)) {
 			push @rdata, rd_name(PTR, $ttl, 'a.example.net');
 
-		} elsif ($port == 8082) {
+		} elsif ($port == port(9)) {
 			$rcode = SERVFAIL;
 
-		} elsif ($port == 8083) {
+		} elsif ($port == port(10)) {
 			# zero length RDATA
 
 			push @rdata, pack("n3N n", 0xc00c, PTR, IN, $ttl, 0);
 
-		} elsif ($port == 8084) {
+		} elsif ($port == port(11)) {
 			# PTR answered with CNAME
 
 			push @rdata, rd_name(CNAME, $ttl,
 				'1.1.0.0.127.in-addr.arpa');
 
-		} elsif ($port == 8085) {
+		} elsif ($port == port(12)) {
 			# uncompressed answer
 
 			push @rdata, pack("(C/a*)6x n2N n(C/a*)3x",
 				('1', '0', '0', '127', 'in-addr', 'arpa'),
 				PTR, IN, $ttl, 15, ('a', 'example', 'net'));
 
-		} elsif ($port == 8086) {
+		} elsif ($port == port(13)) {
 			push @rdata, rd_name(DNAME, $ttl, 'a.example.net');
 
-		} elsif ($port == 8087) {
+		} elsif ($port == port(14)) {
 			# PTR answered with CNAME+PTR
 
 			push @rdata, rd_name(CNAME, $ttl,
--- a/mail_smtp.t
+++ b/mail_smtp.t
@@ -29,7 +29,7 @@ local $SIG{PIPE} = 'IGNORE';
 
 my $t = Test::Nginx->new()
 	->has(qw/mail smtp http rewrite/)->plan(25)
-	->run_daemon(\&Test::Nginx::SMTP::smtp_test_daemon)
+	->run_daemon(\&Test::Nginx::SMTP::smtp_test_daemon, port(2))
 	->write_file_expand('nginx.conf', <<'EOF')->run();
 
 %%TEST_GLOBALS%%
@@ -41,11 +41,11 @@ events {
 
 mail {
     proxy_pass_error_message  on;
-    auth_http  http://127.0.0.1:8080/mail/auth;
+    auth_http  http://127.0.0.1:%%PORT_0%%/mail/auth;
     xclient    off;
 
     server {
-        listen     127.0.0.1:8025;
+        listen     127.0.0.1:%%PORT_1%%;
         protocol   smtp;
         smtp_auth  login plain none;
     }
@@ -55,7 +55,7 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         location = /mail/auth {
@@ -72,7 +72,7 @@ http {
 
             add_header Auth-Status $reply;
             add_header Auth-Server 127.0.0.1;
-            add_header Auth-Port 8026;
+            add_header Auth-Port %%PORT_2%%;
             add_header Auth-Wait 1;
             return 204;
         }
@@ -83,7 +83,7 @@ EOF
 
 ###############################################################################
 
-my $s = Test::Nginx::SMTP->new();
+my $s = Test::Nginx::SMTP->new(PeerAddr => '127.0.0.1:' . port(1));
 $s->check(qr/^220 /, "greeting");
 
 $s->send('EHLO example.com');
@@ -111,7 +111,7 @@ my $s = Test::Nginx::SMTP->new();
 
 # Try auth login in simple form
 
-$s = Test::Nginx::SMTP->new();
+$s = Test::Nginx::SMTP->new(PeerAddr => '127.0.0.1:' . port(1));
 $s->read();
 $s->send('EHLO example.com');
 $s->read();
@@ -128,7 +128,7 @@ my $s = Test::Nginx::SMTP->new();
 # [MS-XLOGIN]: SMTP Protocol AUTH LOGIN Extension Specification
 # http://download.microsoft.com/download/5/D/D/5DD33FDF-91F5-496D-9884-0A0B0EE698BB/%5BMS-XLOGIN%5D.pdf
 
-$s = Test::Nginx::SMTP->new();
+$s = Test::Nginx::SMTP->new(PeerAddr => '127.0.0.1:' . port(1));
 $s->read();
 $s->send('EHLO example.com');
 $s->read();
@@ -140,7 +140,7 @@ my $s = Test::Nginx::SMTP->new();
 
 # Try auth plain with pipelining
 
-$s = Test::Nginx::SMTP->new();
+$s = Test::Nginx::SMTP->new(PeerAddr => '127.0.0.1:' . port(1));
 $s->read();
 $s->send('EHLO example.com');
 $s->read();
@@ -164,7 +164,7 @@ my $s = Test::Nginx::SMTP->new();
 
 # Try auth none
 
-$s = Test::Nginx::SMTP->new();
+$s = Test::Nginx::SMTP->new(PeerAddr => '127.0.0.1:' . port(1));
 $s->read();
 $s->send('EHLO example.com');
 $s->read();
@@ -180,7 +180,7 @@ my $s = Test::Nginx::SMTP->new();
 
 # Auth none with pipelining
 
-$s = Test::Nginx::SMTP->new();
+$s = Test::Nginx::SMTP->new(PeerAddr => '127.0.0.1:' . port(1));
 $s->read();
 $s->send('EHLO example.com');
 $s->read();
@@ -195,7 +195,7 @@ my $s = Test::Nginx::SMTP->new();
 
 # Connection must stay even if error returned to rcpt to command
 
-$s = Test::Nginx::SMTP->new();
+$s = Test::Nginx::SMTP->new(PeerAddr => '127.0.0.1:' . port(1));
 $s->read();
 $s->send('EHLO example.com');
 $s->read();
@@ -211,7 +211,7 @@ my $s = Test::Nginx::SMTP->new();
 
 # Make sure command split into many packets processed correctly
 
-$s = Test::Nginx::SMTP->new();
+$s = Test::Nginx::SMTP->new(PeerAddr => '127.0.0.1:' . port(1));
 $s->read();
 
 $s->print('HEL');
--- a/mail_smtp_greeting_delay.t
+++ b/mail_smtp_greeting_delay.t
@@ -34,11 +34,11 @@ events {
 
 mail {
     proxy_pass_error_message  on;
-    auth_http  http://127.0.0.1:8080/mail/auth;
+    auth_http  http://127.0.0.1:%%PORT_0%%/mail/auth;
     xclient    off;
 
     server {
-        listen     127.0.0.1:8025;
+        listen     127.0.0.1:%%PORT_1%%;
         protocol   smtp;
         smtp_greeting_delay  1s;
     }
@@ -51,7 +51,7 @@ EOF
 # With smtp_greeting_delay session expected to be closed after first error
 # message if client sent something before greeting.
 
-my $s = Test::Nginx::SMTP->new();
+my $s = Test::Nginx::SMTP->new(PeerAddr => '127.0.0.1:' . port(1));
 $s->send('HELO example.com');
 $s->check(qr/^5.. /, "command before greeting - session must be rejected");
 ok($s->eof(), "session have to be closed");
--- a/mail_smtp_xclient.t
+++ b/mail_smtp_xclient.t
@@ -25,7 +25,7 @@ select STDOUT; $| = 1;
 local $SIG{PIPE} = 'IGNORE';
 
 my $t = Test::Nginx->new()->has(qw/mail smtp http rewrite/)->plan(6)
-	->run_daemon(\&Test::Nginx::SMTP::smtp_test_daemon)
+	->run_daemon(\&Test::Nginx::SMTP::smtp_test_daemon, port(2))
 	->write_file_expand('nginx.conf', <<'EOF')->run();
 
 %%TEST_GLOBALS%%
@@ -37,11 +37,11 @@ events {
 
 mail {
     proxy_pass_error_message  on;
-    auth_http  http://127.0.0.1:8080/mail/auth;
+    auth_http  http://127.0.0.1:%%PORT_0%%/mail/auth;
     xclient    on;
 
     server {
-        listen     127.0.0.1:8025;
+        listen     127.0.0.1:%%PORT_1%%;
         protocol   smtp;
         smtp_auth  login plain none;
     }
@@ -51,13 +51,13 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         location = /mail/auth {
             add_header Auth-Status OK;
             add_header Auth-Server 127.0.0.1;
-            add_header Auth-Port   8026;
+            add_header Auth-Port   %%PORT_2%%;
             add_header Auth-Wait   1;
             return 204;
         }
@@ -82,14 +82,14 @@ EOF
 
 # xclient
 
-my $s = Test::Nginx::SMTP->new();
+my $s = Test::Nginx::SMTP->new(PeerAddr => '127.0.0.1:' . port(1));
 $s->read();
 $s->send('AUTH PLAIN ' . encode_base64("\0test\@example.com\0secret", ''));
 $s->authok('xclient');
 
 # xclient, helo
 
-$s = Test::Nginx::SMTP->new();
+$s = Test::Nginx::SMTP->new(PeerAddr => '127.0.0.1:' . port(1));
 $s->read();
 $s->send('HELO example.com');
 $s->read();
@@ -98,7 +98,7 @@ my $s = Test::Nginx::SMTP->new();
 
 # xclient, ehlo
 
-$s = Test::Nginx::SMTP->new();
+$s = Test::Nginx::SMTP->new(PeerAddr => '127.0.0.1:' . port(1));
 $s->read();
 $s->send('EHLO example.com');
 $s->read();
@@ -107,7 +107,7 @@ my $s = Test::Nginx::SMTP->new();
 
 # xclient, from, rcpt
 
-$s = Test::Nginx::SMTP->new();
+$s = Test::Nginx::SMTP->new(PeerAddr => '127.0.0.1:' . port(1));
 $s->read();
 $s->send('MAIL FROM:<test@example.com>');
 $s->read();
@@ -116,7 +116,7 @@ my $s = Test::Nginx::SMTP->new();
 
 # xclient, helo, from, rcpt
 
-$s = Test::Nginx::SMTP->new();
+$s = Test::Nginx::SMTP->new(PeerAddr => '127.0.0.1:' . port(1));
 $s->read();
 $s->send('HELO example.com');
 $s->read();
@@ -127,7 +127,7 @@ my $s = Test::Nginx::SMTP->new();
 
 # xclient, ehlo, from, rcpt
 
-$s = Test::Nginx::SMTP->new();
+$s = Test::Nginx::SMTP->new(PeerAddr => '127.0.0.1:' . port(1));
 $s->read();
 $s->send('EHLO example.com');
 $s->read();
--- a/map.t
+++ b/map.t
@@ -64,7 +64,7 @@ http {
     }
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         location / {
--- a/map_complex.t
+++ b/map_complex.t
@@ -48,7 +48,7 @@ http {
     }
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         location / {
--- a/memcached.t
+++ b/memcached.t
@@ -39,18 +39,18 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         location / {
             set $memcached_key $uri;
-            memcached_pass 127.0.0.1:8081;
+            memcached_pass 127.0.0.1:%%PORT_1%%;
         }
 
         location /next {
             set $memcached_key $uri;
             memcached_next_upstream  not_found;
-            memcached_pass 127.0.0.1:8081;
+            memcached_pass 127.0.0.1:%%PORT_1%%;
         }
     }
 }
@@ -62,22 +62,22 @@ my @memopts = ();
 
 if ($memhelp =~ /repcached/) {
 	# repcached patch adds additional listen socket
-	push @memopts, '-X', '8082';
+	push @memopts, '-X', port(2);
 }
 if ($memhelp =~ /-U/) {
 	# UDP port is on by default in memcached 1.2.7+
 	push @memopts, '-U', '0';
 }
 
-$t->run_daemon('memcached', '-l', '127.0.0.1', '-p', '8081', @memopts);
+$t->run_daemon('memcached', '-l', '127.0.0.1', '-p', port(1), @memopts);
 $t->run();
 
-$t->waitforsocket('127.0.0.1:8081')
+$t->waitforsocket('127.0.0.1:' . port(1))
 	or die "Can't start memcached";
 
 ###############################################################################
 
-my $memd = Cache::Memcached->new(servers => [ '127.0.0.1:8081' ],
+my $memd = Cache::Memcached->new(servers => [ '127.0.0.1:' . port(1) ],
 	connect_timeout => 1.0);
 $memd->set('/', 'SEE-THIS')
 	or die "can't put value into memcached: $!";
--- a/memcached_fake.t
+++ b/memcached_fake.t
@@ -36,12 +36,12 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         location / {
             set $memcached_key $uri;
-            memcached_pass 127.0.0.1:8081;
+            memcached_pass 127.0.0.1:%%PORT_1%%;
         }
 
         location /ssi {
@@ -57,7 +57,7 @@ EOF
 $t->run_daemon(\&memcached_fake_daemon);
 $t->run();
 
-$t->waitforsocket('127.0.0.1:8081')
+$t->waitforsocket('127.0.0.1:' . port(1))
 	or die "Can't start fake memcached";
 
 ###############################################################################
@@ -73,7 +73,7 @@ like(`grep -F '[error]' ${\($t->testdir(
 sub memcached_fake_daemon {
 	my $server = IO::Socket::INET->new(
 		Proto => 'tcp',
-		LocalAddr => '127.0.0.1:8081',
+		LocalAddr => '127.0.0.1:' . port(1),
 		Listen => 5,
 		Reuse => 1
 	)
--- a/memcached_keepalive.t
+++ b/memcached_keepalive.t
@@ -39,24 +39,24 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     upstream memd {
-        server 127.0.0.1:8081;
+        server 127.0.0.1:%%PORT_1%%;
         keepalive 1;
     }
 
     upstream memd3 {
-        server 127.0.0.1:8081;
-        server 127.0.0.1:8082;
+        server 127.0.0.1:%%PORT_1%%;
+        server 127.0.0.1:%%PORT_2%%;
         keepalive 1;
     }
 
     upstream memd4 {
-        server 127.0.0.1:8081;
-        server 127.0.0.1:8082;
+        server 127.0.0.1:%%PORT_1%%;
+        server 127.0.0.1:%%PORT_2%%;
         keepalive 10;
     }
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         location / {
@@ -92,8 +92,8 @@ if ($memhelp =~ /repcached/) {
 	# repcached patches adds additional listen socket memcached
 	# that should be different too
 
-	push @memopts1, '-X', '8091';
-	push @memopts2, '-X', '8092';
+	push @memopts1, '-X', port(3);
+	push @memopts2, '-X', port(4);
 }
 if ($memhelp =~ /-U/) {
 	# UDP ports no longer off by default in memcached 1.2.7+
@@ -108,21 +108,21 @@ if ($memhelp =~ /-t/) {
 	push @memopts2, '-t', '1';
 }
 
-$t->run_daemon('memcached', '-l', '127.0.0.1', '-p', '8081', @memopts1);
-$t->run_daemon('memcached', '-l', '127.0.0.1', '-p', '8082', @memopts2);
+$t->run_daemon('memcached', '-l', '127.0.0.1', '-p', port(1), @memopts1);
+$t->run_daemon('memcached', '-l', '127.0.0.1', '-p', port(2), @memopts2);
 
 $t->run();
 
-$t->waitforsocket('127.0.0.1:8081')
+$t->waitforsocket('127.0.0.1:' . port(1))
 	or die "Unable to start memcached";
-$t->waitforsocket('127.0.0.1:8082')
+$t->waitforsocket('127.0.0.1:' . port(2))
 	or die "Unable to start second memcached";
 
 ###############################################################################
 
-my $memd1 = Cache::Memcached->new(servers => [ '127.0.0.1:8081' ],
+my $memd1 = Cache::Memcached->new(servers => [ '127.0.0.1:' . port(1) ],
 	connect_timeout => 1.0);
-my $memd2 = Cache::Memcached->new(servers => [ '127.0.0.1:8082' ],
+my $memd2 = Cache::Memcached->new(servers => [ '127.0.0.1:' . port(2) ],
 	connect_timeout => 1.0);
 
 $memd1->set('/', 'SEE-THIS');
--- a/memcached_keepalive_stale.t
+++ b/memcached_keepalive_stale.t
@@ -41,12 +41,12 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     upstream memd {
-        server 127.0.0.1:8081;
+        server 127.0.0.1:%%PORT_1%%;
         keepalive 1;
     }
 
     server {
-        listen       127.0.0.1:8080 sndbuf=32k;
+        listen       127.0.0.1:%%PORT_0%% sndbuf=32k;
         server_name  localhost;
 
         location / {
@@ -65,7 +65,7 @@ if ($memhelp =~ /repcached/) {
 	# repcached patches adds additional listen socket memcached
 	# that should be different too
 
-	push @memopts1, '-X', '8091';
+	push @memopts1, '-X', port(2);
 }
 if ($memhelp =~ /-U/) {
 	# UDP ports no longer off by default in memcached 1.2.7+
@@ -78,16 +78,16 @@ if ($memhelp =~ /-t/) {
 	push @memopts1, '-t', '1';
 }
 
-$t->run_daemon('memcached', '-l', '127.0.0.1', '-p', '8081', @memopts1);
+$t->run_daemon('memcached', '-l', '127.0.0.1', '-p', port(1), @memopts1);
 
 $t->run();
 
-$t->waitforsocket('127.0.0.1:8081')
+$t->waitforsocket('127.0.0.1:' . port(1))
 	or die "Unable to start memcached";
 
 ###############################################################################
 
-my $memd1 = Cache::Memcached->new(servers => [ '127.0.0.1:8081' ],
+my $memd1 = Cache::Memcached->new(servers => [ '127.0.0.1:' . port(1) ],
 	connect_timeout => 1.0);
 
 # It's possible that stale events occur, i.e. read event handler called
--- a/mp4.t
+++ b/mp4.t
@@ -40,7 +40,7 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         location / {
--- a/not_modified.t
+++ b/not_modified.t
@@ -35,7 +35,7 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         location / {
--- a/not_modified_proxy.t
+++ b/not_modified_proxy.t
@@ -47,7 +47,7 @@ http {
     proxy_set_header If-None-Match "";
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         location / {
@@ -58,11 +58,11 @@ http {
         }
 
         location /proxy/ {
-            proxy_pass http://127.0.0.1:8080/;
+            proxy_pass http://127.0.0.1:%%PORT_0%%/;
         }
 
         location /cache/ {
-            proxy_pass http://127.0.0.1:8080/;
+            proxy_pass http://127.0.0.1:%%PORT_0%%/;
             proxy_cache one;
             proxy_cache_valid 200 1y;
         }
--- a/perl.t
+++ b/perl.t
@@ -37,7 +37,7 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         location / {
--- a/perl_gzip.t
+++ b/perl_gzip.t
@@ -38,7 +38,7 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         gzip on;
--- a/post_action.t
+++ b/post_action.t
@@ -37,7 +37,7 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         location / {
@@ -53,7 +53,7 @@ http {
         }
 
         location /post.remote {
-            proxy_pass http://127.0.0.1:8080/post.html;
+            proxy_pass http://127.0.0.1:%%PORT_0%%/post.html;
         }
     }
 }
--- a/proxy.t
+++ b/proxy.t
@@ -38,15 +38,15 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     upstream u {
-        server 127.0.0.1:8081;
+        server 127.0.0.1:%%PORT_1%%;
     }
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         location / {
-            proxy_pass http://127.0.0.1:8081;
+            proxy_pass http://127.0.0.1:%%PORT_1%%;
             proxy_read_timeout 1s;
             proxy_connect_timeout 2s;
         }
@@ -61,7 +61,7 @@ http {
 EOF
 
 $t->run_daemon(\&http_daemon);
-$t->run()->waitforsocket('127.0.0.1:8081');
+$t->run()->waitforsocket('127.0.0.1:' . port(1));
 
 ###############################################################################
 
@@ -70,7 +70,8 @@ like(http_get('/multi'), qr/AND-THIS/, '
 
 unlike(http_head('/'), qr/SEE-THIS/, 'proxy head request');
 
-like(http_get('/var?b=127.0.0.1:8081/'), qr/SEE-THIS/, 'proxy with variables');
+like(http_get('/var?b=127.0.0.1:' . port(1) . '/'), qr/SEE-THIS/,
+	'proxy with variables');
 like(http_get('/var?b=u/'), qr/SEE-THIS/, 'proxy with variables to upstream');
 
 SKIP: {
@@ -98,7 +99,7 @@ like(http_get('/', socket => $s), qr/200
 sub http_daemon {
 	my $server = IO::Socket::INET->new(
 		Proto => 'tcp',
-		LocalHost => '127.0.0.1:8081',
+		LocalHost => '127.0.0.1:' . port(1),
 		Listen => 5,
 		Reuse => 1
 	)
--- a/proxy_bind.t
+++ b/proxy_bind.t
@@ -40,33 +40,33 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen          127.0.0.1:8080;
+        listen          127.0.0.1:%%PORT_0%%;
         server_name     localhost;
 
         proxy_bind      127.0.0.2;
 
         location / {
             proxy_bind  127.0.0.1;
-            proxy_pass  http://127.0.0.1:8081/;
+            proxy_pass  http://127.0.0.1:%%PORT_1%%/;
         }
 
         location /inherit {
-            proxy_pass  http://127.0.0.1:8081/;
+            proxy_pass  http://127.0.0.1:%%PORT_1%%/;
         }
 
         location /off {
             proxy_bind  off;
-            proxy_pass  http://127.0.0.1:8081/;
+            proxy_pass  http://127.0.0.1:%%PORT_1%%/;
         }
 
         location /var {
             proxy_bind  $arg_b;
-            proxy_pass  http://127.0.0.1:8081/;
+            proxy_pass  http://127.0.0.1:%%PORT_1%%/;
         }
     }
 
     server {
-        listen          127.0.0.1:8081;
+        listen          127.0.0.1:%%PORT_1%%;
         server_name     localhost;
 
         location / {
--- a/proxy_bind_transparent.t
+++ b/proxy_bind_transparent.t
@@ -42,17 +42,17 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen          127.0.0.1:8080;
+        listen          127.0.0.1:%%PORT_0%%;
         server_name     localhost;
 
         location / {
             proxy_bind  127.0.0.2 transparent;
-            proxy_pass  http://127.0.0.1:8081/;
+            proxy_pass  http://127.0.0.1:%%PORT_1%%/;
         }
     }
 
     server {
-        listen          127.0.0.1:8081;
+        listen          127.0.0.1:%%PORT_1%%;
         server_name     localhost;
 
         location / {
--- a/proxy_cache.t
+++ b/proxy_cache.t
@@ -38,14 +38,14 @@ http {
                        keys_zone=NAME:1m;
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         gzip on;
         gzip_min_length 0;
 
         location / {
-            proxy_pass    http://127.0.0.1:8081;
+            proxy_pass    http://127.0.0.1:%%PORT_1%%;
 
             proxy_cache   NAME;
 
@@ -64,7 +64,7 @@ http {
         }
     }
     server {
-        listen       127.0.0.1:8081;
+        listen       127.0.0.1:%%PORT_1%%;
         server_name  localhost;
 
         location / {
--- a/proxy_cache_bypass.t
+++ b/proxy_cache_bypass.t
@@ -37,11 +37,11 @@ http {
     proxy_cache_path %%TESTDIR%%/cache keys_zone=one:1m;
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         location / {
-            proxy_pass http://127.0.0.1:8081;
+            proxy_pass http://127.0.0.1:%%PORT_1%%;
 
             proxy_cache one;
             proxy_cache_key $uri;
@@ -60,7 +60,7 @@ http {
     }
 
     server {
-        listen       127.0.0.1:8081;
+        listen       127.0.0.1:%%PORT_1%%;
         server_name  localhost;
 
         location / {
--- a/proxy_cache_chunked.t
+++ b/proxy_cache_chunked.t
@@ -40,11 +40,11 @@ http {
     proxy_cache_path %%TESTDIR%%/cache keys_zone=NAME:1m;
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         location / {
-            proxy_pass http://127.0.0.1:8081;
+            proxy_pass http://127.0.0.1:%%PORT_1%%;
             proxy_http_version 1.1;
             proxy_cache NAME;
             proxy_cache_valid any 1m;
@@ -56,7 +56,7 @@ http {
 EOF
 
 $t->run_daemon(\&http_chunked_daemon);
-$t->run()->waitforsocket('127.0.0.1:8081');
+$t->run()->waitforsocket('127.0.0.1:' . port(1));
 
 ###############################################################################
 
@@ -68,7 +68,7 @@ like(http_get("/"), qr/SEE-THIS.*HIT/s, 
 sub http_chunked_daemon {
 	my $server = IO::Socket::INET->new(
 		Proto => 'tcp',
-		LocalAddr => '127.0.0.1:8081',
+		LocalAddr => '127.0.0.1:' . port(1),
 		Listen => 5,
 		Reuse => 1
 	)
--- a/proxy_cache_convert_head.t
+++ b/proxy_cache_convert_head.t
@@ -39,7 +39,7 @@ http {
                        keys_zone=NAME:1m;
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         proxy_cache   NAME;
@@ -51,22 +51,22 @@ http {
         add_header X-Cache-Status $upstream_cache_status;
 
         location / {
-            proxy_pass http://127.0.0.1:8081/t.html;
+            proxy_pass http://127.0.0.1:%%PORT_1%%/t.html;
             proxy_cache_convert_head   off;
 
             location /inner {
-                proxy_pass http://127.0.0.1:8081/t.html;
+                proxy_pass http://127.0.0.1:%%PORT_1%%/t.html;
                 proxy_cache_convert_head on;
             }
         }
 
         location /on {
-            proxy_pass http://127.0.0.1:8081/t.html;
+            proxy_pass http://127.0.0.1:%%PORT_1%%/t.html;
             proxy_cache_convert_head on;
         }
     }
     server {
-        listen       127.0.0.1:8081;
+        listen       127.0.0.1:%%PORT_1%%;
         server_name  localhost;
 
         location / {
--- a/proxy_cache_lock.t
+++ b/proxy_cache_lock.t
@@ -38,18 +38,18 @@ http {
                        keys_zone=NAME:1m;
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         location / {
-            proxy_pass    http://127.0.0.1:8081;
+            proxy_pass    http://127.0.0.1:%%PORT_1%%;
             proxy_cache   NAME;
 
             proxy_cache_lock on;
         }
 
         location /timeout {
-            proxy_pass    http://127.0.0.1:8081;
+            proxy_pass    http://127.0.0.1:%%PORT_1%%;
             proxy_cache   NAME;
 
             proxy_cache_lock on;
@@ -57,7 +57,7 @@ http {
         }
 
         location /nolock {
-            proxy_pass    http://127.0.0.1:8081;
+            proxy_pass    http://127.0.0.1:%%PORT_1%%;
             proxy_cache   NAME;
         }
     }
@@ -69,7 +69,7 @@ EOF
 
 $t->run();
 
-$t->waitforsocket('127.0.0.1:8081');
+$t->waitforsocket('127.0.0.1:' . port(1));
 
 ###############################################################################
 
@@ -126,7 +126,7 @@ like(http_get('/nolock'), qr/request 3/,
 sub http_fake_daemon {
 	my $server = IO::Socket::INET->new(
 		Proto => 'tcp',
-		LocalAddr => '127.0.0.1:8081',
+		LocalAddr => '127.0.0.1:' . port(1),
 		Listen => 5,
 		Reuse => 1
 	)
--- a/proxy_cache_lock_age.t
+++ b/proxy_cache_lock_age.t
@@ -41,11 +41,11 @@ http {
                        keys_zone=NAME:1m;
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         location / {
-            proxy_pass    http://127.0.0.1:8081;
+            proxy_pass    http://127.0.0.1:%%PORT_1%%;
             proxy_cache   NAME;
 
             proxy_cache_lock on;
@@ -56,8 +56,8 @@ http {
 
 EOF
 
-$t->run_daemon(\&http_daemon, 8081);
-$t->run()->waitforsocket('127.0.0.1:8081');
+$t->run_daemon(\&http_daemon, port(1));
+$t->run()->waitforsocket('127.0.0.1:' . port(1));
 
 ###############################################################################
 
--- a/proxy_cache_lock_ssi.t
+++ b/proxy_cache_lock_ssi.t
@@ -40,11 +40,11 @@ http {
     limit_req_zone $binary_remote_addr zone=one:1m rate=1r/m;
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         location / {
-            proxy_pass    http://127.0.0.1:8081;
+            proxy_pass    http://127.0.0.1:%%PORT_1%%;
             proxy_cache   NAME;
 
             proxy_cache_lock on;
@@ -61,7 +61,7 @@ http {
     }
 
     server {
-        listen       127.0.0.1:8081;
+        listen       127.0.0.1:%%PORT_1%%;
         server_name  localhost;
         limit_req zone=one burst=5;
     }
--- a/proxy_cache_path.t
+++ b/proxy_cache_path.t
@@ -43,11 +43,11 @@ http {
                        keys_zone=LEVELS:1m  use_temp_path=off;
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         location / {
-            proxy_pass    http://127.0.0.1:8081;
+            proxy_pass    http://127.0.0.1:%%PORT_1%%;
 
             proxy_cache   $arg_c;
 
@@ -58,7 +58,7 @@ http {
     }
 
     server {
-        listen       127.0.0.1:8081;
+        listen       127.0.0.1:%%PORT_1%%;
         server_name  localhost;
 
         location / {
--- a/proxy_cache_range.t
+++ b/proxy_cache_range.t
@@ -38,16 +38,16 @@ http {
                        keys_zone=NAME:1m;
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         location / {
-            proxy_pass    http://127.0.0.1:8081;
+            proxy_pass    http://127.0.0.1:%%PORT_1%%;
             proxy_cache   NAME;
             proxy_cache_valid 200 1m;
         }
         location /min_uses {
-            proxy_pass    http://127.0.0.1:8081/;
+            proxy_pass    http://127.0.0.1:%%PORT_1%%/;
             proxy_cache   NAME;
             proxy_cache_valid 200 1m;
             proxy_cache_min_uses 2;
@@ -55,7 +55,7 @@ http {
     }
 
     server {
-        listen       127.0.0.1:8081;
+        listen       127.0.0.1:%%PORT_1%%;
         server_name  localhost;
 
         location / {
--- a/proxy_cache_revalidate.t
+++ b/proxy_cache_revalidate.t
@@ -40,11 +40,11 @@ http {
     proxy_cache_revalidate on;
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         location / {
-            proxy_pass    http://127.0.0.1:8081;
+            proxy_pass    http://127.0.0.1:%%PORT_1%%;
             proxy_cache   one;
 
             proxy_cache_valid  200 404  2s;
@@ -54,12 +54,12 @@ http {
     }
 
     server {
-        listen       127.0.0.1:8081;
+        listen       127.0.0.1:%%PORT_1%%;
         server_name  localhost;
 
         location / { }
         location /etag/ {
-            proxy_pass http://127.0.0.1:8081/;
+            proxy_pass http://127.0.0.1:%%PORT_1%%/;
             proxy_hide_header Last-Modified;
         }
         location /201 {
--- a/proxy_cache_variables.t
+++ b/proxy_cache_variables.t
@@ -41,11 +41,11 @@ http {
                        keys_zone=NAME2:1m;
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         location / {
-            proxy_pass    http://127.0.0.1:8081;
+            proxy_pass    http://127.0.0.1:%%PORT_1%%;
 
             proxy_cache   $arg_c;
 
@@ -56,7 +56,7 @@ http {
     }
 
     server {
-        listen       127.0.0.1:8081;
+        listen       127.0.0.1:%%PORT_1%%;
         server_name  localhost;
 
         location / {
--- a/proxy_cache_vary.t
+++ b/proxy_cache_vary.t
@@ -38,36 +38,36 @@ http {
     proxy_cache_key    $uri;
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         add_header X-Cache-Status $upstream_cache_status;
 
         location / {
-            proxy_pass    http://127.0.0.1:8081/;
+            proxy_pass    http://127.0.0.1:%%PORT_1%%/;
             proxy_cache   one;
         }
 
         location /replace/ {
-            proxy_pass    http://127.0.0.1:8081/;
+            proxy_pass    http://127.0.0.1:%%PORT_1%%/;
             proxy_cache   one;
         }
 
         location /revalidate/ {
-            proxy_pass    http://127.0.0.1:8081/;
+            proxy_pass    http://127.0.0.1:%%PORT_1%%/;
             proxy_cache   one;
             proxy_cache_revalidate on;
         }
 
         location /ignore/ {
-            proxy_pass    http://127.0.0.1:8081/;
+            proxy_pass    http://127.0.0.1:%%PORT_1%%/;
             proxy_cache   one;
             proxy_ignore_headers Vary;
         }
     }
 
     server {
-        listen       127.0.0.1:8081;
+        listen       127.0.0.1:%%PORT_1%%;
         server_name  localhost;
 
         gzip on;
--- a/proxy_chunked.t
+++ b/proxy_chunked.t
@@ -40,15 +40,15 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         location / {
-            proxy_pass http://127.0.0.1:8081;
+            proxy_pass http://127.0.0.1:%%PORT_1%%;
             proxy_read_timeout 1s;
         }
         location /nobuffering {
-            proxy_pass http://127.0.0.1:8081;
+            proxy_pass http://127.0.0.1:%%PORT_1%%;
             proxy_read_timeout 1s;
             proxy_buffering off;
         }
@@ -64,7 +64,7 @@ EOF
 	'<!--#include virtual="/" set="one" --><!--#echo var="one" -->');
 
 $t->run_daemon(\&http_chunked_daemon);
-$t->run()->waitforsocket('127.0.0.1:8081');
+$t->run()->waitforsocket('127.0.0.1:' . port(1));
 
 ###############################################################################
 
@@ -77,7 +77,7 @@ like(http_get('/inmemory.html'), qr/\x0d
 sub http_chunked_daemon {
 	my $server = IO::Socket::INET->new(
 		Proto => 'tcp',
-		LocalAddr => '127.0.0.1:8081',
+		LocalAddr => '127.0.0.1:' . port(1),
 		Listen => 5,
 		Reuse => 1
 	)
--- a/proxy_cookie.t
+++ b/proxy_cookie.t
@@ -37,11 +37,11 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         location / {
-            proxy_pass http://127.0.0.1:8081;
+            proxy_pass http://127.0.0.1:%%PORT_1%%;
 
             proxy_cookie_domain www.example.org .example.com;
             proxy_cookie_domain .$server_name.com en.$server_name.org;
@@ -55,7 +55,7 @@ http {
     }
 
     server {
-        listen       127.0.0.1:8081;
+        listen       127.0.0.1:%%PORT_1%%;
         server_name  localhost;
 
         location / {
@@ -77,6 +77,8 @@ EOF
 
 ###############################################################################
 
+my $port = port(0);
+
 is(http_get_set_cookie('/?domain=www.Example.org'),
 	'v=path=domain=; Domain=example.com', 'domain rewrite');
 is(http_get_set_cookie('/?domain=.LocalHost.com'),
@@ -103,7 +105,7 @@ is(http_get_set_cookie('/?domain=www.exa
 
 sub http_get_set_cookie {
 	my ($uri) = @_;
-	http_get("http://127.0.0.1:8080$uri") =~ /^Set-Cookie:\s(.+?)\x0d?$/mi;
+	http_get("http://127.0.0.1:$port$uri") =~ /^Set-Cookie:\s(.+?)\x0d?$/mi;
 	return $1;
 }
 
--- a/proxy_force_ranges.t
+++ b/proxy_force_ranges.t
@@ -40,15 +40,15 @@ http {
                        keys_zone=NAME:1m;
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         location / {
-            proxy_pass    http://127.0.0.1:8081;
+            proxy_pass    http://127.0.0.1:%%PORT_1%%;
         }
 
         location /cache/ {
-            proxy_pass    http://127.0.0.1:8081/;
+            proxy_pass    http://127.0.0.1:%%PORT_1%%/;
             proxy_cache   NAME;
             proxy_cache_valid 200 1m;
 
@@ -57,7 +57,7 @@ http {
     }
 
     server {
-        listen       127.0.0.1:8081;
+        listen       127.0.0.1:%%PORT_1%%;
         server_name  localhost;
 
         location / {
--- a/proxy_if.t
+++ b/proxy_if.t
@@ -38,18 +38,18 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         location / {
-            proxy_pass http://127.0.0.1:8081/;
+            proxy_pass http://127.0.0.1:%%PORT_1%%/;
         }
 
         # request was sent to backend without uri changed
         # to '/' due to if
 
         location /proxy-pass-uri {
-            proxy_pass http://127.0.0.1:8081/replacement;
+            proxy_pass http://127.0.0.1:%%PORT_1%%/replacement;
 
             if ($arg_if) {
                 # nothing
@@ -69,7 +69,7 @@ http {
         # nested locations though
 
         location /proxy-pass-uri-lmt {
-            proxy_pass http://127.0.0.1:8081/replacement;
+            proxy_pass http://127.0.0.1:%%PORT_1%%/replacement;
 
             limit_except POST {
                 # nothing
@@ -85,10 +85,10 @@ http {
         }
 
         location /proxy-pass-uri-lmt-different {
-            proxy_pass http://127.0.0.1:8081/replacement;
+            proxy_pass http://127.0.0.1:%%PORT_1%%/replacement;
 
             limit_except POST {
-                proxy_pass http://127.0.0.1:8081;
+                proxy_pass http://127.0.0.1:%%PORT_1%%;
             }
         }
 
@@ -101,7 +101,7 @@ http {
 
             if ($true) {
                 # proxy_pass inside if
-                proxy_pass http://127.0.0.1:8081;
+                proxy_pass http://127.0.0.1:%%PORT_1%%;
             }
 
             if ($true) {
@@ -114,14 +114,14 @@ http {
         # exclusive
 
         location /variables {
-            proxy_pass http://127.0.0.1:8081/outer/$host;
+            proxy_pass http://127.0.0.1:%%PORT_1%%/outer/$host;
 
             if ($arg_if) {
-                proxy_pass http://127.0.0.1:8081;
+                proxy_pass http://127.0.0.1:%%PORT_1%%;
             }
 
             location /variables/inner {
-                proxy_pass http://127.0.0.1:8081;
+                proxy_pass http://127.0.0.1:%%PORT_1%%;
             }
         }
 
@@ -130,21 +130,21 @@ http {
         # be correctly inherited into if's
 
         location /ssl {
-            proxy_pass https://127.0.0.1:8082/outer;
+            proxy_pass https://127.0.0.1:%%PORT_2%%/outer;
 
             if ($arg_if) {
                 # inherited from outer
             }
 
             location /ssl/inner {
-                proxy_pass http://127.0.0.1:8081;
+                proxy_pass http://127.0.0.1:%%PORT_1%%;
             }
         }
     }
 
     server {
-        listen       127.0.0.1:8081;
-        listen       127.0.0.1:8082 ssl;
+        listen       127.0.0.1:%%PORT_1%%;
+        listen       127.0.0.1:%%PORT_2%% ssl;
         server_name  localhost;
 
         ssl_certificate localhost.crt;
--- a/proxy_keepalive.t
+++ b/proxy_keepalive.t
@@ -38,12 +38,12 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     upstream backend {
-        server 127.0.0.1:8081;
+        server 127.0.0.1:%%PORT_1%%;
         keepalive 1;
     }
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         proxy_http_version 1.1;
@@ -74,7 +74,7 @@ EOF
 $t->run_daemon(\&http_daemon);
 $t->run();
 
-$t->waitforsocket('127.0.0.1:8081')
+$t->waitforsocket('127.0.0.1:' . port(1))
 	or die "Can't start test backend";
 
 ###############################################################################
@@ -215,7 +215,7 @@ like(`grep -F '[error]' ${\($t->testdir(
 sub http_daemon {
 	my $server = IO::Socket::INET->new(
 		Proto => 'tcp',
-		LocalHost => '127.0.0.1:8081',
+		LocalHost => '127.0.0.1:' . port(1),
 		Listen => 5,
 		Reuse => 1
 	)
--- a/proxy_limit_rate.t
+++ b/proxy_limit_rate.t
@@ -37,11 +37,11 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         location / {
-            proxy_pass http://127.0.0.1:8080/data;
+            proxy_pass http://127.0.0.1:%%PORT_0%%/data;
             proxy_limit_rate 12000;
             add_header X-Msec $msec;
         }
--- a/proxy_merge_headers.t
+++ b/proxy_merge_headers.t
@@ -41,33 +41,33 @@ http {
     proxy_hide_header X-Hidden;
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         proxy_cache  NAME;
 
         location / {
-            proxy_pass    http://127.0.0.1:8081;
+            proxy_pass    http://127.0.0.1:%%PORT_1%%;
 
             location /nested/ {
-                proxy_pass   http://127.0.0.1:8081;
+                proxy_pass   http://127.0.0.1:%%PORT_1%%;
                 proxy_pass_header X-Pad;
             }
         }
 
         location /no/ {
-            proxy_pass    http://127.0.0.1:8081;
+            proxy_pass    http://127.0.0.1:%%PORT_1%%;
             proxy_cache   off;
         }
 
         location /setbody/ {
-            proxy_pass    http://127.0.0.1:8081;
+            proxy_pass    http://127.0.0.1:%%PORT_1%%;
             proxy_set_body "body";
         }
     }
 
     server {
-        listen       127.0.0.1:8081;
+        listen       127.0.0.1:%%PORT_1%%;
         server_name  localhost;
 
         location / {
--- a/proxy_next_upstream.t
+++ b/proxy_next_upstream.t
@@ -36,17 +36,17 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     upstream u {
-        server 127.0.0.1:8081;
-        server 127.0.0.1:8082;
+        server 127.0.0.1:%%PORT_1%%;
+        server 127.0.0.1:%%PORT_2%%;
     }
 
     upstream u2 {
-        server 127.0.0.1:8081;
-        server 127.0.0.1:8082;
+        server 127.0.0.1:%%PORT_1%%;
+        server 127.0.0.1:%%PORT_2%%;
     }
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         location / {
@@ -67,7 +67,7 @@ http {
     }
 
     server {
-        listen       127.0.0.1:8081;
+        listen       127.0.0.1:%%PORT_1%%;
         server_name  localhost;
 
         location / {
@@ -86,7 +86,7 @@ http {
     }
 
     server {
-        listen       127.0.0.1:8082;
+        listen       127.0.0.1:%%PORT_2%%;
         server_name  localhost;
 
         location / {
@@ -105,6 +105,8 @@ EOF
 
 ###############################################################################
 
+my ($p1, $p2) = (port(1), port(2));
+
 # check if both request fallback to a backend
 # which returns valid response
 
@@ -128,7 +130,7 @@ unlike(http_get('/ok') . http_get('/ok')
 # make sure all backends are tried once
 
 like(http_get('/all/rr'),
-	qr/^127.0.0.1:808(1, 127.0.0.1:8082|2, 127.0.0.1:8081)$/mi,
+	qr/^127.0.0.1:($p1, 127.0.0.1:$p2|$p2, 127.0.0.1:$p1)$/mi,
 	'all tried once');
 
 ###############################################################################
--- a/proxy_next_upstream_tries.t
+++ b/proxy_next_upstream_tries.t
@@ -38,19 +38,19 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     upstream u {
-        server 127.0.0.1:8081;
-        server 127.0.0.1:8081;
-        server 127.0.0.1:8081;
+        server 127.0.0.1:%%PORT_1%%;
+        server 127.0.0.1:%%PORT_1%%;
+        server 127.0.0.1:%%PORT_1%%;
     }
 
     upstream u2 {
-        server 127.0.0.1:8081;
-        server 127.0.0.1:8081 backup;
-        server 127.0.0.1:8081 backup;
+        server 127.0.0.1:%%PORT_1%%;
+        server 127.0.0.1:%%PORT_1%% backup;
+        server 127.0.0.1:%%PORT_1%% backup;
     }
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         proxy_next_upstream http_404;
@@ -68,9 +68,9 @@ http {
         }
 
         location /tries/resolver {
-            resolver 127.0.0.1:8083;
+            resolver 127.0.0.1:%%PORT_2_UDP%%;
 
-            proxy_pass http://$host:8081;
+            proxy_pass http://$host:%%PORT_1%%;
             proxy_next_upstream_tries 2;
         }
 
@@ -90,9 +90,9 @@ http {
         }
 
         location /timeout/resolver {
-            resolver 127.0.0.1:8083;
+            resolver 127.0.0.1:%%PORT_2_UDP%%;
 
-            proxy_pass http://$host:8081/w2;
+            proxy_pass http://$host:%%PORT_1%%/w2;
             proxy_next_upstream_timeout 3800ms;
         }
 
@@ -109,12 +109,12 @@ http {
 
 EOF
 
-$t->run_daemon(\&http_daemon, 8081);
-$t->run_daemon(\&dns_daemon, 8083, $t);
+$t->run_daemon(\&http_daemon, port(1));
+$t->run_daemon(\&dns_daemon, port(2), $t);
 $t->run();
 
-$t->waitforsocket('127.0.0.1:8081');
-$t->waitforfile($t->testdir . '/8083');
+$t->waitforsocket('127.0.0.1:' . port(1));
+$t->waitforfile($t->testdir . '/' . port(2));
 
 ###############################################################################
 
--- a/proxy_noclose.t
+++ b/proxy_noclose.t
@@ -47,16 +47,16 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         location / {
-            proxy_pass http://127.0.0.1:8081;
+            proxy_pass http://127.0.0.1:%%PORT_1%%;
             proxy_read_timeout 2s;
         }
 
         location /uselen {
-            proxy_pass http://127.0.0.1:8081;
+            proxy_pass http://127.0.0.1:%%PORT_1%%;
 
             # test will wait only 2s for reply, we it will fail if
             # Content-Length not used as a hint
@@ -69,7 +69,7 @@ http {
 EOF
 
 $t->run_daemon(\&http_noclose_daemon);
-$t->run()->waitforsocket('127.0.0.1:8081');
+$t->run()->waitforsocket('127.0.0.1:' . port(1));
 
 ###############################################################################
 
@@ -90,7 +90,7 @@ like(http_get('/nolen'), qr/SEE-THIS/, '
 sub http_noclose_daemon {
 	my $server = IO::Socket::INET->new(
 		Proto => 'tcp',
-		LocalAddr => '127.0.0.1:8081',
+		LocalAddr => '127.0.0.1:' . port(1),
 		Listen => 5,
 		Reuse => 1
 	)
--- a/proxy_non_idempotent.t
+++ b/proxy_non_idempotent.t
@@ -37,18 +37,18 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     upstream u {
-        server 127.0.0.1:8081 max_fails=0;
-        server 127.0.0.1:8081 max_fails=0;
+        server 127.0.0.1:%%PORT_1%% max_fails=0;
+        server 127.0.0.1:%%PORT_1%% max_fails=0;
     }
 
     upstream uk {
-        server 127.0.0.1:8081 max_fails=0;
-        server 127.0.0.1:8081 max_fails=0;
+        server 127.0.0.1:%%PORT_1%% max_fails=0;
+        server 127.0.0.1:%%PORT_1%% max_fails=0;
         keepalive 10;
     }
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         add_header X-IP $upstream_addr always;
@@ -72,7 +72,7 @@ http {
     }
 
     server {
-        listen       127.0.0.1:8081;
+        listen       127.0.0.1:%%PORT_1%%;
         server_name  localhost;
 
         location / {
--- a/proxy_pass_request.t
+++ b/proxy_pass_request.t
@@ -37,23 +37,23 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         proxy_pass_request_headers off;
 
         location / {
-            proxy_pass http://127.0.0.1:8081;
+            proxy_pass http://127.0.0.1:%%PORT_1%%;
         }
 
         location /body {
-            proxy_pass http://127.0.0.1:8081;
+            proxy_pass http://127.0.0.1:%%PORT_1%%;
             proxy_pass_request_headers on;
             proxy_pass_request_body off;
         }
 
         location /both {
-            proxy_pass http://127.0.0.1:8081;
+            proxy_pass http://127.0.0.1:%%PORT_1%%;
             proxy_pass_request_headers off;
             proxy_pass_request_body off;
         }
@@ -63,7 +63,7 @@ http {
 EOF
 
 $t->run_daemon(\&http_daemon);
-$t->run()->waitforsocket('127.0.0.1:8081');
+$t->run()->waitforsocket('127.0.0.1:' . port(1));
 
 ###############################################################################
 
@@ -90,7 +90,7 @@ EOF
 sub http_daemon {
 	my $server = IO::Socket::INET->new(
 		Proto => 'tcp',
-		LocalHost => '127.0.0.1:8081',
+		LocalHost => '127.0.0.1:' . port(1),
 		Listen => 5,
 		Reuse => 1
 	)
--- a/proxy_protocol.t
+++ b/proxy_protocol.t
@@ -41,7 +41,7 @@ http {
     log_format pp '$remote_addr $request';
 
     server {
-        listen       127.0.0.1:8080 proxy_protocol;
+        listen       127.0.0.1:%%PORT_0%% proxy_protocol;
         server_name  localhost;
 
         set_real_ip_from  127.0.0.1/32;
--- a/proxy_protocol_ipv6.t
+++ b/proxy_protocol_ipv6.t
@@ -37,7 +37,7 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen       [::1]:8080 proxy_protocol;
+        listen       [::1]:%%PORT_0%% proxy_protocol;
         server_name  localhost;
 
         add_header X-IP $remote_addr;
@@ -54,8 +54,8 @@ http {
 
 stream {
     server {
-        listen      127.0.0.1:8080;
-        proxy_pass  [::1]:8080;
+        listen      127.0.0.1:%%PORT_0%%;
+        proxy_pass  [::1]:%%PORT_0%%;
 
         proxy_protocol on;
     }
--- a/proxy_protocol_port.t
+++ b/proxy_protocol_port.t
@@ -40,7 +40,7 @@ http {
     log_format port $proxy_protocol_port;
 
     server {
-        listen       127.0.0.1:8080 proxy_protocol;
+        listen       127.0.0.1:%%PORT_0%% proxy_protocol;
         server_name  localhost;
 
         add_header X-PP-Port $proxy_protocol_port;
--- a/proxy_redirect.t
+++ b/proxy_redirect.t
@@ -37,53 +37,54 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         location / {
             set $some_var var_here;
 
-            proxy_pass http://127.0.0.1:8081;
+            proxy_pass http://127.0.0.1:%%PORT_1%%;
 
-            proxy_redirect http://127.0.0.1:8081/var_in_second/ /$some_var/;
-            proxy_redirect http://127.0.0.1:8081/$some_var/ /replaced/;
+            proxy_redirect http://127.0.0.1:%%PORT_1%%/var_in_second/
+                           /$some_var/;
+            proxy_redirect http://127.0.0.1:%%PORT_1%%/$some_var/ /replaced/;
 
-            proxy_redirect ~^(.+)81/regex_w_([^/]+) $180/$2/test.html;
+            proxy_redirect ~^(.+)/regex_w_([^/]+) $1/$2/test.html;
             proxy_redirect ~*re+gexp? /replaced/test.html;
         }
 
         location /expl_default/ {
-            proxy_pass http://127.0.0.1:8081/replace_this/;
+            proxy_pass http://127.0.0.1:%%PORT_1%%/replace_this/;
             proxy_redirect wrong wrong;
             proxy_redirect default;
         }
 
         location /impl_default/ {
-            proxy_pass http://127.0.0.1:8081/replace_this/;
+            proxy_pass http://127.0.0.1:%%PORT_1%%/replace_this/;
         }
 
         location /off/ {
-            proxy_pass http://127.0.0.1:8081/;
+            proxy_pass http://127.0.0.1:%%PORT_1%%/;
             proxy_redirect off;
 
             location /off/on/ {
-                proxy_pass http://127.0.0.1:8081;
-                proxy_redirect http://127.0.0.1:8081/off/ /;
+                proxy_pass http://127.0.0.1:%%PORT_1%%;
+                proxy_redirect http://127.0.0.1:%%PORT_1%%/off/ /;
 
                 location /off/on/on/ {
-                    proxy_pass http://127.0.0.1:8081;
+                    proxy_pass http://127.0.0.1:%%PORT_1%%;
                 }
             }
         }
     }
 
     server {
-        listen       127.0.0.1:8081;
+        listen       127.0.0.1:%%PORT_1%%;
         server_name  localhost;
 
         location / {
-            add_header Refresh "7; url=http://127.0.0.1:8081$uri";
-            return http://127.0.0.1:8081$uri;
+            add_header Refresh "7; url=http://127.0.0.1:%%PORT_1%%$uri";
+            return http://127.0.0.1:%%PORT_1%%$uri;
         }
     }
 }
@@ -94,44 +95,45 @@ EOF
 
 ###############################################################################
 
+my ($p0, $p1) = (port(0), port(1));
 
-is(http_get_location('http://127.0.0.1:8080/impl_default/test.html'),
-	'http://127.0.0.1:8080/impl_default/test.html', 'implicit default');
-is(http_get_location('http://127.0.0.1:8080/expl_default/test.html'),
-	'http://127.0.0.1:8080/expl_default/test.html', 'explicit default');
+is(http_get_location("http://127.0.0.1:$p0/impl_default/test.html"),
+	"http://127.0.0.1:$p0/impl_default/test.html", 'implicit default');
+is(http_get_location("http://127.0.0.1:$p0/expl_default/test.html"),
+	"http://127.0.0.1:$p0/expl_default/test.html", 'explicit default');
 
-is(http_get_refresh('http://127.0.0.1:8080/impl_default/test.html'),
+is(http_get_refresh("http://127.0.0.1:$p0/impl_default/test.html"),
 	'7; url=/impl_default/test.html', 'implicit default (refresh)');
-is(http_get_refresh('http://127.0.0.1:8080/expl_default/test.html'),
+is(http_get_refresh("http://127.0.0.1:$p0/expl_default/test.html"),
 	'7; url=/expl_default/test.html', 'explicit default (refresh)');
 
-is(http_get_location('http://127.0.0.1:8080/var_in_second/test.html'),
-	'http://127.0.0.1:8080/var_here/test.html', 'variable in second arg');
-is(http_get_refresh('http://127.0.0.1:8080/var_in_second/test.html'),
+is(http_get_location("http://127.0.0.1:$p0/var_in_second/test.html"),
+	"http://127.0.0.1:$p0/var_here/test.html", 'variable in second arg');
+is(http_get_refresh("http://127.0.0.1:$p0/var_in_second/test.html"),
 	'7; url=/var_here/test.html', 'variable in second arg (refresh)');
 
-is(http_get_location('http://127.0.0.1:8080/off/test.html'),
-	'http://127.0.0.1:8081/test.html', 'rewrite off');
-is(http_get_location('http://127.0.0.1:8080/off/on/test.html'),
-	'http://127.0.0.1:8080/on/test.html', 'rewrite off overwrite');
+is(http_get_location("http://127.0.0.1:$p0/off/test.html"),
+	"http://127.0.0.1:$p1/test.html", 'rewrite off');
+is(http_get_location("http://127.0.0.1:$p0/off/on/test.html"),
+	"http://127.0.0.1:$p0/on/test.html", 'rewrite off overwrite');
 
-is(http_get_location('http://127.0.0.1:8080/off/on/on/test.html'),
-	'http://127.0.0.1:8080/on/on/test.html', 'rewrite inheritance');
+is(http_get_location("http://127.0.0.1:$p0/off/on/on/test.html"),
+	"http://127.0.0.1:$p0/on/on/test.html", 'rewrite inheritance');
 
-is(http_get_location('http://127.0.0.1:8080/var_here/test.html'),
-	'http://127.0.0.1:8080/replaced/test.html', 'variable in first arg');
-is(http_get_refresh('http://127.0.0.1:8080/var_here/test.html'),
+is(http_get_location("http://127.0.0.1:$p0/var_here/test.html"),
+	"http://127.0.0.1:$p0/replaced/test.html", 'variable in first arg');
+is(http_get_refresh("http://127.0.0.1:$p0/var_here/test.html"),
 	'7; url=/replaced/test.html', 'variable in first arg (refresh)');
 
-is(http_get_location('http://127.0.0.1:8080/ReeegEX/test.html'),
-	'http://127.0.0.1:8080/replaced/test.html', 'caseless regexp');
-is(http_get_location('http://127.0.0.1:8080/regex_w_captures/test.html'),
-	'http://127.0.0.1:8080/captures/test.html', 'regexp w/captures');
+is(http_get_location("http://127.0.0.1:$p0/ReeegEX/test.html"),
+	"http://127.0.0.1:$p0/replaced/test.html", 'caseless regexp');
+is(http_get_location("http://127.0.0.1:$p0/regex_w_captures/test.html"),
+	"http://127.0.0.1:$p1/captures/test.html", 'regexp w/captures');
 
-is(http_get_refresh('http://127.0.0.1:8080/ReeegEX/test.html'),
+is(http_get_refresh("http://127.0.0.1:$p0/ReeegEX/test.html"),
 	'7; url=/replaced/test.html', 'caseless regexp (refresh)');
-is(http_get_refresh('http://127.0.0.1:8080/regex_w_captures/test.html'),
-	'7; url=http://127.0.0.1:8080/captures/test.html',
+is(http_get_refresh("http://127.0.0.1:$p0/regex_w_captures/test.html"),
+	"7; url=http://127.0.0.1:$p1/captures/test.html",
 	'regexp w/captures (refresh)');
 
 ###############################################################################
--- a/proxy_request_buffering.t
+++ b/proxy_request_buffering.t
@@ -39,7 +39,7 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         client_header_buffer_size 1k;
@@ -48,25 +48,25 @@ http {
         location / {
             client_body_buffer_size 2k;
             add_header X-Body "$request_body";
-            proxy_pass http://127.0.0.1:8081;
+            proxy_pass http://127.0.0.1:%%PORT_1%%;
         }
         location /small {
             client_body_in_file_only on;
-            proxy_pass http://127.0.0.1:8080/;
+            proxy_pass http://127.0.0.1:%%PORT_0%%/;
         }
         location /single {
             client_body_in_single_buffer on;
             add_header X-Body "$request_body";
-            proxy_pass http://127.0.0.1:8081;
+            proxy_pass http://127.0.0.1:%%PORT_1%%;
         }
         location /discard {
             return 200 "TEST\n";
         }
         location /preread {
-            proxy_pass http://127.0.0.1:8082/;
+            proxy_pass http://127.0.0.1:%%PORT_2%%/;
         }
         location /error_page {
-            proxy_pass http://127.0.0.1:8081/404;
+            proxy_pass http://127.0.0.1:%%PORT_1%%/404;
             error_page 404 /404;
             proxy_intercept_errors on;
         }
@@ -76,11 +76,11 @@ http {
     }
 
     server {
-        listen       127.0.0.1:8081;
+        listen       127.0.0.1:%%PORT_1%%;
         server_name  localhost;
 
         location / {
-            proxy_pass http://127.0.0.1:8080/discard;
+            proxy_pass http://127.0.0.1:%%PORT_0%%/discard;
         }
         location /404 { }
     }
@@ -127,7 +127,7 @@ like(http_get_body('/small', '0123456789
 
 # interactive tests
 
-my $s = get_body('/preread', 8082, 10);
+my $s = get_body('/preread', port(2), 10);
 ok($s, 'no preread');
 
 SKIP: {
@@ -140,7 +140,7 @@ like($s->{http_end}(), qr/200 OK/, 'no p
 
 }
 
-$s = get_body('/preread', 8082, 10, '01234');
+$s = get_body('/preread', port(2), 10, '01234');
 ok($s, 'preread');
 
 SKIP: {
--- a/proxy_request_buffering_chunked.t
+++ b/proxy_request_buffering_chunked.t
@@ -39,7 +39,7 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         client_header_buffer_size 1k;
@@ -49,25 +49,25 @@ http {
         location / {
             client_body_buffer_size 2k;
             add_header X-Body "$request_body";
-            proxy_pass http://127.0.0.1:8081;
+            proxy_pass http://127.0.0.1:%%PORT_1%%;
         }
         location /small {
             client_body_in_file_only on;
-            proxy_pass http://127.0.0.1:8080/;
+            proxy_pass http://127.0.0.1:%%PORT_0%%/;
         }
         location /single {
             client_body_in_single_buffer on;
             add_header X-Body "$request_body";
-            proxy_pass http://127.0.0.1:8081;
+            proxy_pass http://127.0.0.1:%%PORT_1%%;
         }
         location /discard {
             return 200 "TEST\n";
         }
         location /preread {
-            proxy_pass http://127.0.0.1:8082/;
+            proxy_pass http://127.0.0.1:%%PORT_2%%/;
         }
         location /error_page {
-            proxy_pass http://127.0.0.1:8081/404;
+            proxy_pass http://127.0.0.1:%%PORT_1%%/404;
             error_page 404 /404;
             proxy_intercept_errors on;
         }
@@ -77,11 +77,11 @@ http {
     }
 
     server {
-        listen       127.0.0.1:8081;
+        listen       127.0.0.1:%%PORT_1%%;
         server_name  localhost;
 
         location / {
-            proxy_pass http://127.0.0.1:8080/discard;
+            proxy_pass http://127.0.0.1:%%PORT_0%%/discard;
         }
         location /404 { }
     }
@@ -128,7 +128,7 @@ like(http_get_body('/small', '0123456789
 
 # interactive tests
 
-my $s = get_body('/preread', 8082);
+my $s = get_body('/preread', port(2));
 ok($s, 'no preread');
 
 SKIP: {
@@ -144,7 +144,7 @@ like($s->{http_end}(), qr/200 OK/, 'no p
 
 }
 
-$s = get_body('/preread', 8082, '01234');
+$s = get_body('/preread', port(2), '01234');
 ok($s, 'preread');
 
 SKIP: {
@@ -158,7 +158,7 @@ like($s->{http_end}(), qr/200 OK/, 'prer
 
 }
 
-$s = get_body('/preread', 8082, '01234', many => 1);
+$s = get_body('/preread', port(2), '01234', many => 1);
 ok($s, 'chunks');
 
 SKIP: {
--- a/proxy_request_buffering_keepalive.t
+++ b/proxy_request_buffering_keepalive.t
@@ -37,12 +37,12 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     upstream backend {
-        server 127.0.0.1:8081;
+        server 127.0.0.1:%%PORT_1%%;
         keepalive 1;
     }
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         proxy_http_version 1.1;
@@ -56,7 +56,7 @@ http {
     }
 
     server {
-        listen       127.0.0.1:8081;
+        listen       127.0.0.1:%%PORT_1%%;
         server_name  localhost;
 
         location / { }
--- a/proxy_request_buffering_ssl.t
+++ b/proxy_request_buffering_ssl.t
@@ -40,7 +40,7 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         client_header_buffer_size 1k;
@@ -49,21 +49,21 @@ http {
         location / {
             client_body_buffer_size 2k;
             add_header X-Body "$request_body";
-            proxy_pass https://127.0.0.1:8081;
+            proxy_pass https://127.0.0.1:%%PORT_1%%;
         }
         location /single {
             client_body_in_single_buffer on;
             add_header X-Body "$request_body";
-            proxy_pass https://127.0.0.1:8081;
+            proxy_pass https://127.0.0.1:%%PORT_1%%;
         }
         location /discard {
             return 200 "TEST\n";
         }
         location /preread {
-            proxy_pass https://127.0.0.1:8081;
+            proxy_pass https://127.0.0.1:%%PORT_1%%;
         }
         location /error_page {
-            proxy_pass https://127.0.0.1:8081/404;
+            proxy_pass https://127.0.0.1:%%PORT_1%%/404;
             error_page 404 /404;
             proxy_intercept_errors on;
         }
@@ -73,7 +73,7 @@ http {
     }
 
     server {
-        listen       127.0.0.1:8081 ssl;
+        listen       127.0.0.1:%%PORT_1%% ssl;
         server_name  localhost;
 
         ssl_certificate_key localhost.key;
@@ -82,12 +82,12 @@ http {
         location /preread {
             client_body_buffer_size 2k;
             add_header X-Body "$request_body";
-            proxy_pass http://127.0.0.1:8082/;
+            proxy_pass http://127.0.0.1:%%PORT_2%%/;
             proxy_request_buffering off;
         }
 
         location / {
-            proxy_pass http://127.0.0.1:8080/discard;
+            proxy_pass http://127.0.0.1:%%PORT_0%%/discard;
         }
         location /404 { }
     }
@@ -147,7 +147,7 @@ like(http_get_body('/discard', '01234567
 
 # interactive tests
 
-my $s = get_body('/preread', 8082, 10);
+my $s = get_body('/preread', port(2), 10);
 ok($s, 'no preread');
 
 SKIP: {
@@ -160,7 +160,7 @@ like($s->{http_end}(), qr/200 OK/, 'no p
 
 }
 
-$s = get_body('/preread', 8082, 15, '01234');
+$s = get_body('/preread', port(2), 15, '01234');
 ok($s, 'preread');
 
 SKIP: {
--- a/proxy_set_body.t
+++ b/proxy_set_body.t
@@ -35,21 +35,21 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         location / {
-            proxy_pass http://127.0.0.1:8080/body;
+            proxy_pass http://127.0.0.1:%%PORT_0%%/body;
             proxy_set_body "body";
         }
 
         location /p1 {
-            proxy_pass http://127.0.0.1:8080/x1;
+            proxy_pass http://127.0.0.1:%%PORT_0%%/x1;
             proxy_set_body "body";
         }
 
         location /p2 {
-            proxy_pass http://127.0.0.1:8080/body;
+            proxy_pass http://127.0.0.1:%%PORT_0%%/body;
             proxy_set_body "body two";
         }
 
@@ -60,7 +60,7 @@ http {
 
         location /body {
             add_header X-Body $request_body;
-            proxy_pass http://127.0.0.1:8080/empty;
+            proxy_pass http://127.0.0.1:%%PORT_0%%/empty;
         }
 
         location /empty {
--- a/proxy_ssi_body.t
+++ b/proxy_ssi_body.t
@@ -39,14 +39,14 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         location / {
         }
 
         location /proxy {
-            proxy_pass http://127.0.0.1:8080/;
+            proxy_pass http://127.0.0.1:%%PORT_0%%/;
             client_body_in_file_only on;
             ssi on;
         }
--- a/proxy_ssl.t
+++ b/proxy_ssl.t
@@ -35,7 +35,7 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen 127.0.0.1:8081 ssl;
+        listen 127.0.0.1:%%PORT_1%% ssl;
 
         ssl_certificate_key localhost.key;
         ssl_certificate localhost.crt;
@@ -47,21 +47,21 @@ http {
     }
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         location /ssl_reuse {
-            proxy_pass https://127.0.0.1:8081/;
+            proxy_pass https://127.0.0.1:%%PORT_1%%/;
             proxy_ssl_session_reuse on;
         }
 
         location /ssl {
-            proxy_pass https://127.0.0.1:8081/;
+            proxy_pass https://127.0.0.1:%%PORT_1%%/;
             proxy_ssl_session_reuse off;
         }
 
         location /timeout {
-            proxy_pass https://127.0.0.1:8081/;
+            proxy_pass https://127.0.0.1:%%PORT_1%%/;
             proxy_connect_timeout 2s;
         }
     }
--- a/proxy_ssl_certificate.t
+++ b/proxy_ssl_certificate.t
@@ -39,25 +39,25 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         proxy_ssl_session_reuse off;
 
         location /verify {
-            proxy_pass https://127.0.0.1:8081/;
+            proxy_pass https://127.0.0.1:%%PORT_1%%/;
             proxy_ssl_certificate 1.example.com.crt;
             proxy_ssl_certificate_key 1.example.com.key;
         }
 
         location /fail {
-            proxy_pass https://127.0.0.1:8081/;
+            proxy_pass https://127.0.0.1:%%PORT_1%%/;
             proxy_ssl_certificate 2.example.com.crt;
             proxy_ssl_certificate_key 2.example.com.key;
         }
 
         location /encrypted {
-            proxy_pass https://127.0.0.1:8082/;
+            proxy_pass https://127.0.0.1:%%PORT_2%%/;
             proxy_ssl_certificate 3.example.com.crt;
             proxy_ssl_certificate_key 3.example.com.key;
             proxy_ssl_password_file password;
@@ -65,7 +65,7 @@ http {
     }
 
     server {
-        listen       127.0.0.1:8081 ssl;
+        listen       127.0.0.1:%%PORT_1%% ssl;
         server_name  localhost;
 
         ssl_certificate 2.example.com.crt;
@@ -81,7 +81,7 @@ http {
     }
 
     server {
-        listen       127.0.0.1:8082 ssl;
+        listen       127.0.0.1:%%PORT_2%% ssl;
         server_name  localhost;
 
         ssl_certificate 1.example.com.crt;
--- a/proxy_ssl_keepalive.t
+++ b/proxy_ssl_keepalive.t
@@ -40,12 +40,12 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     upstream u {
-        server 127.0.0.1:8081;
+        server 127.0.0.1:%%PORT_1%%;
         keepalive 1;
     }
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         proxy_http_version 1.1;
@@ -57,7 +57,7 @@ http {
     }
 
     server {
-        listen       127.0.0.1:8081 ssl;
+        listen       127.0.0.1:%%PORT_1%% ssl;
         server_name  localhost;
 
         ssl_certificate_key localhost.key;
--- a/proxy_ssl_name.t
+++ b/proxy_ssl_name.t
@@ -38,15 +38,15 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     upstream backend {
-        server 127.0.0.1:8081;
+        server 127.0.0.1:%%PORT_1%%;
     }
 
     upstream backend2 {
-        server 127.0.0.1:8081;
+        server 127.0.0.1:%%PORT_1%%;
     }
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         # session reuse is off, as sessions are cached
@@ -56,13 +56,13 @@ http {
         proxy_ssl_session_reuse off;
 
         location /1 {
-            proxy_pass https://127.0.0.1:8081/;
+            proxy_pass https://127.0.0.1:%%PORT_1%%/;
             proxy_ssl_name 1.example.com;
             proxy_ssl_server_name on;
         }
 
         location /2 {
-            proxy_pass https://127.0.0.1:8081/;
+            proxy_pass https://127.0.0.1:%%PORT_1%%/;
             proxy_ssl_name 2.example.com;
             proxy_ssl_server_name on;
 
@@ -90,19 +90,19 @@ http {
         }
 
         location /ip {
-            proxy_pass https://127.0.0.1:8081/;
+            proxy_pass https://127.0.0.1:%%PORT_1%%/;
             proxy_ssl_server_name on;
         }
 
         #location /ip6 {
-        #    proxy_pass https://[::1]:8081/;
+        #    proxy_pass https://[::1]:%%PORT_1%%/;
         #    proxy_ssl_server_name on;
         #}
     }
 
     server {
-        listen 127.0.0.1:8081 ssl;
-        #listen [::1]:8081 ssl;
+        listen 127.0.0.1:%%PORT_1%% ssl;
+        #listen [::1]:%%PORT_1%% ssl;
         server_name 1.example.com;
 
         ssl_certificate localhost.crt;
--- a/proxy_ssl_verify.t
+++ b/proxy_ssl_verify.t
@@ -37,46 +37,46 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         location /verify {
-            proxy_pass https://127.0.0.1:8081/;
+            proxy_pass https://127.0.0.1:%%PORT_1%%/;
             proxy_ssl_name example.com;
             proxy_ssl_verify on;
             proxy_ssl_trusted_certificate 1.example.com.crt;
         }
 
         location /wildcard {
-            proxy_pass https://127.0.0.1:8081/;
+            proxy_pass https://127.0.0.1:%%PORT_1%%/;
             proxy_ssl_name foo.example.com;
             proxy_ssl_verify on;
             proxy_ssl_trusted_certificate 1.example.com.crt;
         }
 
         location /fail {
-            proxy_pass https://127.0.0.1:8081/;
+            proxy_pass https://127.0.0.1:%%PORT_1%%/;
             proxy_ssl_name no.match.example.com;
             proxy_ssl_verify on;
             proxy_ssl_trusted_certificate 1.example.com.crt;
         }
 
         location /cn {
-            proxy_pass https://127.0.0.1:8082/;
+            proxy_pass https://127.0.0.1:%%PORT_2%%/;
             proxy_ssl_name 2.example.com;
             proxy_ssl_verify on;
             proxy_ssl_trusted_certificate 2.example.com.crt;
         }
 
         location /cn/fail {
-            proxy_pass https://127.0.0.1:8082/;
+            proxy_pass https://127.0.0.1:%%PORT_2%%/;
             proxy_ssl_name bad.example.com;
             proxy_ssl_verify on;
             proxy_ssl_trusted_certificate 2.example.com.crt;
         }
 
         location /untrusted {
-            proxy_pass https://127.0.0.1:8082/;
+            proxy_pass https://127.0.0.1:%%PORT_2%%/;
             proxy_ssl_verify on;
             proxy_ssl_trusted_certificate 1.example.com.crt;
             proxy_ssl_session_reuse off;
@@ -84,7 +84,7 @@ http {
     }
 
     server {
-        listen 127.0.0.1:8081 ssl;
+        listen 127.0.0.1:%%PORT_1%% ssl;
         server_name 1.example.com;
 
         ssl_certificate 1.example.com.crt;
@@ -94,7 +94,7 @@ http {
     }
 
     server {
-        listen 127.0.0.1:8082 ssl;
+        listen 127.0.0.1:%%PORT_2%% ssl;
         server_name 2.example.com;
 
         ssl_certificate 2.example.com.crt;
--- a/proxy_store.t
+++ b/proxy_store.t
@@ -36,15 +36,15 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         location /store- {
-            proxy_pass http://127.0.0.1:8080/;
+            proxy_pass http://127.0.0.1:%%PORT_0%%/;
             proxy_store on;
         }
         location /store-string- {
-            proxy_pass http://127.0.0.1:8080/;
+            proxy_pass http://127.0.0.1:%%PORT_0%%/;
             proxy_store %%TESTDIR%%$uri;
         }
         location /ssi.html {
--- a/proxy_unfinished.t
+++ b/proxy_unfinished.t
@@ -49,24 +49,24 @@ http {
                        keys_zone=one:1m;
 
     server {
-        listen       127.0.0.1:8080 sndbuf=32k;
+        listen       127.0.0.1:%%PORT_0%% sndbuf=32k;
         server_name  localhost;
 
         location / {
             sub_filter foo bar;
             sub_filter_types *;
-            proxy_pass http://127.0.0.1:8081;
+            proxy_pass http://127.0.0.1:%%PORT_1%%;
         }
 
         location /un/ {
             sub_filter foo bar;
             sub_filter_types *;
-            proxy_pass http://127.0.0.1:8081/;
+            proxy_pass http://127.0.0.1:%%PORT_1%%/;
             proxy_buffering off;
         }
 
         location /cache/ {
-            proxy_pass http://127.0.0.1:8081/;
+            proxy_pass http://127.0.0.1:%%PORT_1%%/;
             proxy_cache one;
             add_header X-Cache-Status $upstream_cache_status;
         }
@@ -74,7 +74,7 @@ http {
         location /proxy/ {
             sub_filter foo bar;
             sub_filter_types *;
-            proxy_pass http://127.0.0.1:8080/local/;
+            proxy_pass http://127.0.0.1:%%PORT_0%%/local/;
             proxy_buffer_size 1k;
             proxy_buffers 4 1k;
         }
@@ -90,7 +90,7 @@ EOF
 $t->write_file('big.html', 'X' x (1024 * 1024) . 'finished');
 
 $t->run_daemon(\&http_daemon);
-$t->run()->waitforsocket('127.0.0.1:8081');
+$t->run()->waitforsocket('127.0.0.1:' . port(1));
 
 ###############################################################################
 
@@ -163,7 +163,7 @@ sub http_get_11 {
 sub http_daemon {
 	my $server = IO::Socket::INET->new(
 		Proto => 'tcp',
-		LocalAddr => '127.0.0.1:8081',
+		LocalAddr => '127.0.0.1:' . port(1),
 		Listen => 5,
 		Reuse => 1
 	)
--- a/proxy_unix.t
+++ b/proxy_unix.t
@@ -45,7 +45,7 @@ http {
     }
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         location / {
--- a/proxy_upgrade.t
+++ b/proxy_upgrade.t
@@ -44,11 +44,11 @@ http {
     access_log %%TESTDIR%%/cc.log test;
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         location / {
-            proxy_pass    http://127.0.0.1:8081;
+            proxy_pass    http://127.0.0.1:%%PORT_1%%;
             proxy_http_version 1.1;
             proxy_set_header Upgrade $http_upgrade;
             proxy_set_header Connection "Upgrade";
@@ -65,7 +65,7 @@ my $d = $t->testdir();
 $t->run_daemon(\&upgrade_fake_daemon);
 $t->run();
 
-$t->waitforsocket('127.0.0.1:8081')
+$t->waitforsocket('127.0.0.1:' . port(1))
 	or die "Can't start test backend";
 
 ###############################################################################
@@ -147,7 +147,7 @@ sub upgrade_connect {
 
 	my $s = IO::Socket::INET->new(
 		Proto => 'tcp',
-		PeerAddr => '127.0.0.1:8080',
+		PeerAddr => '127.0.0.1:' . port(0),
 	)
 		or die "Can't connect to nginx: $!\n";
 
@@ -250,7 +250,7 @@ sub upgrade_read {
 sub upgrade_fake_daemon {
 	my $server = IO::Socket::INET->new(
 		Proto => 'tcp',
-		LocalAddr => '127.0.0.1:8081',
+		LocalAddr => '127.0.0.1:' . port(1),
 		Listen => 5,
 		Reuse => 1
 	)
--- a/proxy_upstream_cookie.t
+++ b/proxy_upstream_cookie.t
@@ -36,17 +36,17 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         location / {
             add_header X-Upstream-Cookie $upstream_cookie_tc;
-            proxy_pass http://127.0.0.1:8081;
+            proxy_pass http://127.0.0.1:%%PORT_1%%;
         }
     }
 
     server {
-        listen       127.0.0.1:8081;
+        listen       127.0.0.1:%%PORT_1%%;
         server_name  localhost;
 
         location / {
--- a/proxy_variables.t
+++ b/proxy_variables.t
@@ -36,15 +36,15 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     upstream u {
-        server 127.0.0.1:8081;
-        server 127.0.0.1:8081;
+        server 127.0.0.1:%%PORT_1%%;
+        server 127.0.0.1:%%PORT_1%%;
     }
 
     log_format time '$upstream_connect_time:$upstream_header_time:'
                     '$upstream_response_time';
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         add_header X-Connect $upstream_connect_time;
@@ -52,7 +52,7 @@ http {
         add_header X-Response $upstream_response_time;
 
         location / {
-            proxy_pass http://127.0.0.1:8081;
+            proxy_pass http://127.0.0.1:%%PORT_1%%;
             access_log %%TESTDIR%%/time.log time;
         }
 
@@ -61,7 +61,7 @@ http {
         }
 
         location /vars {
-            proxy_pass http://127.0.0.1:8080/stub;
+            proxy_pass http://127.0.0.1:%%PORT_0%%/stub;
 
             add_header X-Proxy-Host $proxy_host;
             add_header X-Proxy-Port $proxy_port;
@@ -75,18 +75,19 @@ http {
 EOF
 
 $t->write_file('stub', '');
-$t->run_daemon(\&http_daemon, 8081);
+$t->run_daemon(\&http_daemon, port(1));
 $t->try_run('no upstream_connect_time')->plan(18);
 
-$t->waitforsocket('127.0.0.1:8081');
+$t->waitforsocket('127.0.0.1:' . port(1));
 
 ###############################################################################
 
 my $re = qr/(\d\.\d{3})/;
+my $p0 = port(0);
 my ($ct, $ht, $rt, $ct2, $ht2, $rt2);
 
-like(http_get('/vars'), qr/X-Proxy-Host:\s127\.0\.0\.1:8080/, 'proxy_host');
-like(http_get('/vars'), qr/X-Proxy-Port:\s8080/, 'proxy_port');
+like(http_get('/vars'), qr/X-Proxy-Host:\s127\.0\.0\.1:$p0/, 'proxy_host');
+like(http_get('/vars'), qr/X-Proxy-Port:\s$p0/, 'proxy_port');
 like(http_xff('/vars', '192.0.2.1'), qr/X-Proxy-Forwarded:.*192\.0\.2\.1/,
 	'proxy_add_x_forwarded_for');
 
--- a/proxy_websocket.t
+++ b/proxy_websocket.t
@@ -47,11 +47,11 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         location / {
-            proxy_pass    http://127.0.0.1:8081;
+            proxy_pass    http://127.0.0.1:%%PORT_1%%;
             proxy_http_version 1.1;
             proxy_set_header Upgrade $http_upgrade;
             proxy_set_header Connection "Upgrade";
@@ -66,7 +66,7 @@ EOF
 $t->run_daemon(\&websocket_fake_daemon);
 $t->run();
 
-$t->waitforsocket('127.0.0.1:8081')
+$t->waitforsocket('127.0.0.1:' . port(1))
 	or die "Can't start test backend";
 
 ###############################################################################
@@ -125,7 +125,7 @@ sub websocket_connect {
 
 	my $s = IO::Socket::INET->new(
 		Proto => 'tcp',
-		PeerAddr => '127.0.0.1:8080'
+		PeerAddr => '127.0.0.1:' . port(0)
 	)
 		or die "Can't connect to nginx: $!\n";
 
@@ -210,7 +210,7 @@ sub websocket_read {
 sub websocket_fake_daemon {
 	my $server = IO::Socket::INET->new(
 		Proto => 'tcp',
-		LocalAddr => '127.0.0.1:8081',
+		LocalAddr => '127.0.0.1:' . port(1),
 		Listen => 5,
 		Reuse => 1
 	)
--- a/proxy_xar.t
+++ b/proxy_xar.t
@@ -36,7 +36,7 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         # catch safe and unhandled unsafe URIs,
@@ -47,7 +47,7 @@ http {
         }
 
         location /proxy {
-            proxy_pass http://127.0.0.1:8080/return-xar;
+            proxy_pass http://127.0.0.1:%%PORT_0%%/return-xar;
         }
         location /return-xar {
             add_header  X-Accel-Redirect     $arg_xar;
--- a/random_index.t
+++ b/random_index.t
@@ -35,7 +35,7 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         location / {
--- a/range.t
+++ b/range.t
@@ -40,7 +40,7 @@ http {
     }
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         location /t2.html {
--- a/range_charset.t
+++ b/range_charset.t
@@ -43,18 +43,18 @@ http {
                        keys_zone=NAME:1m;
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         location / {
-            proxy_pass    http://127.0.0.1:8081;
+            proxy_pass    http://127.0.0.1:%%PORT_1%%;
             proxy_cache   NAME;
             proxy_cache_valid 200 1m;
         }
     }
 
     server {
-        listen       127.0.0.1:8081;
+        listen       127.0.0.1:%%PORT_1%%;
         server_name  localhost;
 
         charset B;
--- a/range_flv.t
+++ b/range_flv.t
@@ -36,7 +36,7 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
         location / {
             flv;
--- a/range_if_range.t
+++ b/range_if_range.t
@@ -36,7 +36,7 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         location /t2.html {
--- a/range_mp4.t
+++ b/range_mp4.t
@@ -37,7 +37,7 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
         location / {
             mp4;
--- a/realip.t
+++ b/realip.t
@@ -40,7 +40,7 @@ http {
     set_real_ip_from  10.0.1.0/24;
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         location / { }
--- a/realip_remote_addr.t
+++ b/realip_remote_addr.t
@@ -40,7 +40,7 @@ http {
     real_ip_header    X-Forwarded-For;
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         location / {
--- a/realip_remote_port.t
+++ b/realip_remote_port.t
@@ -42,7 +42,7 @@ http {
     set_real_ip_from  ::1/128;
 
     server {
-        listen       [::1]:8081;
+        listen       [::1]:%%PORT_1%%;
         listen       unix:%%TESTDIR%%/unix.sock;
 
         location / {
@@ -51,7 +51,7 @@ http {
     }
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         location / {
@@ -64,7 +64,7 @@ http {
         }
 
         location /inet6 {
-            proxy_pass http://[::1]:8081/;
+            proxy_pass http://[::1]:%%PORT_1%%/;
         }
 
         location /unix {
--- a/referer.t
+++ b/referer.t
@@ -36,7 +36,7 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  another;
 
         valid_referers server_names;
@@ -44,7 +44,7 @@ http {
     }
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  _;
 
         location / {
@@ -55,7 +55,7 @@ http {
     }
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost ~bar ~^anchoredre$;
 
         location /blocked {
@@ -117,7 +117,8 @@ EOF
 
 ok(valid('/simple', 'http://www.example.org'), 'simple');
 ok(valid('/simple', 'http://www.example.org/uri'), 'simple uri');
-ok(valid('/simple', 'http://www.example.org:8080/uri'), 'simple port uri');
+ok(valid('/simple', 'http://www.example.org:' . port(0) . '/uri'),
+	'simple port uri');
 ok(!valid('/simple', 'localhost'), 'simple invalid');
 ok(valid('/simple', 'https://www.example.org'), 'https');
 ok(!valid('/simple', 'example.com'), 'no scheme');
@@ -143,7 +144,7 @@ ok(!valid('/long', 'http://' . 'a' x 257
 ok(valid('/uri', 'http://www.example.org/uri'), 'uri');
 ok(valid('/uri', 'http://www.example.org/urii'), 'uri prefix');
 ok(!valid('/uri', 'http://www.example.org/uRi'), 'uri case');
-ok(valid('/uri', 'http://www.example.org:8080/urii'), 'uri port');
+ok(valid('/uri', 'http://www.example.org:' . port(0) . '/urii'), 'uri port');
 ok(!valid('/uri', 'http://www.example.org/ur'), 'uri invalid len');
 ok(!valid('/uri', 'http://www.example.org/urd'), 'uri invalid cmp');
 
--- a/request_id.t
+++ b/request_id.t
@@ -38,7 +38,7 @@ http {
     log_format id $request_id;
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         add_header X-Request-Id $request_id;
--- a/rewrite.t
+++ b/rewrite.t
@@ -35,7 +35,7 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         location / {
--- a/rewrite_set.t
+++ b/rewrite_set.t
@@ -37,7 +37,7 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         ssi on;
--- a/rewrite_unescape.t
+++ b/rewrite_unescape.t
@@ -35,7 +35,7 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         location /t1 {
--- a/scgi.t
+++ b/scgi.t
@@ -38,15 +38,15 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     upstream u {
-        server 127.0.0.1:8081;
+        server 127.0.0.1:%%PORT_1%%;
     }
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         location / {
-            scgi_pass 127.0.0.1:8081;
+            scgi_pass 127.0.0.1:%%PORT_1%%;
             scgi_param SCGI 1;
             scgi_param REQUEST_URI $request_uri;
             scgi_param HTTP_X_BLAH "blah";
@@ -77,7 +77,8 @@ unlike(http_head('/'), qr/SEE-THIS/, 'no
 like(http_get_headers('/headers'), qr/SEE-THIS/,
 	'scgi request with many ignored headers');
 
-like(http_get('/var?b=127.0.0.1:8081'), qr/SEE-THIS/, 'scgi with variables');
+like(http_get('/var?b=127.0.0.1:' . port(1)), qr/SEE-THIS/,
+	'scgi with variables');
 like(http_get('/var?b=u'), qr/SEE-THIS/, 'scgi with variables to upstream');
 
 ###############################################################################
@@ -115,7 +116,7 @@ EOF
 sub scgi_daemon {
 	my $server = IO::Socket::INET->new(
 		Proto => 'tcp',
-		LocalHost => '127.0.0.1:8081',
+		LocalHost => '127.0.0.1:' . port(1),
 		Listen => 5,
 		Reuse => 1
 	)
@@ -129,7 +130,7 @@ sub scgi_daemon {
 		$request->read_env();
 
 		$request->connection()->print(<<EOF);
-Location: http://127.0.0.1:8080/redirect
+Location: http://localhost/redirect
 Content-Type: text/html
 
 SEE-THIS
--- a/scgi_body.t
+++ b/scgi_body.t
@@ -38,11 +38,11 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         location / {
-            scgi_pass 127.0.0.1:8081;
+            scgi_pass 127.0.0.1:%%PORT_1%%;
             scgi_param SCGI 1;
             scgi_param REQUEST_URI $request_uri;
         }
@@ -104,7 +104,7 @@ EOF
 sub scgi_daemon {
 	my $server = IO::Socket::INET->new(
 		Proto => 'tcp',
-		LocalHost => '127.0.0.1:8081',
+		LocalHost => '127.0.0.1:' . port(1),
 		Listen => 5,
 		Reuse => 1
 	)
@@ -119,7 +119,7 @@ sub scgi_daemon {
 			$request->env->{CONTENT_LENGTH});
 
 		$request->connection()->print(<<EOF);
-Location: http://127.0.0.1:8080/redirect
+Location: http://localhost/redirect
 Content-Type: text/html
 X-Body: $body
 
--- a/scgi_cache.t
+++ b/scgi_cache.t
@@ -44,11 +44,11 @@ http {
     add_header       X-Cache-Status  $upstream_cache_status;
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         location / {
-            scgi_pass 127.0.0.1:8081;
+            scgi_pass 127.0.0.1:%%PORT_1%%;
             scgi_param SCGI 1;
             scgi_param REQUEST_URI $uri;
             scgi_cache one;
@@ -83,7 +83,7 @@ like(http_get('/unfinished'), qr/MISS/, 
 sub scgi_daemon {
 	my $server = IO::Socket::INET->new(
 		Proto => 'tcp',
-		LocalHost => '127.0.0.1:8081',
+		LocalHost => '127.0.0.1:' . port(1),
 		Listen => 5,
 		Reuse => 1
 	)
--- a/scgi_gzip.t
+++ b/scgi_gzip.t
@@ -38,12 +38,12 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         location / {
             gzip on;
-            scgi_pass 127.0.0.1:8081;
+            scgi_pass 127.0.0.1:%%PORT_1%%;
             scgi_param SCGI 1;
             scgi_param REQUEST_URI $request_uri;
             scgi_param HTTP_X_BLAH "blah";
@@ -65,7 +65,7 @@ like(http_gzip_request('/'), qr/Content-
 sub scgi_daemon {
 	my $server = IO::Socket::INET->new(
 		Proto => 'tcp',
-		LocalHost => '127.0.0.1:8081',
+		LocalHost => '127.0.0.1:' . port(1),
 		Listen => 5,
 		Reuse => 1
 	)
--- a/scgi_merge_params.t
+++ b/scgi_merge_params.t
@@ -46,22 +46,22 @@ http {
     scgi_param HTTP_X_BLAH "blah";
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         scgi_cache  NAME;
 
         location / {
-            scgi_pass    127.0.0.1:8081;
+            scgi_pass    127.0.0.1:%%PORT_1%%;
         }
 
         location /no/ {
-            scgi_pass    127.0.0.1:8081;
+            scgi_pass    127.0.0.1:%%PORT_1%%;
             scgi_cache   off;
         }
 
         location /custom/ {
-            scgi_pass    127.0.0.1:8081;
+            scgi_pass    127.0.0.1:%%PORT_1%%;
             scgi_param   SCGI 1;
             scgi_param   HTTP_X_BLAH  "custom";
         }
@@ -115,7 +115,7 @@ EOF
 sub scgi_daemon {
 	my $server = IO::Socket::INET->new(
 		Proto => 'tcp',
-		LocalHost => '127.0.0.1:8081',
+		LocalHost => '127.0.0.1:' . port(1),
 		Listen => 5,
 		Reuse => 1
 	)
@@ -133,7 +133,7 @@ sub scgi_daemon {
 		my $blah = $request->env->{HTTP_X_BLAH} || '';
 
 		$request->connection()->print(<<EOF);
-Location: http://127.0.0.1:8080/redirect
+Location: http://localhost/redirect
 Content-Type: text/html
 
 ims=$ims;iums=$iums;blah=$blah;
--- a/secure_link.t
+++ b/secure_link.t
@@ -39,7 +39,7 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         location / {
--- a/server_tokens.t
+++ b/server_tokens.t
@@ -36,7 +36,7 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         location /200 {
--- a/slice.t
+++ b/slice.t
@@ -44,7 +44,7 @@ http {
     fastcgi_cache_key    $uri$is_args$args$slice_range;
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         location / { }
@@ -52,7 +52,7 @@ http {
         location /cache/ {
             slice 2;
 
-            proxy_pass    http://127.0.0.1:8081/;
+            proxy_pass    http://127.0.0.1:%%PORT_1%%/;
 
             proxy_cache   NAME;
 
@@ -66,7 +66,7 @@ http {
         location /fastcgi {
             slice 2;
 
-            fastcgi_pass    127.0.0.1:8082;
+            fastcgi_pass    127.0.0.1:%%PORT_2%%;
 
             fastcgi_cache   NAME2;
 
@@ -81,7 +81,7 @@ http {
     }
 
     server {
-        listen       127.0.0.1:8081;
+        listen       127.0.0.1:%%PORT_1%%;
         server_name  localhost;
 
         location / { }
@@ -228,7 +228,7 @@ SKIP: {
 	skip 'win32', 5 if $^O eq 'MSWin32';
 
 	$t->run_daemon(\&fastcgi_daemon);
-	$t->waitforsocket('127.0.0.1:8082');
+	$t->waitforsocket('127.0.0.1:' . port(2));
 
 	like(http_get('/fastcgi'), qr/200 OK.*MISS.*^012345678$/ms, 'fastcgi');
 	like(http_get('/fastcgi'), qr/200 OK.*HIT.*^012345678$/ms,
@@ -258,7 +258,7 @@ EOF
 ###############################################################################
 
 sub fastcgi_daemon {
-	my $socket = FCGI::OpenSocket('127.0.0.1:8082', 5);
+	my $socket = FCGI::OpenSocket('127.0.0.1:' . port(2), 5);
 	my $request = FCGI::Request(\*STDIN, \*STDOUT, \*STDERR, \%ENV,
 		$socket);
 
--- a/split_clients.t
+++ b/split_clients.t
@@ -43,7 +43,7 @@ http {
     }
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         location / {
--- a/ssi.t
+++ b/ssi.t
@@ -40,7 +40,7 @@ http {
                            keys_zone=NAME:1m;
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         if ($args = "found") {
@@ -52,10 +52,10 @@ http {
         }
         location /proxy/ {
             ssi on;
-            proxy_pass http://127.0.0.1:8080/local/;
+            proxy_pass http://127.0.0.1:%%PORT_0%%/local/;
         }
         location /cache/ {
-            proxy_pass http://127.0.0.1:8080/local/;
+            proxy_pass http://127.0.0.1:%%PORT_0%%/local/;
             proxy_cache NAME;
             proxy_cache_valid 200 1h;
         }
--- a/ssi_if.t
+++ b/ssi_if.t
@@ -37,7 +37,7 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
         location / {
             ssi on;
--- a/ssi_include_big.t
+++ b/ssi_include_big.t
@@ -40,11 +40,11 @@ http {
     gzip on;
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         location /proxy/ {
-            proxy_pass http://127.0.0.1:8080/local/;
+            proxy_pass http://127.0.0.1:%%PORT_0%%/local/;
         }
         location = /local/blah {
             return 204;
--- a/ssi_waited.t
+++ b/ssi_waited.t
@@ -36,7 +36,7 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
         location / {
             ssi on;
--- a/ssl.t
+++ b/ssl.t
@@ -48,8 +48,8 @@ http {
     ssl_session_tickets off;
 
     server {
-        listen       127.0.0.1:8443 ssl;
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_5%% ssl;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         ssl_certificate_key inner.key;
@@ -74,7 +74,7 @@ http {
     }
 
     server {
-        listen      127.0.0.1:8081;
+        listen      127.0.0.1:%%PORT_1%%;
         server_name  localhost;
 
         # Special case for enabled "ssl" directive.
@@ -89,7 +89,7 @@ http {
     }
 
     server {
-        listen      127.0.0.1:8082 ssl;
+        listen      127.0.0.1:%%PORT_2%% ssl;
         server_name  localhost;
 
         ssl_session_cache builtin:1000;
@@ -100,7 +100,7 @@ http {
     }
 
     server {
-        listen      127.0.0.1:8083 ssl;
+        listen      127.0.0.1:%%PORT_3%% ssl;
         server_name  localhost;
 
         ssl_session_cache none;
@@ -111,7 +111,7 @@ http {
     }
 
     server {
-        listen      127.0.0.1:8084 ssl;
+        listen      127.0.0.1:%%PORT_4%% ssl;
         server_name  localhost;
 
         ssl_session_cache off;
@@ -150,39 +150,39 @@ my $ctx = new IO::Socket::SSL::SSL_Conte
 
 ###############################################################################
 
-like(http_get('/reuse', socket => get_ssl_socket($ctx)), qr/^body \.$/m,
-	'shared initial session');
-like(http_get('/reuse', socket => get_ssl_socket($ctx)), qr/^body r$/m,
-	'shared session reused');
+like(http_get('/reuse', socket => get_ssl_socket($ctx, port(5))),
+	qr/^body \.$/m, 'shared initial session');
+like(http_get('/reuse', socket => get_ssl_socket($ctx, port(5))),
+	qr/^body r$/m, 'shared session reused');
 
-like(http_get('/', socket => get_ssl_socket($ctx, 8081)), qr/^body \.$/m,
+like(http_get('/', socket => get_ssl_socket($ctx, port(1))), qr/^body \.$/m,
 	'builtin initial session');
-like(http_get('/', socket => get_ssl_socket($ctx, 8081)), qr/^body r$/m,
+like(http_get('/', socket => get_ssl_socket($ctx, port(1))), qr/^body r$/m,
 	'builtin session reused');
 
-like(http_get('/', socket => get_ssl_socket($ctx, 8082)), qr/^body \.$/m,
+like(http_get('/', socket => get_ssl_socket($ctx, port(2))), qr/^body \.$/m,
 	'builtin size initial session');
-like(http_get('/', socket => get_ssl_socket($ctx, 8082)), qr/^body r$/m,
+like(http_get('/', socket => get_ssl_socket($ctx, port(2))), qr/^body r$/m,
 	'builtin size session reused');
 
-like(http_get('/', socket => get_ssl_socket($ctx, 8083)), qr/^body \.$/m,
+like(http_get('/', socket => get_ssl_socket($ctx, port(3))), qr/^body \.$/m,
 	'reused none initial session');
-like(http_get('/', socket => get_ssl_socket($ctx, 8083)), qr/^body \.$/m,
+like(http_get('/', socket => get_ssl_socket($ctx, port(3))), qr/^body \.$/m,
 	'session not reused 1');
 
-like(http_get('/', socket => get_ssl_socket($ctx, 8084)), qr/^body \.$/m,
+like(http_get('/', socket => get_ssl_socket($ctx, port(4))), qr/^body \.$/m,
 	'reused off initial session');
-like(http_get('/', socket => get_ssl_socket($ctx, 8084)), qr/^body \.$/m,
+like(http_get('/', socket => get_ssl_socket($ctx, port(4))), qr/^body \.$/m,
 	'session not reused 2');
 
 # ssl certificate inheritance
 
-my $s = get_ssl_socket($ctx, 8081);
+my $s = get_ssl_socket($ctx, port(1));
 like($s->dump_peer_certificate(), qr/CN=localhost/, 'CN');
 
 $s->close();
 
-$s = get_ssl_socket($ctx);
+$s = get_ssl_socket($ctx, port(5));
 like($s->dump_peer_certificate(), qr/CN=inner/, 'CN inner');
 
 $s->close();
@@ -191,23 +191,24 @@ like($s->dump_peer_certificate(), qr/CN=
 
 select undef, undef, undef, 2.1;
 
-like(http_get('/', socket => get_ssl_socket($ctx, 8081)), qr/^body \.$/m,
+like(http_get('/', socket => get_ssl_socket($ctx, port(1))), qr/^body \.$/m,
 	'session timeout');
 
 # embedded variables
 
-my ($sid) = http_get('/id', socket => get_ssl_socket($ctx)) =~ /^body (\w+)$/m;
+my ($sid) = http_get('/id',
+	socket => get_ssl_socket($ctx, port(5))) =~ /^body (\w+)$/m;
 is(length $sid, 64, 'session id');
 
 unlike(http_get('/id'), qr/body \w/, 'session id no ssl');
 
-like(http_get('/cipher', socket => get_ssl_socket($ctx)),
+like(http_get('/cipher', socket => get_ssl_socket($ctx, port(5))),
 	qr/^body [\w-]+$/m, 'cipher');
 
-like(http_get('/client_verify', socket => get_ssl_socket($ctx)),
+like(http_get('/client_verify', socket => get_ssl_socket($ctx, port(5))),
 	qr/^body NONE$/m, 'client verify');
 
-like(http_get('/protocol', socket => get_ssl_socket($ctx)),
+like(http_get('/protocol', socket => get_ssl_socket($ctx, port(5))),
 	qr/^body (TLS|SSL)v(\d|\.)+$/m, 'protocol');
 
 ###############################################################################
@@ -223,7 +224,7 @@ sub get_ssl_socket {
 		$s = IO::Socket::SSL->new(
 			Proto => 'tcp',
 			PeerAddr => '127.0.0.1',
-			PeerPort => $port || '8443',
+			PeerPort => $port,
 			SSL_verify_mode => IO::Socket::SSL::SSL_VERIFY_NONE(),
 			SSL_reuse_ctx => $ctx,
 			SSL_error_trap => sub { die $_[1] }
--- a/ssl_certificate_chain.t
+++ b/ssl_certificate_chain.t
@@ -43,7 +43,7 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen       127.0.0.1:8081 ssl;
+        listen       127.0.0.1:%%PORT_0%% ssl;
         server_name  localhost;
 
         ssl_certificate_key end.key;
@@ -51,7 +51,7 @@ http {
     }
 
     server {
-        listen       127.0.0.1:8082 ssl;
+        listen       127.0.0.1:%%PORT_1%% ssl;
         server_name  localhost;
 
         ssl_certificate_key int.key;
@@ -59,7 +59,7 @@ http {
     }
 
     server {
-        listen       127.0.0.1:8083 ssl;
+        listen       127.0.0.1:%%PORT_2%% ssl;
         server_name  localhost;
 
         ssl_certificate_key end.key;
@@ -137,9 +137,9 @@ system("openssl ca -batch -config '$d/ca
 
 ###############################################################################
 
-is(get_ssl_socket(8081), undef, 'incomplete chain');
-ok(get_ssl_socket(8082), 'intermediate');
-ok(get_ssl_socket(8083), 'intermediate server');
+is(get_ssl_socket(port(0)), undef, 'incomplete chain');
+ok(get_ssl_socket(port(1)), 'intermediate');
+ok(get_ssl_socket(port(2)), 'intermediate server');
 
 ###############################################################################
 
--- a/ssl_certificates.t
+++ b/ssl_certificates.t
@@ -47,7 +47,7 @@ http {
     ssl_certificate rsa.crt;
 
     server {
-        listen       127.0.0.1:8443 ssl;
+        listen       127.0.0.1:%%PORT_0%% ssl;
         server_name  localhost;
 
         ssl_certificate_key dsa.key;
@@ -108,7 +108,7 @@ sub get_cert {
 		$s = IO::Socket::SSL->new(
 			Proto => 'tcp',
 			PeerAddr => '127.0.0.1',
-			PeerPort => '8443',
+			PeerPort => port(0),
 			SSL_verify_mode => IO::Socket::SSL::SSL_VERIFY_NONE(),
 			SSL_cipher_list => $ciphers,
 			SSL_error_trap => sub { die $_[1] }
--- a/ssl_engine_keys.t
+++ b/ssl_engine_keys.t
@@ -43,8 +43,8 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen       127.0.0.1:8443 ssl;
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_1%% ssl;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         ssl_certificate_key engine:pkcs11:slot_0-id_00;
@@ -54,7 +54,7 @@ http {
             # index index.html by default
         }
         location /proxy {
-            proxy_pass https://127.0.0.1:8443/;
+            proxy_pass https://127.0.0.1:%%PORT_1%%/;
         }
     }
 }
--- a/ssl_password_file.t
+++ b/ssl_password_file.t
@@ -54,8 +54,8 @@ http {
     ssl_password_file password_http;
 
     server {
-        listen       127.0.0.1:8443 ssl;
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_1%% ssl;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         ssl_password_file password;
@@ -66,21 +66,21 @@ http {
     }
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  two_entries;
 
         ssl_password_file password_many;
     }
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  file_is_fifo;
 
         ssl_password_file password_fifo;
     }
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  inherits;
 
         ssl_certificate_key inherits.key;
@@ -148,7 +148,7 @@ sub get_ssl_socket {
 		alarm(2);
 		$s = IO::Socket::SSL->new(
 			Proto => 'tcp',
-			PeerAddr => '127.0.0.1:8443',
+			PeerAddr => '127.0.0.1:' . port(1),
 			SSL_verify_mode => IO::Socket::SSL::SSL_VERIFY_NONE(),
 			SSL_error_trap => sub { die $_[1] }
 		);
--- a/ssl_proxy_protocol.t
+++ b/ssl_proxy_protocol.t
@@ -47,7 +47,7 @@ http {
     log_format pp '$remote_addr $request';
 
     server {
-        listen       127.0.0.1:8080 proxy_protocol ssl;
+        listen       127.0.0.1:%%PORT_0%% proxy_protocol ssl;
         server_name  localhost;
 
         ssl_certificate_key localhost.key;
--- a/ssl_proxy_upgrade.t
+++ b/ssl_proxy_upgrade.t
@@ -51,14 +51,14 @@ http {
     access_log %%TESTDIR%%/cc.log test;
 
     server {
-        listen       127.0.0.1:8080 ssl;
+        listen       127.0.0.1:%%PORT_0%% ssl;
         server_name  localhost;
 
         ssl_certificate_key localhost.key;
         ssl_certificate localhost.crt;
 
         location / {
-            proxy_pass    http://127.0.0.1:8081;
+            proxy_pass    http://127.0.0.1:%%PORT_1%%;
             proxy_http_version 1.1;
             proxy_set_header Upgrade $http_upgrade;
             proxy_set_header Connection "Upgrade";
@@ -91,7 +91,7 @@ foreach my $name ('localhost') {
 $t->run_daemon(\&upgrade_fake_daemon);
 $t->run();
 
-$t->waitforsocket('127.0.0.1:8081')
+$t->waitforsocket('127.0.0.1:' . port(1))
 	or die "Can't start test backend";
 
 ###############################################################################
@@ -173,7 +173,7 @@ sub upgrade_connect {
 
 	my $s = IO::Socket::SSL->new(
 		Proto => 'tcp',
-		PeerAddr => '127.0.0.1:8080',
+		PeerAddr => '127.0.0.1:' . port(0),
 		SSL_verify_mode => IO::Socket::SSL::SSL_VERIFY_NONE(),
 	)
 		or die "Can't connect to nginx: $!\n";
@@ -283,7 +283,7 @@ sub upgrade_read {
 sub upgrade_fake_daemon {
 	my $server = IO::Socket::INET->new(
 		Proto => 'tcp',
-		LocalAddr => '127.0.0.1:8081',
+		LocalAddr => '127.0.0.1:' . port(1),
 		Listen => 5,
 		Reuse => 1
 	)
--- a/ssl_sni.t
+++ b/ssl_sni.t
@@ -37,7 +37,7 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen       127.0.0.1:8443 ssl;
+        listen       127.0.0.1:%%PORT_0%% ssl;
         server_name  localhost;
 
         ssl_certificate_key localhost.key;
@@ -49,7 +49,7 @@ http {
     }
 
     server {
-        listen       127.0.0.1:8443;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  example.com;
 
         ssl_certificate_key example.com.key;
@@ -136,7 +136,7 @@ sub get_ssl_socket {
 		alarm(2);
 		$s = IO::Socket::SSL->new(
 			Proto => 'tcp',
-			PeerAddr => '127.0.0.1:8443',
+			PeerAddr => '127.0.0.1:' . port(0),
 			SSL_hostname => $host,
 			SSL_verify_mode => IO::Socket::SSL::SSL_VERIFY_NONE(),
 			SSL_error_trap => sub { die $_[1] }
--- a/ssl_sni_reneg.t
+++ b/ssl_sni_reneg.t
@@ -58,7 +58,7 @@ http {
     ssl_certificate localhost.crt;
 
     server {
-        listen       127.0.0.1:8443 ssl;
+        listen       127.0.0.1:%%PORT_0%% ssl;
         server_name  localhost;
 
         location / { }
@@ -118,7 +118,7 @@ sub get_ssl_socket {
 	my $s;
 
 	my $dest_ip = inet_aton('127.0.0.1');
-	my $dest_serv_params = sockaddr_in(8443, $dest_ip);
+	my $dest_serv_params = sockaddr_in(port(0), $dest_ip);
 
 	eval {
 		local $SIG{ALRM} = sub { die "timeout\n" };
--- a/ssl_sni_sessions.t
+++ b/ssl_sni_sessions.t
@@ -39,7 +39,7 @@ http {
     ssl_certificate localhost.crt;
 
     server {
-        listen       127.0.0.1:8443 ssl;
+        listen       127.0.0.1:%%PORT_0%% ssl;
         server_name  default;
 
         ssl_session_tickets off;
@@ -51,7 +51,7 @@ http {
     }
 
     server {
-        listen       127.0.0.1:8443;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  nocache;
 
         ssl_session_tickets off;
@@ -63,7 +63,7 @@ http {
     }
 
     server {
-        listen       127.0.0.1:8444 ssl;
+        listen       127.0.0.1:%%PORT_1%% ssl;
         server_name  default;
 
         ssl_session_ticket_key ticket1.key;
@@ -74,7 +74,7 @@ http {
     }
 
     server {
-        listen       127.0.0.1:8444;
+        listen       127.0.0.1:%%PORT_1%%;
         server_name  tickets;
 
         ssl_session_ticket_key ticket2.key;
@@ -135,8 +135,8 @@ foreach my $name ('localhost') {
 
 my $ctx = get_ssl_context();
 
-like(get('default', 8443, $ctx), qr!default:\.!, 'default server');
-like(get('default', 8443, $ctx), qr!default:r!, 'default server reused');
+like(get('default', port(0), $ctx), qr!default:\.!, 'default server');
+like(get('default', port(0), $ctx), qr!default:r!, 'default server reused');
 
 # check that sessions are still properly saved and restored
 # when using an SNI-based virtual server with different session cache;
@@ -150,16 +150,16 @@ like(get('default', 8443, $ctx), qr!defa
 
 $ctx = get_ssl_context();
 
-like(get('nocache', 8443, $ctx), qr!nocache:\.!, 'without cache');
-like(get('nocache', 8443, $ctx), qr!nocache:r!, 'without cache reused');
+like(get('nocache', port(0), $ctx), qr!nocache:\.!, 'without cache');
+like(get('nocache', port(0), $ctx), qr!nocache:r!, 'without cache reused');
 
 # make sure tickets can be used if an SNI-based virtual server
 # uses a different set of session ticket keys explicitly set
 
 $ctx = get_ssl_context();
 
-like(get('tickets', 8444, $ctx), qr!tickets:\.!, 'tickets');
-like(get('tickets', 8444, $ctx), qr!tickets:r!, 'tickets reused');
+like(get('tickets', port(1), $ctx), qr!tickets:\.!, 'tickets');
+like(get('tickets', port(1), $ctx), qr!tickets:r!, 'tickets reused');
 
 ###############################################################################
 
--- a/ssl_verify_client.t
+++ b/ssl_verify_client.t
@@ -50,7 +50,7 @@ http {
     add_header X-Verify $ssl_client_verify;
 
     server {
-        listen       127.0.0.1:8443 ssl;
+        listen       127.0.0.1:%%PORT_0%% ssl;
         server_name  localhost;
 
         ssl_client_certificate client.crt;
@@ -59,7 +59,7 @@ http {
     }
 
     server {
-        listen       127.0.0.1:8443 ssl;
+        listen       127.0.0.1:%%PORT_0%% ssl;
         server_name  example.com;
 
         location / { }
@@ -119,7 +119,7 @@ sub get {
 		$s = IO::Socket::SSL->new(
 			Proto => 'tcp',
 			PeerAddr => '127.0.0.1',
-			PeerPort => 8443,
+			PeerPort => port(0),
 			SSL_verify_mode => IO::Socket::SSL::SSL_VERIFY_NONE(),
 			SSL_hostname => $sni,
 			SSL_cert_file => "$d/client.crt",
--- a/stream_access.t
+++ b/stream_access.t
@@ -36,110 +36,110 @@ events {
 
 stream {
     server {
-        listen       127.0.0.1:8082;
-        proxy_pass   [::1]:8080;
+        listen       127.0.0.1:%%PORT_2%%;
+        proxy_pass   [::1]:%%PORT_0%%;
     }
 
     server {
-        listen       127.0.0.1:8083;
+        listen       127.0.0.1:%%PORT_3%%;
         proxy_pass   unix:%%TESTDIR%%/unix.sock.0;
     }
 
     server {
-        listen       127.0.0.1:8085;
-        proxy_pass   [::1]:8081;
+        listen       127.0.0.1:%%PORT_5%%;
+        proxy_pass   [::1]:%%PORT_1%%;
     }
 
     server {
-        listen       127.0.0.1:8086;
+        listen       127.0.0.1:%%PORT_6%%;
         proxy_pass   unix:%%TESTDIR%%/unix.sock.1;
     }
 
     server {
-        listen       127.0.0.1:8088;
-        proxy_pass   [::1]:8082;
+        listen       127.0.0.1:%%PORT_8%%;
+        proxy_pass   [::1]:%%PORT_2%%;
     }
 
     server {
-        listen       127.0.0.1:8089;
+        listen       127.0.0.1:%%PORT_9%%;
         proxy_pass   unix:%%TESTDIR%%/unix.sock.2;
     }
 
     server {
-        listen       127.0.0.1:8091;
-        proxy_pass   [::1]:8083;
+        listen       127.0.0.1:%%PORT_11%%;
+        proxy_pass   [::1]:%%PORT_3%%;
     }
 
     server {
-        listen       127.0.0.1:8092;
+        listen       127.0.0.1:%%PORT_12%%;
         proxy_pass   unix:%%TESTDIR%%/unix.sock.3;
     }
 
     server {
-        listen       127.0.0.1:8094;
-        proxy_pass   [::1]:8084;
+        listen       127.0.0.1:%%PORT_14%%;
+        proxy_pass   [::1]:%%PORT_4%%;
     }
 
     server {
-        listen       127.0.0.1:8095;
+        listen       127.0.0.1:%%PORT_15%%;
         proxy_pass   unix:%%TESTDIR%%/unix.sock.4;
     }
 
     server {
-        listen       127.0.0.1:8097;
-        proxy_pass   [::1]:8085;
+        listen       127.0.0.1:%%PORT_17%%;
+        proxy_pass   [::1]:%%PORT_5%%;
     }
 
     server {
-        listen       127.0.0.1:8098;
+        listen       127.0.0.1:%%PORT_18%%;
         proxy_pass   unix:%%TESTDIR%%/unix.sock.5;
     }
 
     server {
-        listen       127.0.0.1:8081;
-        listen       [::1]:8080;
+        listen       127.0.0.1:%%PORT_1%%;
+        listen       [::1]:%%PORT_0%%;
         listen       unix:%%TESTDIR%%/unix.sock.0;
-        proxy_pass   127.0.0.1:8080;
+        proxy_pass   127.0.0.1:%%PORT_0%%;
         allow        all;
     }
 
     server {
-        listen       127.0.0.1:8084;
-        listen       [::1]:8081;
+        listen       127.0.0.1:%%PORT_4%%;
+        listen       [::1]:%%PORT_1%%;
         listen       unix:%%TESTDIR%%/unix.sock.1;
-        proxy_pass   127.0.0.1:8080;
+        proxy_pass   127.0.0.1:%%PORT_0%%;
         deny         all;
     }
 
     server {
-        listen       127.0.0.1:8087;
-        listen       [::1]:8082;
+        listen       127.0.0.1:%%PORT_7%%;
+        listen       [::1]:%%PORT_2%%;
         listen       unix:%%TESTDIR%%/unix.sock.2;
-        proxy_pass   127.0.0.1:8080;
+        proxy_pass   127.0.0.1:%%PORT_0%%;
         allow        unix:;
     }
 
     server {
-        listen       127.0.0.1:8090;
-        listen       [::1]:8083;
+        listen       127.0.0.1:%%PORT_10%%;
+        listen       [::1]:%%PORT_3%%;
         listen       unix:%%TESTDIR%%/unix.sock.3;
-        proxy_pass   127.0.0.1:8080;
+        proxy_pass   127.0.0.1:%%PORT_0%%;
         deny         127.0.0.1;
     }
 
     server {
-        listen       127.0.0.1:8093;
-        listen       [::1]:8084;
+        listen       127.0.0.1:%%PORT_13%%;
+        listen       [::1]:%%PORT_4%%;
         listen       unix:%%TESTDIR%%/unix.sock.4;
-        proxy_pass   127.0.0.1:8080;
+        proxy_pass   127.0.0.1:%%PORT_0%%;
         deny         ::1;
     }
 
     server {
-        listen       127.0.0.1:8096;
-        listen       [::1]:8085;
+        listen       127.0.0.1:%%PORT_16%%;
+        listen       [::1]:%%PORT_5%%;
         listen       unix:%%TESTDIR%%/unix.sock.5;
-        proxy_pass   127.0.0.1:8080;
+        proxy_pass   127.0.0.1:%%PORT_0%%;
         deny         unix:;
     }
 }
@@ -148,7 +148,7 @@ EOF
 
 $t->try_run('no inet6 support')->plan(18);
 $t->run_daemon(\&stream_daemon);
-$t->waitforsocket('127.0.0.1:8080');
+$t->waitforsocket('127.0.0.1:' . port(0));
 
 ###############################################################################
 
@@ -156,46 +156,46 @@ my $str = 'SEE-THIS';
 
 # allow all
 
-is(stream('127.0.0.1:8081')->io($str), $str, 'inet allow all');
-is(stream('127.0.0.1:8082')->io($str), $str, 'inet6 allow all');
-is(stream('127.0.0.1:8083')->io($str), $str, 'unix allow all');
+is(stream('127.0.0.1:' . port(1))->io($str), $str, 'inet allow all');
+is(stream('127.0.0.1:' . port(2))->io($str), $str, 'inet6 allow all');
+is(stream('127.0.0.1:' . port(3))->io($str), $str, 'unix allow all');
 
 # deny all
 
-is(stream('127.0.0.1:8084')->io($str), '', 'inet deny all');
-is(stream('127.0.0.1:8085')->io($str), '', 'inet6 deny all');
-is(stream('127.0.0.1:8086')->io($str), '', 'unix deny all');
+is(stream('127.0.0.1:' . port(4))->io($str), '', 'inet deny all');
+is(stream('127.0.0.1:' . port(5))->io($str), '', 'inet6 deny all');
+is(stream('127.0.0.1:' . port(6))->io($str), '', 'unix deny all');
 
 # allow unix
 
-is(stream('127.0.0.1:8087')->io($str), $str, 'inet allow unix');
-is(stream('127.0.0.1:8088')->io($str), $str, 'inet6 allow unix');
-is(stream('127.0.0.1:8089')->io($str), $str, 'unix allow unix');
+is(stream('127.0.0.1:' . port(7))->io($str), $str, 'inet allow unix');
+is(stream('127.0.0.1:' . port(8))->io($str), $str, 'inet6 allow unix');
+is(stream('127.0.0.1:' . port(9))->io($str), $str, 'unix allow unix');
 
 # deny inet
 
-is(stream('127.0.0.1:8090')->io($str), '', 'inet deny inet');
-is(stream('127.0.0.1:8091')->io($str), $str, 'inet6 deny inet');
-is(stream('127.0.0.1:8092')->io($str), $str, 'unix deny inet');
+is(stream('127.0.0.1:' . port(10))->io($str), '', 'inet deny inet');
+is(stream('127.0.0.1:' . port(11))->io($str), $str, 'inet6 deny inet');
+is(stream('127.0.0.1:' . port(12))->io($str), $str, 'unix deny inet');
 
 # deny inet6
 
-is(stream('127.0.0.1:8093')->io($str), $str, 'inet deny inet6');
-is(stream('127.0.0.1:8094')->io($str), '', 'inet6 deny inet6');
-is(stream('127.0.0.1:8095')->io($str), $str, 'unix deny inet6');
+is(stream('127.0.0.1:' . port(13))->io($str), $str, 'inet deny inet6');
+is(stream('127.0.0.1:' . port(14))->io($str), '', 'inet6 deny inet6');
+is(stream('127.0.0.1:' . port(15))->io($str), $str, 'unix deny inet6');
 
 # deny unix
 
-is(stream('127.0.0.1:8096')->io($str), $str, 'inet deny unix');
-is(stream('127.0.0.1:8097')->io($str), $str, 'inet6 deny unix');
-is(stream('127.0.0.1:8098')->io($str), '', 'unix deny unix');
+is(stream('127.0.0.1:' . port(16))->io($str), $str, 'inet deny unix');
+is(stream('127.0.0.1:' . port(17))->io($str), $str, 'inet6 deny unix');
+is(stream('127.0.0.1:' . port(18))->io($str), '', 'unix deny unix');
 
 ###############################################################################
 
 sub stream_daemon {
 	my $server = IO::Socket::INET->new(
 		Proto => 'tcp',
-		LocalAddr => '127.0.0.1:8080',
+		LocalAddr => '127.0.0.1:' . port(0),
 		Listen => 5,
 		Reuse => 1
 	)
--- a/stream_error_log.t
+++ b/stream_error_log.t
@@ -35,7 +35,7 @@ my $t = Test::Nginx->new()->has(qw/strea
 
 error_log %%TESTDIR%%/e_glob.log info;
 error_log %%TESTDIR%%/e_glob2.log info;
-error_log syslog:server=127.0.0.1:8083 info;
+error_log syslog:server=127.0.0.1:%%PORT_3_UDP%% info;
 
 daemon off;
 
@@ -44,11 +44,11 @@ events {
 
 stream {
     upstream u {
-        server 127.0.0.1:8083 down;
+        server 127.0.0.1:%%PORT_3_UDP%% down;
     }
 
     server {
-        listen      127.0.0.1:8080;
+        listen      127.0.0.1:%%PORT_0%%;
         proxy_pass  u;
 
         error_log %%TESTDIR%%/e_debug.log debug;
@@ -58,12 +58,12 @@ stream {
     }
 
     server {
-        listen      127.0.0.1:8082;
-        proxy_pass  127.0.0.1:8081;
+        listen      127.0.0.1:%%PORT_2%%;
+        proxy_pass  127.0.0.1:%%PORT_1%%;
 
         error_log %%TESTDIR%%/e_stream.log info;
-        error_log syslog:server=127.0.0.1:8080 info;
-        error_log syslog:server=127.0.0.1:8084 info;
+        error_log syslog:server=127.0.0.1:%%PORT_5_UDP%% info;
+        error_log syslog:server=127.0.0.1:%%PORT_4_UDP%% info;
     }
 }
 
@@ -75,10 +75,10 @@ open my $stderr, '<', $t->testdir() . '/
 	or die "Can't open stderr file: $!";
 
 $t->run_daemon(\&stream_daemon);
-$t->run_daemon(\&syslog_daemon, 8083, $t, 's_glob.log');
-$t->run_daemon(\&syslog_daemon, 8084, $t, 's_stream.log');
+$t->run_daemon(\&syslog_daemon, port(3), $t, 's_glob.log');
+$t->run_daemon(\&syslog_daemon, port(4), $t, 's_stream.log');
 
-$t->waitforsocket('127.0.0.1:8081');
+$t->waitforsocket('127.0.0.1:' . port(1));
 $t->waitforfile($t->testdir . '/s_glob.log');
 $t->waitforfile($t->testdir . '/s_stream.log');
 
@@ -113,7 +113,8 @@ is_deeply(levels($t, 'e_glob.log'), leve
 
 # syslog
 
-parse_syslog_message('syslog', get_syslog('data2', '127.0.0.1:8082'));
+parse_syslog_message('syslog', get_syslog('data2', '127.0.0.1:' . port(2),
+	port(5)));
 
 is_deeply(levels($t, 's_glob.log'), levels($t, 'e_glob.log'),
 	'global syslog messages');
@@ -126,7 +127,7 @@ SKIP: {
 skip "relies on error log contents", 5 unless $ENV{TEST_NGINX_UNSAFE};
 
 my $msg = 'no live upstreams while connecting to upstream, '
-	. 'client: 127.0.0.1, server: 127.0.0.1:8080, upstream: "u"';
+	. 'client: 127.0.0.1, server: 127.0.0.1:' . port(0) . ', upstream: "u"';
 
 unlike($t->read_file('e_glob.log'), qr/$msg/ms, 'stream error in global');
 like($t->read_file('e_info.log'), qr/$msg/ms, 'stream error in info');
@@ -168,8 +169,6 @@ sub get_syslog {
 	my ($data, $peer, $port) = @_;
 	my ($s);
 
-	$port = 8080 unless defined $port;
-
 	eval {
 		local $SIG{ALRM} = sub { die "timeout\n" };
 		local $SIG{PIPE} = sub { die "sigpipe\n" };
@@ -276,7 +275,7 @@ sub stream_daemon {
 	my $server = IO::Socket::INET->new(
 		Proto => 'tcp',
 		LocalHost => '127.0.0.1',
-		LocalPort => 8081,
+		LocalPort => port(1),
 		Listen => 5,
 		Reuse => 1
 	)
--- a/stream_limit_conn.t
+++ b/stream_limit_conn.t
@@ -37,32 +37,32 @@ stream {
     limit_conn_zone  $binary_remote_addr  zone=zone2:1m;
 
     server {
-        listen           127.0.0.1:8080;
-        proxy_pass       127.0.0.1:8084;
+        listen           127.0.0.1:%%PORT_0%%;
+        proxy_pass       127.0.0.1:%%PORT_4%%;
         limit_conn       zone 1;
     }
 
     server {
-        listen           127.0.0.1:8085;
-        proxy_pass       127.0.0.1:8084;
+        listen           127.0.0.1:%%PORT_5%%;
+        proxy_pass       127.0.0.1:%%PORT_4%%;
         limit_conn       zone 5;
     }
 
     server {
-        listen           127.0.0.1:8081;
-        proxy_pass       127.0.0.1:8084;
+        listen           127.0.0.1:%%PORT_1%%;
+        proxy_pass       127.0.0.1:%%PORT_4%%;
         limit_conn       zone2 1;
     }
 
     server {
-        listen           127.0.0.1:8082;
-        proxy_pass       127.0.0.1:8080;
+        listen           127.0.0.1:%%PORT_2%%;
+        proxy_pass       127.0.0.1:%%PORT_0%%;
         limit_conn       zone2 1;
     }
 
     server {
-        listen           127.0.0.1:8083;
-        proxy_pass       127.0.0.1:8080;
+        listen           127.0.0.1:%%PORT_3%%;
+        proxy_pass       127.0.0.1:%%PORT_0%%;
         limit_conn       zone 1;
     }
 }
@@ -71,7 +71,7 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen       127.0.0.1:8084;
+        listen       127.0.0.1:%%PORT_4%%;
         server_name  localhost;
 
         location / { }
@@ -96,8 +96,8 @@ EOF
 ok($s, 'long connection');
 
 is(get(), undef, 'rejected same zone');
-like(get('127.0.0.1:8081'), qr/200 OK/, 'passed different zone');
-like(get('127.0.0.1:8085'), qr/200 OK/, 'passed same zone unlimited');
+like(get('127.0.0.1:' . port(1)), qr/200 OK/, 'passed different zone');
+like(get('127.0.0.1:' . port(5)), qr/200 OK/, 'passed same zone unlimited');
 
 ok(http(<<EOF, socket => $s), 'long connection closed');
 Host: localhost
@@ -106,8 +106,8 @@ EOF
 
 # zones proxy chain
 
-like(get('127.0.0.1:8082'), qr/200 OK/, 'passed proxy');
-is(get('127.0.0.1:8083'), undef, 'rejected proxy');
+like(get('127.0.0.1:' . port(2)), qr/200 OK/, 'passed proxy');
+is(get('127.0.0.1:' . port(3)), undef, 'rejected proxy');
 
 ###############################################################################
 
@@ -126,7 +126,7 @@ sub getconn {
 	my $peer = shift;
 	my $s = IO::Socket::INET->new(
 		Proto => 'tcp',
-		PeerAddr => $peer || '127.0.0.1:8080'
+		PeerAddr => $peer || '127.0.0.1:' . port(0)
 	)
 		or die "Can't connect to nginx: $!\n";
 
--- a/stream_limit_rate.t
+++ b/stream_limit_rate.t
@@ -46,59 +46,59 @@ stream {
     proxy_upload_rate        1000;
 
     server {
-        listen               127.0.0.1:8081;
-        proxy_pass           127.0.0.1:8080;
+        listen               127.0.0.1:%%PORT_1%%;
+        proxy_pass           127.0.0.1:%%PORT_0%%;
     }
 
     server {
-        listen               127.0.0.1:8082;
-        proxy_pass           127.0.0.1:8080;
+        listen               127.0.0.1:%%PORT_2%%;
+        proxy_pass           127.0.0.1:%%PORT_0%%;
         proxy_download_rate  0;
         proxy_upload_rate    0;
     }
 
     server {
-        listen               127.0.0.1:8083;
-        proxy_pass           127.0.0.1:8080;
+        listen               127.0.0.1:%%PORT_3%%;
+        proxy_pass           127.0.0.1:%%PORT_0%%;
         proxy_download_rate  1;
     }
 
     server {
-        listen               127.0.0.1:8084;
-        proxy_pass           127.0.0.1:8080;
+        listen               127.0.0.1:%%PORT_4%%;
+        proxy_pass           127.0.0.1:%%PORT_0%%;
         proxy_upload_rate    1;
     }
 
     server {
-        listen               127.0.0.1:8085;
-        proxy_pass           127.0.0.1:8080;
+        listen               127.0.0.1:%%PORT_5%%;
+        proxy_pass           127.0.0.1:%%PORT_0%%;
         proxy_download_rate  250;
     }
 
     server {
-        listen               127.0.0.1:8086;
-        proxy_pass           127.0.0.1:8090;
+        listen               127.0.0.1:%%PORT_6%%;
+        proxy_pass           127.0.0.1:%%PORT_7%%;
         proxy_upload_rate    250;
     }
 }
 
 EOF
 
-$t->run_daemon(\&stream_daemon, 8080);
-$t->run_daemon(\&stream_daemon, 8090);
+$t->run_daemon(\&stream_daemon, port(0));
+$t->run_daemon(\&stream_daemon, port(7));
 $t->run();
 
-$t->waitforsocket('127.0.0.1:8080');
-$t->waitforsocket('127.0.0.1:8090');
+$t->waitforsocket('127.0.0.1:' . port(0));
+$t->waitforsocket('127.0.0.1:' . port(7));
 
 ###############################################################################
 
 my $str = '1234567890' x 100;
 
-my %r = response($str, peer => '127.0.0.1:8081');
+my %r = response($str, peer => '127.0.0.1:' . port(1));
 is($r{'data'}, $str, 'exact limit');
 
-%r = response($str, peer => '127.0.0.1:8082');
+%r = response($str, peer => '127.0.0.1:' . port(2));
 is($r{'data'}, $str, 'unlimited');
 
 SKIP: {
@@ -107,10 +107,10 @@ skip 'unsafe on VM', 2 unless $ENV{TEST_
 # if interaction between backend and client is slow then proxy can add extra
 # bytes to upload/download data
 
-%r = response($str, peer => '127.0.0.1:8083', readonce => 1);
+%r = response($str, peer => '127.0.0.1:' . port(3), readonce => 1);
 is($r{'data'}, '1', 'download - one byte');
 
-%r = response($str, peer =>  '127.0.0.1:8084');
+%r = response($str, peer =>  '127.0.0.1:' . port(4));
 is($r{'data'}, '1', 'upload - one byte');
 
 }
@@ -119,13 +119,13 @@ is($r{'data'}, '1', 'upload - one byte')
 # the first four chunks are quarters of test string
 # and the fifth one is some extra data from backend.
 
-%r = response($str, peer =>  '127.0.0.1:8085');
+%r = response($str, peer =>  '127.0.0.1:' . port(5));
 my $diff = time() - $r{'time'};
 cmp_ok($diff, '>=', 4, 'download - time');
 is($r{'data'}, $str, 'download - data');
 
 my $time = time();
-%r = response($str . 'close', peer => '127.0.0.1:8086');
+%r = response($str . 'close', peer => '127.0.0.1:' . port(6));
 $diff = time() - $time;
 cmp_ok($diff, '>=', 4, 'upload - time');
 is($r{'data'}, $str . 'close', 'upload - data');
@@ -156,6 +156,7 @@ sub response {
 
 sub stream_daemon {
 	my $port = shift;
+
 	my $server = IO::Socket::INET->new(
 		Proto => 'tcp',
 		LocalAddr => '127.0.0.1',
@@ -193,13 +194,13 @@ sub stream_handle_client {
 
 	log2i("$client $buffer");
 
-	$buffer .= " " . time() if $client->sockport() eq 8080;
+	$buffer .= " " . time() if $client->sockport() eq port(0);
 
 	log2o("$client $buffer");
 
 	$client->syswrite($buffer);
 
-	return $client->sockport() eq 8080 ? 1 : $buffer =~ /close/;
+	return $client->sockport() eq port(0) ? 1 : $buffer =~ /close/;
 }
 
 sub log2i { Test::Nginx::log_core('|| <<', @_); }
--- a/stream_proxy.t
+++ b/stream_proxy.t
@@ -37,8 +37,8 @@ events {
 
 stream {
     server {
-        listen      127.0.0.1:8080;
-        proxy_pass  127.0.0.1:8081;
+        listen      127.0.0.1:%%PORT_0%%;
+        proxy_pass  127.0.0.1:%%PORT_1%%;
         proxy_connect_timeout 2s;
     }
 }
@@ -46,7 +46,7 @@ stream {
 EOF
 
 $t->run_daemon(\&stream_daemon);
-$t->run()->waitforsocket('127.0.0.1:8081');
+$t->run()->waitforsocket('127.0.0.1:' . port(1));
 
 ###############################################################################
 
@@ -68,7 +68,7 @@ is($s->io('foo', length => 3), 'bar', 'p
 sub stream_daemon {
 	my $server = IO::Socket::INET->new(
 		Proto => 'tcp',
-		LocalAddr => '127.0.0.1:8081',
+		LocalAddr => '127.0.0.1:' . port(1),
 		Listen => 5,
 		Reuse => 1
 	)
--- a/stream_proxy_bind.t
+++ b/stream_proxy_bind.t
@@ -38,9 +38,9 @@ events {
 
 stream {
     server {
-        listen            127.0.0.1:8081;
+        listen            127.0.0.1:%%PORT_1%%;
         proxy_bind        127.0.0.2;
-        proxy_pass        127.0.0.1:8082;
+        proxy_pass        127.0.0.1:%%PORT_2%%;
     }
 }
 
@@ -48,16 +48,16 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen          127.0.0.1:8080;
+        listen          127.0.0.1:%%PORT_0%%;
         server_name     localhost;
 
         location / {
-            proxy_pass  http://127.0.0.1:8081;
+            proxy_pass  http://127.0.0.1:%%PORT_1%%;
         }
     }
 
     server {
-        listen          127.0.0.1:8082;
+        listen          127.0.0.1:%%PORT_2%%;
 
         location / {
             add_header   X-IP $remote_addr;
--- a/stream_proxy_next_upstream.t
+++ b/stream_proxy_next_upstream.t
@@ -36,32 +36,32 @@ events {
 
 stream {
     upstream u {
-        server 127.0.0.1:8087 max_fails=0;
-        server 127.0.0.1:8088 max_fails=0;
-        server 127.0.0.1:8089 backup;
+        server 127.0.0.1:%%PORT_3%% max_fails=0;
+        server 127.0.0.1:%%PORT_4%% max_fails=0;
+        server 127.0.0.1:%%PORT_5%% backup;
     }
 
     upstream u2 {
-        server 127.0.0.1:8087;
-        server 127.0.0.1:8089 backup;
+        server 127.0.0.1:%%PORT_3%%;
+        server 127.0.0.1:%%PORT_5%% backup;
     }
 
     proxy_connect_timeout 1s;
 
     server {
-        listen      127.0.0.1:8081;
+        listen      127.0.0.1:%%PORT_0%%;
         proxy_pass  u;
         proxy_next_upstream off;
     }
 
     server {
-        listen      127.0.0.1:8082;
+        listen      127.0.0.1:%%PORT_1%%;
         proxy_pass  u2;
         proxy_next_upstream on;
     }
 
     server {
-        listen      127.0.0.1:8083;
+        listen      127.0.0.1:%%PORT_2%%;
         proxy_pass  u;
         proxy_next_upstream on;
         proxy_next_upstream_tries 2;
@@ -71,23 +71,23 @@ stream {
 EOF
 
 $t->run_daemon(\&stream_daemon);
-$t->run()->waitforsocket('127.0.0.1:8089');
+$t->run()->waitforsocket('127.0.0.1:' . port(5));
 
 ###############################################################################
 
-is(stream('127.0.0.1:8081')->io('.'), '', 'next off');
-is(stream('127.0.0.1:8082')->io('.'), 'SEE-THIS', 'next on');
+is(stream('127.0.0.1:' . port(0))->io('.'), '', 'next off');
+is(stream('127.0.0.1:' . port(1))->io('.'), 'SEE-THIS', 'next on');
 
 # make sure backup is not tried
 
-is(stream('127.0.0.1:8083')->io('.'), '', 'next tries');
+is(stream('127.0.0.1:' . port(2))->io('.'), '', 'next tries');
 
 ###############################################################################
 
 sub stream_daemon {
 	my $server = IO::Socket::INET->new(
 		Proto => 'tcp',
-		LocalHost => '127.0.0.1:8089',
+		LocalHost => '127.0.0.1:' . port(5),
 		Listen => 5,
 		Reuse => 1
 	)
--- a/stream_proxy_protocol.t
+++ b/stream_proxy_protocol.t
@@ -40,13 +40,13 @@ stream {
     proxy_protocol on;
 
     server {
-        listen          127.0.0.1:8080;
-        proxy_pass      127.0.0.1:8081;
+        listen          127.0.0.1:%%PORT_0%%;
+        proxy_pass      127.0.0.1:%%PORT_1%%;
     }
 
     server {
-        listen          127.0.0.1:8082;
-        proxy_pass      127.0.0.1:8081;
+        listen          127.0.0.1:%%PORT_2%%;
+        proxy_pass      127.0.0.1:%%PORT_1%%;
         proxy_protocol  off;
     }
 }
@@ -55,23 +55,24 @@ EOF
 
 $t->run_daemon(\&stream_daemon);
 $t->try_run('no stream proxy_protocol')->plan(2);
-$t->waitforsocket('127.0.0.1:8081');
+$t->waitforsocket('127.0.0.1:' . port(1));
 
 ###############################################################################
 
-my $s = stream();
+my $dp = port(0);
+my $s = stream('127.0.0.1:' . $dp);
 my $data = $s->io('close');
 my $sp = $s->sockport();
-is($data, "PROXY TCP4 127.0.0.1 127.0.0.1 $sp 8080${CRLF}close", 'protocol on');
+is($data, "PROXY TCP4 127.0.0.1 127.0.0.1 $sp $dp${CRLF}close", 'protocol on');
 
-is(stream('127.0.0.1:8082')->io('close'), 'close', 'protocol off');
+is(stream('127.0.0.1:' . port(2))->io('close'), 'close', 'protocol off');
 
 ###############################################################################
 
 sub stream_daemon {
 	my $server = IO::Socket::INET->new(
 		Proto => 'tcp',
-		LocalAddr => '127.0.0.1:8081',
+		LocalAddr => '127.0.0.1:' . port(1),
 		Listen => 5,
 		Reuse => 1
 	)
--- a/stream_proxy_protocol_ipv6.t
+++ b/stream_proxy_protocol_ipv6.t
@@ -38,24 +38,24 @@ events {
 
 stream {
     server {
-        listen          127.0.0.1:8080;
-        proxy_pass      [::1]:8080;
+        listen          127.0.0.1:%%PORT_0%%;
+        proxy_pass      [::1]:%%PORT_0%%;
     }
 
     server {
-        listen          127.0.0.1:8081;
-        proxy_pass      [::1]:8081;
+        listen          127.0.0.1:%%PORT_1%%;
+        proxy_pass      [::1]:%%PORT_1%%;
     }
 
     server {
-        listen          [::1]:8080;
-        proxy_pass      127.0.0.1:8082;
+        listen          [::1]:%%PORT_0%%;
+        proxy_pass      127.0.0.1:%%PORT_2%%;
         proxy_protocol  on;
     }
 
     server {
-        listen          [::1]:8081;
-        proxy_pass      127.0.0.1:8082;
+        listen          [::1]:%%PORT_1%%;
+        proxy_pass      127.0.0.1:%%PORT_2%%;
     }
 }
 
@@ -63,20 +63,23 @@ EOF
 
 $t->run_daemon(\&stream_daemon);
 $t->try_run('no inet6 support or stream proxy_protocol')->plan(2);
-$t->waitforsocket('127.0.0.1:8082');
+$t->waitforsocket('127.0.0.1:' . port(2));
 
 ###############################################################################
 
-like(stream()->io('close'), qr/PROXY TCP6 ::1 ::1 \d+ 8080$CRLF/,
-	'protocol on');
-unlike(stream('127.0.0.1:8081')->io('close'), qr/PROXY/, 'protocol off');
+my $dp = port(0);
+
+like(stream('127.0.0.1:' . $dp)->io('close'),
+	qr/PROXY TCP6 ::1 ::1 \d+ $dp$CRLF/, 'protocol on');
+unlike(stream('127.0.0.1:' . port(1))->io('close'), qr/PROXY/,
+	'protocol off');
 
 ###############################################################################
 
 sub stream_daemon {
 	my $server = IO::Socket::INET->new(
 		Proto => 'tcp',
-		LocalHost => '127.0.0.1:8082',
+		LocalHost => '127.0.0.1:' . port(2),
 		Listen => 5,
 		Reuse => 1
 	)
--- a/stream_proxy_protocol_ssl.t
+++ b/stream_proxy_protocol_ssl.t
@@ -43,13 +43,13 @@ stream {
     proxy_protocol  on;
 
     server {
-        listen          127.0.0.1:8080;
-        proxy_pass      127.0.0.1:8081;
+        listen          127.0.0.1:%%PORT_0%%;
+        proxy_pass      127.0.0.1:%%PORT_1%%;
     }
 
     server {
-        listen          127.0.0.1:8082;
-        proxy_pass      127.0.0.1:8083;
+        listen          127.0.0.1:%%PORT_2%%;
+        proxy_pass      127.0.0.1:%%PORT_3%%;
         proxy_protocol  off;
     }
 }
@@ -74,20 +74,22 @@ foreach my $name ('localhost') {
 		or die "Can't create certificate for $name: $!\n";
 }
 
-$t->run_daemon(\&stream_daemon_ssl, 8081, path => $d, pp => 1);
-$t->run_daemon(\&stream_daemon_ssl, 8083, path => $d, pp => 0);
+$t->run_daemon(\&stream_daemon_ssl, port(1), path => $d, pp => 1);
+$t->run_daemon(\&stream_daemon_ssl, port(3), path => $d, pp => 0);
 $t->try_run('no stream proxy_protocol')->plan(2);
 
-$t->waitforsocket('127.0.0.1:8081');
-$t->waitforsocket('127.0.0.1:8083');
+$t->waitforsocket('127.0.0.1:' . port(1));
+$t->waitforsocket('127.0.0.1:' . port(3));
 
 ###############################################################################
 
-my %r = pp_get('test');
-is($r{'data'}, "PROXY TCP4 127.0.0.1 127.0.0.1 $r{'sp'} 8080" . CRLF . 'test',
+my $dp = port(0);
+
+my %r = pp_get('test', '127.0.0.1:' . $dp);
+is($r{'data'}, "PROXY TCP4 127.0.0.1 127.0.0.1 $r{'sp'} $dp" . CRLF . 'test',
 	'protocol on');
 
-%r = pp_get('test', '127.0.0.1:8082');
+%r = pp_get('test', '127.0.0.1:' . port(2));
 is($r{'data'}, 'test', 'protocol off');
 
 ###############################################################################
@@ -105,7 +107,7 @@ sub getconn {
 	my $peer = shift;
 	my $s = IO::Socket::INET->new(
 		Proto => 'tcp',
-		PeerAddr => $peer || '127.0.0.1:8080'
+		PeerAddr => $peer
 	)
 		or die "Can't connect to nginx: $!\n";
 
--- a/stream_proxy_ssl.t
+++ b/stream_proxy_ssl.t
@@ -40,14 +40,14 @@ stream {
     proxy_connect_timeout 2s;
 
     server {
-        listen      127.0.0.1:8080;
-        proxy_pass  127.0.0.1:8087;
+        listen      127.0.0.1:%%PORT_0%%;
+        proxy_pass  127.0.0.1:%%PORT_2%%;
         proxy_ssl_session_reuse off;
     }
 
     server {
-        listen      127.0.0.1:8081;
-        proxy_pass  127.0.0.1:8087;
+        listen      127.0.0.1:%%PORT_1%%;
+        proxy_pass  127.0.0.1:%%PORT_2%%;
     }
 }
 
@@ -55,7 +55,7 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen       127.0.0.1:8087 ssl;
+        listen       127.0.0.1:%%PORT_2%% ssl;
         server_name  localhost;
 
         ssl_certificate_key localhost.key;
@@ -94,14 +94,12 @@ foreach my $name ('localhost') {
 
 ###############################################################################
 
-like(http_get('/', socket => getconn('127.0.0.1:8080')),
-	qr/200 OK.*X-Session: \./s, 'ssl');
-like(http_get('/', socket => getconn('127.0.0.1:8081')),
+like(http_get('/'), qr/200 OK.*X-Session: \./s, 'ssl');
+like(http_get('/', socket => getconn('127.0.0.1:' . port(1))),
 	qr/200 OK.*X-Session: \./s, 'ssl 2');
 
-like(http_get('/', socket => getconn('127.0.0.1:8080')),
-	qr/200 OK.*X-Session: \./s, 'ssl reuse session');
-like(http_get('/', socket => getconn('127.0.0.1:8081')),
+like(http_get('/'), qr/200 OK.*X-Session: \./s, 'ssl reuse session');
+like(http_get('/', socket => getconn('127.0.0.1:' . port(1))),
 	qr/200 OK.*X-Session: r/s, 'ssl reuse session 2');
 
 my $s = http('', start => 1);
@@ -116,7 +114,7 @@ sub getconn {
 	my $peer = shift;
 	my $s = IO::Socket::INET->new(
 		Proto => 'tcp',
-		PeerAddr => $peer || '127.0.0.1:8080'
+		PeerAddr => $peer
 	)
 		or die "Can't connect to nginx: $!\n";
 
--- a/stream_proxy_ssl_certificate.t
+++ b/stream_proxy_ssl_certificate.t
@@ -40,24 +40,24 @@ stream {
     proxy_ssl_session_reuse off;
 
     server {
-        listen      127.0.0.1:8083;
-        proxy_pass  127.0.0.1:8081;
+        listen      127.0.0.1:%%PORT_2%%;
+        proxy_pass  127.0.0.1:%%PORT_0%%;
 
         proxy_ssl_certificate 1.example.com.crt;
         proxy_ssl_certificate_key 1.example.com.key;
     }
 
     server {
-        listen      127.0.0.1:8084;
-        proxy_pass  127.0.0.1:8081;
+        listen      127.0.0.1:%%PORT_3%%;
+        proxy_pass  127.0.0.1:%%PORT_0%%;
 
         proxy_ssl_certificate 2.example.com.crt;
         proxy_ssl_certificate_key 2.example.com.key;
     }
 
     server {
-        listen      127.0.0.1:8085;
-        proxy_pass  127.0.0.1:8082;
+        listen      127.0.0.1:%%PORT_4%%;
+        proxy_pass  127.0.0.1:%%PORT_1%%;
 
         proxy_ssl_certificate 3.example.com.crt;
         proxy_ssl_certificate_key 3.example.com.key;
@@ -69,7 +69,7 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen       127.0.0.1:8081 ssl;
+        listen       127.0.0.1:%%PORT_0%% ssl;
         server_name  localhost;
 
         ssl_certificate 2.example.com.crt;
@@ -85,7 +85,7 @@ http {
     }
 
     server {
-        listen       127.0.0.1:8082 ssl;
+        listen       127.0.0.1:%%PORT_1%% ssl;
         server_name  localhost;
 
         ssl_certificate 1.example.com.crt;
@@ -139,16 +139,16 @@ foreach my $name ('3.example.com') {
 
 ###############################################################################
 
-like(http_get('/', socket => getconn('127.0.0.1:8083')),
+like(http_get('/', socket => getconn('127.0.0.1:' . port(2))),
 	qr/X-Verify: SUCCESS/ms, 'verify certificate');
-like(http_get('/', socket => getconn('127.0.0.1:8084')),
+like(http_get('/', socket => getconn('127.0.0.1:' . port(3))),
 	qr/X-Verify: FAILED/ms, 'fail certificate');
-like(http_get('/', socket => getconn('127.0.0.1:8085')),
+like(http_get('/', socket => getconn('127.0.0.1:' . port(4))),
 	qr/X-Verify: SUCCESS/ms, 'with encrypted key');
 
-like(http_get('/', socket => getconn('127.0.0.1:8083')),
+like(http_get('/', socket => getconn('127.0.0.1:' . port(2))),
 	qr!X-Name: /CN=1.example!, 'valid certificate');
-unlike(http_get('/', socket => getconn('127.0.0.1:8084')),
+unlike(http_get('/', socket => getconn('127.0.0.1:' . port(3))),
 	qr!X-Name: /CN=1.example!, 'invalid certificate');
 
 ###############################################################################
@@ -157,7 +157,7 @@ sub getconn {
 	my $peer = shift;
 	my $s = IO::Socket::INET->new(
 		Proto => 'tcp',
-		PeerAddr => $peer || '127.0.0.1:8080'
+		PeerAddr => $peer
 	)
 		or die "Can't connect to nginx: $!\n";
 
--- a/stream_proxy_ssl_name.t
+++ b/stream_proxy_ssl_name.t
@@ -40,41 +40,41 @@ stream {
     proxy_ssl_session_reuse off;
 
     upstream u {
-        server 127.0.0.1:8086;
+        server 127.0.0.1:%%PORT_5%%;
     }
 
     server {
-        listen      127.0.0.1:8080;
+        listen      127.0.0.1:%%PORT_0%%;
         proxy_pass  u;
 
         proxy_ssl_server_name off;
     }
 
     server {
-        listen      127.0.0.1:8081;
+        listen      127.0.0.1:%%PORT_1%%;
         proxy_pass  u;
 
         proxy_ssl_server_name on;
     }
 
     server {
-        listen      127.0.0.1:8082;
-        proxy_pass  127.0.0.1:8086;
+        listen      127.0.0.1:%%PORT_2%%;
+        proxy_pass  127.0.0.1:%%PORT_5%%;
 
         proxy_ssl_server_name on;
         proxy_ssl_name example.com;
     }
 
     server {
-        listen      127.0.0.1:8083;
-        proxy_pass  127.0.0.1:8086;
+        listen      127.0.0.1:%%PORT_3%%;
+        proxy_pass  127.0.0.1:%%PORT_5%%;
 
         proxy_ssl_server_name on;
     }
 
     server {
-        listen      127.0.0.1:8084;
-        proxy_pass  127.0.0.1:8086;
+        listen      127.0.0.1:%%PORT_4%%;
+        proxy_pass  127.0.0.1:%%PORT_5%%;
 
         proxy_ssl_server_name on;
         proxy_ssl_name example.com:123;
@@ -85,7 +85,7 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen       127.0.0.1:8086 ssl;
+        listen       127.0.0.1:%%PORT_5%% ssl;
         server_name  localhost;
 
         ssl_certificate_key localhost.key;
@@ -123,15 +123,14 @@ foreach my $name ('localhost') {
 
 ###############################################################################
 
-like(http_get('/', socket => getconn('127.0.0.1:8080')),
-	qr/200 OK.*X-Name: ,/s, 'no name');
-like(http_get('/', socket => getconn('127.0.0.1:8081')),
+like(http_get('/'), qr/200 OK.*X-Name: ,/s, 'no name');
+like(http_get('/', socket => getconn('127.0.0.1:' . port(1))),
 	qr/200 OK.*X-Name: u,/s, 'name default');
-like(http_get('/', socket => getconn('127.0.0.1:8082')),
+like(http_get('/', socket => getconn('127.0.0.1:' . port(2))),
 	qr/200 OK.*X-Name: example.com,/s, 'name override');
-like(http_get('/', socket => getconn('127.0.0.1:8083')),
+like(http_get('/', socket => getconn('127.0.0.1:' . port(3))),
 	qr/200 OK.*X-Name: ,/s, 'no ip');
-like(http_get('/', socket => getconn('127.0.0.1:8084')),
+like(http_get('/', socket => getconn('127.0.0.1:' . port(4))),
 	qr/200 OK.*X-Name: example.com,/s, 'no port in name');
 
 ###############################################################################
@@ -140,7 +139,7 @@ sub getconn {
 	my $peer = shift;
 	my $s = IO::Socket::INET->new(
 		Proto => 'tcp',
-		PeerAddr => $peer || '127.0.0.1:8080'
+		PeerAddr => $peer
 	)
 		or die "Can't connect to nginx: $!\n";
 
--- a/stream_proxy_ssl_verify.t
+++ b/stream_proxy_ssl_verify.t
@@ -38,56 +38,56 @@ stream {
     proxy_ssl_verify on;
 
     server {
-        listen      127.0.0.1:8080;
-        proxy_pass  127.0.0.1:8087;
+        listen      127.0.0.1:%%PORT_0%%;
+        proxy_pass  127.0.0.1:%%PORT_6%%;
 
         proxy_ssl_name example.com;
         proxy_ssl_trusted_certificate 1.example.com.crt;
     }
 
     server {
-        listen      127.0.0.1:8081;
-        proxy_pass  127.0.0.1:8087;
+        listen      127.0.0.1:%%PORT_1%%;
+        proxy_pass  127.0.0.1:%%PORT_6%%;
 
         proxy_ssl_name foo.example.com;
         proxy_ssl_trusted_certificate 1.example.com.crt;
     }
 
     server {
-        listen      127.0.0.1:8082;
-        proxy_pass  127.0.0.1:8087;
+        listen      127.0.0.1:%%PORT_2%%;
+        proxy_pass  127.0.0.1:%%PORT_6%%;
 
         proxy_ssl_name no.match.example.com;
         proxy_ssl_trusted_certificate 1.example.com.crt;
     }
 
     server {
-        listen      127.0.0.1:8083;
-        proxy_pass  127.0.0.1:8088;
+        listen      127.0.0.1:%%PORT_3%%;
+        proxy_pass  127.0.0.1:%%PORT_7%%;
 
         proxy_ssl_name 2.example.com;
         proxy_ssl_trusted_certificate 2.example.com.crt;
     }
 
     server {
-        listen      127.0.0.1:8084;
-        proxy_pass  127.0.0.1:8088;
+        listen      127.0.0.1:%%PORT_4%%;
+        proxy_pass  127.0.0.1:%%PORT_7%%;
 
         proxy_ssl_name bad.example.com;
         proxy_ssl_trusted_certificate 2.example.com.crt;
     }
 
     server {
-        listen      127.0.0.1:8085;
-        proxy_pass  127.0.0.1:8088;
+        listen      127.0.0.1:%%PORT_5%%;
+        proxy_pass  127.0.0.1:%%PORT_7%%;
 
         proxy_ssl_trusted_certificate 1.example.com.crt;
         proxy_ssl_session_reuse off;
     }
 
     server {
-        listen      127.0.0.1:8087 ssl;
-        proxy_pass  127.0.0.1:8089;
+        listen      127.0.0.1:%%PORT_6%% ssl;
+        proxy_pass  127.0.0.1:%%PORT_8%%;
         proxy_ssl   off;
 
         ssl_certificate 1.example.com.crt;
@@ -95,8 +95,8 @@ stream {
     }
 
     server {
-        listen      127.0.0.1:8088 ssl;
-        proxy_pass  127.0.0.1:8089;
+        listen      127.0.0.1:%%PORT_7%% ssl;
+        proxy_pass  127.0.0.1:%%PORT_8%%;
         proxy_ssl   off;
 
         ssl_certificate 2.example.com.crt;
@@ -147,24 +147,24 @@ foreach my $name ('1.example.com', '2.ex
 $t->run_daemon(\&http_daemon);
 $t->run();
 
-$t->waitforsocket('127.0.0.1:8089');
+$t->waitforsocket('127.0.0.1:' . port(8));
 
 ###############################################################################
 
 # subjectAltName
 
-like(get('/', '127.0.0.1:8080'), qr/200 OK/, 'verify');
-like(get('/', '127.0.0.1:8081'), qr/200 OK/, 'verify wildcard');
-unlike(get('/', '127.0.0.1:8082'), qr/200 OK/, 'verify fail');
+like(get('/', '127.0.0.1:' . port(0)), qr/200 OK/, 'verify');
+like(get('/', '127.0.0.1:' . port(1)), qr/200 OK/, 'verify wildcard');
+unlike(get('/', '127.0.0.1:' . port(2)), qr/200 OK/, 'verify fail');
 
 # commonName
 
-like(get('/', '127.0.0.1:8083'), qr/200 OK/, 'verify cn');
-unlike(get('/', '127.0.0.1:8084'), qr/200 OK/, 'verify cn fail');
+like(get('/', '127.0.0.1:' . port(3)), qr/200 OK/, 'verify cn');
+unlike(get('/', '127.0.0.1:' . port(4)), qr/200 OK/, 'verify cn fail');
 
 # untrusted
 
-unlike(get('/', '127.0.0.1:8085'), qr/200 OK/, 'untrusted');
+unlike(get('/', '127.0.0.1:' . port(5)), qr/200 OK/, 'untrusted');
 
 ###############################################################################
 
@@ -186,7 +186,7 @@ sub get {
 sub http_daemon {
 	my $server = IO::Socket::INET->new(
 		Proto => 'tcp',
-		LocalHost => '127.0.0.1:8089',
+		LocalHost => '127.0.0.1:' . port(8),
 		Listen => 5,
 		Reuse => 1
 	)
--- a/stream_ssl.t
+++ b/stream_ssl.t
@@ -53,32 +53,32 @@ stream {
     ssl_password_file password_http;
 
     server {
-        listen      127.0.0.1:8080 ssl;
-        proxy_pass  127.0.0.1:8081;
+        listen      127.0.0.1:%%PORT_0%% ssl;
+        proxy_pass  127.0.0.1:%%PORT_1%%;
 
         ssl_session_cache builtin;
         ssl_password_file password;
     }
 
     server {
-        listen      127.0.0.1:8082 ssl;
-        proxy_pass  127.0.0.1:8081;
+        listen      127.0.0.1:%%PORT_2%% ssl;
+        proxy_pass  127.0.0.1:%%PORT_1%%;
 
         ssl_session_cache off;
         ssl_password_file password_many;
     }
 
     server {
-        listen      127.0.0.1:8083 ssl;
-        proxy_pass  127.0.0.1:8081;
+        listen      127.0.0.1:%%PORT_3%% ssl;
+        proxy_pass  127.0.0.1:%%PORT_1%%;
 
         ssl_session_cache builtin:1000;
         ssl_password_file password_fifo;
     }
 
     server {
-        listen      127.0.0.1:8084 ssl;
-        proxy_pass  127.0.0.1:8081;
+        listen      127.0.0.1:%%PORT_4%% ssl;
+        proxy_pass  127.0.0.1:%%PORT_1%%;
 
         ssl_session_cache shared:SSL:1m;
         ssl_certificate_key inherits.key;
@@ -123,48 +123,48 @@ fork() || exec("echo localhost > $d/pass
 $t->run_daemon(\&http_daemon);
 $t->run();
 
-$t->waitforsocket('127.0.0.1:8081');
+$t->waitforsocket('127.0.0.1:' . port(1));
 
 ###############################################################################
 
 my ($s, $ssl, $ses);
 
-($s, $ssl) = get_ssl_socket(8080);
+($s, $ssl) = get_ssl_socket(port(0));
 Net::SSLeay::write($ssl, "GET / HTTP/1.0$CRLF$CRLF");
 like(Net::SSLeay::read($ssl), qr/200 OK/, 'ssl');
 
 # ssl_session_cache
 
-($s, $ssl) = get_ssl_socket(8080);
+($s, $ssl) = get_ssl_socket(port(0));
 $ses = Net::SSLeay::get_session($ssl);
 
-($s, $ssl) = get_ssl_socket(8080, $ses);
+($s, $ssl) = get_ssl_socket(port(0), $ses);
 is(Net::SSLeay::session_reused($ssl), 1, 'builtin session reused');
 
-($s, $ssl) = get_ssl_socket(8082);
+($s, $ssl) = get_ssl_socket(port(2));
 $ses = Net::SSLeay::get_session($ssl);
 
-($s, $ssl) = get_ssl_socket(8082, $ses);
+($s, $ssl) = get_ssl_socket(port(2), $ses);
 isnt(Net::SSLeay::session_reused($ssl), 1, 'session not reused');
 
-($s, $ssl) = get_ssl_socket(8083);
+($s, $ssl) = get_ssl_socket(port(3));
 $ses = Net::SSLeay::get_session($ssl);
 
-($s, $ssl) = get_ssl_socket(8083, $ses);
+($s, $ssl) = get_ssl_socket(port(3), $ses);
 is(Net::SSLeay::session_reused($ssl), 1, 'builtin size session reused');
 
-($s, $ssl) = get_ssl_socket(8084);
+($s, $ssl) = get_ssl_socket(port(4));
 $ses = Net::SSLeay::get_session($ssl);
 
-($s, $ssl) = get_ssl_socket(8084, $ses);
+($s, $ssl) = get_ssl_socket(port(4), $ses);
 is(Net::SSLeay::session_reused($ssl), 1, 'shared session reused');
 
 # ssl_certificate inheritance
 
-($s, $ssl) = get_ssl_socket(8080);
+($s, $ssl) = get_ssl_socket(port(0));
 like(Net::SSLeay::dump_peer_certificate($ssl), qr/CN=localhost/, 'CN');
 
-($s, $ssl) = get_ssl_socket(8084);
+($s, $ssl) = get_ssl_socket(port(4));
 like(Net::SSLeay::dump_peer_certificate($ssl), qr/CN=inherits/, 'CN inner');
 
 ###############################################################################
@@ -174,7 +174,7 @@ sub get_ssl_socket {
 	my $s;
 
 	my $dest_ip = inet_aton('127.0.0.1');
-	my $dest_serv_params = sockaddr_in($port || 8080, $dest_ip);
+	my $dest_serv_params = sockaddr_in($port, $dest_ip);
 
 	socket($s, &AF_INET, &SOCK_STREAM, 0) or die "socket: $!";
 	connect($s, $dest_serv_params) or die "connect: $!";
@@ -191,7 +191,7 @@ sub get_ssl_socket {
 sub http_daemon {
 	my $server = IO::Socket::INET->new(
 		Proto => 'tcp',
-		LocalHost => '127.0.0.1:8081',
+		LocalHost => '127.0.0.1:' . port(1),
 		Listen => 5,
 		Reuse => 1
 	)
--- a/stream_tcp_nodelay.t
+++ b/stream_tcp_nodelay.t
@@ -44,30 +44,30 @@ stream {
     tcp_nodelay off;
 
     server {
-        listen      127.0.0.1:8081;
-        proxy_pass  127.0.0.1:8080;
+        listen      127.0.0.1:%%PORT_1%%;
+        proxy_pass  127.0.0.1:%%PORT_0%%;
     }
 
     server {
         tcp_nodelay on;
-        listen      127.0.0.1:8082;
-        proxy_pass  127.0.0.1:8080;
+        listen      127.0.0.1:%%PORT_2%%;
+        proxy_pass  127.0.0.1:%%PORT_0%%;
     }
 }
 
 EOF
 
 $t->run_daemon(\&stream_daemon);
-$t->run()->waitforsocket('127.0.0.1:8080');
+$t->run()->waitforsocket('127.0.0.1:' . port(0));
 
 ###############################################################################
 
 my $str = '1234567890' x 10 . 'F';
 my $length = length($str);
 
-is(stream('127.0.0.1:8081')->io($str, length => $length), $str,
+is(stream('127.0.0.1:' . port(1))->io($str, length => $length), $str,
 	'tcp_nodelay off');
-is(stream('127.0.0.1:8082')->io($str, length => $length), $str,
+is(stream('127.0.0.1:' . port(2))->io($str, length => $length), $str,
 	'tcp_nodelay on');
 
 ###############################################################################
@@ -75,7 +75,7 @@ is(stream('127.0.0.1:8082')->io($str, le
 sub stream_daemon {
 	my $server = IO::Socket::INET->new(
 		Proto => 'tcp',
-		LocalAddr => '127.0.0.1:8080',
+		LocalAddr => '127.0.0.1:' . port(0),
 		Listen => 5,
 		Reuse => 1
 	)
--- a/stream_udp_limit_conn.t
+++ b/stream_udp_limit_conn.t
@@ -41,34 +41,34 @@ stream {
     proxy_timeout    1s;
 
     server {
-        listen           127.0.0.1:8081 udp;
-        proxy_pass       127.0.0.1:8080;
+        listen           127.0.0.1:%%PORT_1_UDP%% udp;
+        proxy_pass       127.0.0.1:%%PORT_0_UDP%%;
 
         limit_conn       zone 1;
         proxy_responses  2;
     }
 
     server {
-        listen           127.0.0.1:8082 udp;
-        proxy_pass       127.0.0.1:8080;
+        listen           127.0.0.1:%%PORT_2_UDP%% udp;
+        proxy_pass       127.0.0.1:%%PORT_0_UDP%%;
         limit_conn       zone2 1;
     }
 
     server {
-        listen           127.0.0.1:8083 udp;
-        proxy_pass       127.0.0.1:8080;
+        listen           127.0.0.1:%%PORT_3_UDP%% udp;
+        proxy_pass       127.0.0.1:%%PORT_0_UDP%%;
         limit_conn       zone 5;
     }
 
     server {
-        listen           127.0.0.1:8084 udp;
-        proxy_pass       127.0.0.1:8081;
+        listen           127.0.0.1:%%PORT_4_UDP%% udp;
+        proxy_pass       127.0.0.1:%%PORT_1_UDP%%;
         limit_conn       zone2 1;
     }
 
     server {
-        listen           127.0.0.1:8085 udp;
-        proxy_pass       127.0.0.1:8081;
+        listen           127.0.0.1:%%PORT_5_UDP%% udp;
+        proxy_pass       127.0.0.1:%%PORT_1_UDP%%;
         limit_conn       zone 1;
     }
 }
@@ -77,13 +77,13 @@ EOF
 
 $t->try_run('no stream udp')->plan(9);
 $t->run_daemon(\&udp_daemon, $t);
-$t->waitforfile($t->testdir . '/8080');
+$t->waitforfile($t->testdir . '/' . port(0));
 
 ###############################################################################
 
 # same and other zones
 
-my $s = dgram('127.0.0.1:8081');
+my $s = dgram('127.0.0.1:' . port(1));
 
 is($s->io('1'), '1', 'passed');
 
@@ -91,21 +91,21 @@ is($s->io('1'), '1', 'passed');
 # in same socket will be treated as new connection
 
 is($s->io('1', read_timeout => 0.1), '', 'rejected new connection');
-is(dgram('127.0.0.1:8081')->io('1', read_timeout => 0.1), '',
+is(dgram('127.0.0.1:' . port(1))->io('1', read_timeout => 0.1), '',
 	'rejected same zone');
-is(dgram('127.0.0.1:8082')->io('1'), '1', 'passed different zone');
-is(dgram('127.0.0.1:8083')->io('1'), '1', 'passed same zone unlimited');
+is(dgram('127.0.0.1:' . port(2))->io('1'), '1', 'passed different zone');
+is(dgram('127.0.0.1:' . port(3))->io('1'), '1', 'passed same zone unlimited');
 
 sleep 1;	# waiting for proxy_timeout to expire
 
 is($s->io('2', read => 2), '12', 'new connection after proxy_timeout');
 
-is(dgram('127.0.0.1:8081')->io('2', read => 2), '12', 'passed 2');
+is(dgram('127.0.0.1:' . port(1))->io('2', read => 2), '12', 'passed 2');
 
 # zones proxy chain
 
-is(dgram('127.0.0.1:8084')->io('1'), '1', 'passed proxy');
-is(dgram('127.0.0.1:8085')->io('1', read_timeout => 0.1), '',
+is(dgram('127.0.0.1:' . port(4))->io('1'), '1', 'passed proxy');
+is(dgram('127.0.0.1:' . port(5))->io('1', read_timeout => 0.1), '',
 	'rejected proxy');
 
 ###############################################################################
@@ -115,14 +115,14 @@ sub udp_daemon {
 
 	my $server = IO::Socket::INET->new(
 		Proto => 'udp',
-		LocalAddr => '127.0.0.1:8080',
+		LocalAddr => '127.0.0.1:' . port(0),
 		Reuse => 1,
 	)
 		or die "Can't create listening socket: $!\n";
 
 	# signal we are ready
 
-	open my $fh, '>', $t->testdir() . '/8080';
+	open my $fh, '>', $t->testdir() . '/' . port(0);
 	close $fh;
 
 	while (1) {
--- a/stream_udp_proxy.t
+++ b/stream_udp_proxy.t
@@ -36,43 +36,43 @@ stream {
     proxy_timeout        1s;
 
     server {
-        listen           127.0.0.1:8080 udp;
-        proxy_pass       127.0.0.1:8081;
+        listen           127.0.0.1:%%PORT_0_UDP%% udp;
+        proxy_pass       127.0.0.1:%%PORT_1_UDP%%;
 
         proxy_responses  0;
     }
 
     server {
-        listen           127.0.0.1:8082 udp;
-        proxy_pass       127.0.0.1:8081;
+        listen           127.0.0.1:%%PORT_2_UDP%% udp;
+        proxy_pass       127.0.0.1:%%PORT_1_UDP%%;
 
         proxy_responses  2;
     }
 
     server {
-        listen           127.0.0.1:8083 udp;
-        proxy_pass       127.0.0.1:8081;
+        listen           127.0.0.1:%%PORT_3_UDP%% udp;
+        proxy_pass       127.0.0.1:%%PORT_1_UDP%%;
     }
 }
 
 EOF
 
 
-$t->run_daemon(\&udp_daemon, 8081, $t);
+$t->run_daemon(\&udp_daemon, port(1), $t);
 $t->try_run('no stream udp')->plan(5);
-$t->waitforfile($t->testdir . '/8081');
+$t->waitforfile($t->testdir . '/' . port(1));
 
 ###############################################################################
 
-my $s = dgram('127.0.0.1:8080');
+my $s = dgram('127.0.0.1:' . port(0));
 is($s->io('1', read => 1, read_timeout => 0.5), '', 'proxy responses 0');
 
-$s = dgram('127.0.0.1:8082');
+$s = dgram('127.0.0.1:' . port(2));
 is($s->io('1'), '1', 'proxy responses 1');
 is($s->io('2', read => 2), '12', 'proxy responses 2');
 is($s->io('3', read => 3, read_timeout => 0.5), '12', 'proxy responses 3');
 
-$s = dgram('127.0.0.1:8083');
+$s = dgram('127.0.0.1:' . port(3));
 is($s->io('3', read => 3), '123', 'proxy responses default');
 
 ###############################################################################
@@ -82,14 +82,14 @@ sub udp_daemon {
 
 	my $server = IO::Socket::INET->new(
 		Proto => 'udp',
-		LocalAddr => "127.0.0.1:$port",
+		LocalAddr => '127.0.0.1:' . port(1),
 		Reuse => 1,
 	)
 		or die "Can't create listening socket: $!\n";
 
 	# signal we are ready
 
-	open my $fh, '>', $t->testdir() . '/' . $port;
+	open my $fh, '>', $t->testdir() . '/' . port(1);
 	close $fh;
 
 	while (1) {
--- a/stream_udp_upstream.t
+++ b/stream_udp_upstream.t
@@ -38,80 +38,81 @@ stream {
     proxy_timeout        1s;
 
     upstream u {
-        server 127.0.0.1:8087;
-        server 127.0.0.1:8088;
+        server 127.0.0.1:%%PORT_4_UDP%%;
+        server 127.0.0.1:%%PORT_5_UDP%%;
     }
 
     upstream u2 {
-        server 127.0.0.1:8089 down;
-        server 127.0.0.1:8089;
-        server 127.0.0.1:8087;
-        server 127.0.0.1:8088;
+        server 127.0.0.1:%%PORT_6_UDP%% down;
+        server 127.0.0.1:%%PORT_6_UDP%%;
+        server 127.0.0.1:%%PORT_4_UDP%%;
+        server 127.0.0.1:%%PORT_5_UDP%%;
     }
 
     upstream u3 {
-        server 127.0.0.1:8087;
-        server 127.0.0.1:8088 weight=2;
+        server 127.0.0.1:%%PORT_4_UDP%%;
+        server 127.0.0.1:%%PORT_5_UDP%% weight=2;
     }
 
     upstream u4 {
-        server 127.0.0.1:8089;
-        server 127.0.0.1:8087 backup;
+        server 127.0.0.1:%%PORT_6_UDP%%;
+        server 127.0.0.1:%%PORT_4_UDP%% backup;
     }
 
     server {
-        listen      127.0.0.1:8081 udp;
+        listen      127.0.0.1:%%PORT_0_UDP%% udp;
         proxy_pass  u;
     }
 
     server {
-        listen      127.0.0.1:8082 udp;
+        listen      127.0.0.1:%%PORT_1_UDP%% udp;
         proxy_pass  u2;
     }
 
     server {
-        listen      127.0.0.1:8083 udp;
+        listen      127.0.0.1:%%PORT_2_UDP%% udp;
         proxy_pass  u3;
     }
 
     server {
-        listen      127.0.0.1:8084 udp;
+        listen      127.0.0.1:%%PORT_3_UDP%% udp;
         proxy_pass  u4;
     }
 }
 
 EOF
 
-$t->run_daemon(\&udp_daemon, 8087, $t);
-$t->run_daemon(\&udp_daemon, 8088, $t);
+$t->run_daemon(\&udp_daemon, port(4), $t);
+$t->run_daemon(\&udp_daemon, port(5), $t);
 $t->try_run('no stream udp')->plan(4);
 
-$t->waitforfile($t->testdir . '/8087');
-$t->waitforfile($t->testdir . '/8088');
+$t->waitforfile($t->testdir . '/' . port(4));
+$t->waitforfile($t->testdir . '/' . port(5));
 
 ###############################################################################
 
-is(many('.', 30, peer => '127.0.0.1:8081'), '8087: 15, 8088: 15', 'balanced');
-is(many('.', 30, peer => '127.0.0.1:8082'), '8087: 15, 8088: 15', 'failures');
-is(many('.', 30, peer => '127.0.0.1:8083'), '8087: 10, 8088: 20', 'weight');
-is(many('.', 30, peer => '127.0.0.1:8084'), '8087: 30', 'backup');
+my @ports = my ($port4, $port5) = (port(4), port(5));
+
+is(many(30, port(0)), "$port4: 15, $port5: 15", 'balanced');
+is(many(30, port(1)), "$port4: 15, $port5: 15", 'failures');
+is(many(30, port(2)), "$port4: 10, $port5: 20", 'weight');
+is(many(30, port(3)), "$port4: 30", 'backup');
 
 ###############################################################################
 
 sub many {
-	my ($data, $count, %opts) = @_;
-	my (%ports, $peer);
-
-	$peer = $opts{peer};
+	my ($count, $port) = @_;
+	my (%ports);
 
 	for (1 .. $count) {
-		if (dgram($peer)->io($data) =~ /(\d+)/) {
+		if (dgram("127.0.0.1:$port")->io('.') =~ /(\d+)/) {
 			$ports{$1} = 0 unless defined $ports{$1};
 			$ports{$1}++;
 		}
 	}
 
-	return join ', ', map { $_ . ": " . $ports{$_} } sort keys %ports;
+	my @keys = map { my $p = $_; grep { $p == $_ } keys %ports } @ports;
+	return join ', ', map { $_ . ": " . $ports{$_} } @keys;
 }
 
 ###############################################################################
--- a/stream_udp_upstream_hash.t
+++ b/stream_udp_upstream_hash.t
@@ -40,57 +40,58 @@ stream {
 
     upstream hash {
         hash $remote_addr;
-        server 127.0.0.1:8087;
-        server 127.0.0.1:8088;
+        server 127.0.0.1:%%PORT_2_UDP%%;
+        server 127.0.0.1:%%PORT_3_UDP%%;
     }
 
     upstream cons {
         hash $remote_addr consistent;
-        server 127.0.0.1:8087;
-        server 127.0.0.1:8088;
+        server 127.0.0.1:%%PORT_2_UDP%%;
+        server 127.0.0.1:%%PORT_3_UDP%%;
     }
 
     server {
-        listen      127.0.0.1:8081 udp;
+        listen      127.0.0.1:%%PORT_0_UDP%% udp;
         proxy_pass  hash;
     }
 
     server {
-        listen      127.0.0.1:8082 udp;
+        listen      127.0.0.1:%%PORT_1_UDP%% udp;
         proxy_pass  cons;
     }
 }
 
 EOF
 
-$t->run_daemon(\&udp_daemon, 8087, $t);
-$t->run_daemon(\&udp_daemon, 8088, $t);
+$t->run_daemon(\&udp_daemon, port(2), $t);
+$t->run_daemon(\&udp_daemon, port(3), $t);
 $t->try_run('no stream udp')->plan(2);
 
-$t->waitforfile($t->testdir . '/8087');
-$t->waitforfile($t->testdir . '/8088');
+$t->waitforfile($t->testdir . '/' . port(2));
+$t->waitforfile($t->testdir . '/' . port(3));
 
 ###############################################################################
 
-is(many('.', 10, peer => '127.0.0.1:8081'), '8088: 10', 'hash');
-is(many('.', 10, peer => '127.0.0.1:8082'), '8088: 10', 'hash consistent');
+my @ports = my ($port2, $port3) = (port(2), port(3));
+
+is(many(10, port(0)), "$port3: 10", 'hash');
+like(many(10, port(1)), qr/($port2|$port3): 10/, 'hash consistent');
 
 ###############################################################################
 
 sub many {
-	my ($data, $count, %opts) = @_;
-	my (%ports, $peer);
-
-	$peer = $opts{peer};
+	my ($count, $port) = @_;
+	my (%ports);
 
 	for (1 .. $count) {
-		if (dgram($peer)->io($data) =~ /(\d+)/) {
+		if (dgram("127.0.0.1:$port")->io('.') =~ /(\d+)/) {
 			$ports{$1} = 0 unless defined $ports{$1};
 			$ports{$1}++;
 		}
 	}
 
-	return join ', ', map { $_ . ": " . $ports{$_} } sort keys %ports;
+	my @keys = map { my $p = $_; grep { $p == $_ } keys %ports } @ports;
+	return join ', ', map { $_ . ": " . $ports{$_} } @keys;
 }
 
 ###############################################################################
--- a/stream_udp_upstream_least_conn.t
+++ b/stream_udp_upstream_least_conn.t
@@ -39,28 +39,30 @@ stream {
 
     upstream u {
         least_conn;
-        server 127.0.0.1:8081;
-        server 127.0.0.1:8082;
+        server 127.0.0.1:%%PORT_1_UDP%%;
+        server 127.0.0.1:%%PORT_2_UDP%%;
     }
 
     server {
-        listen      127.0.0.1:8080 udp;
+        listen      127.0.0.1:%%PORT_0_UDP%% udp;
         proxy_pass  u;
     }
 }
 
 EOF
 
-$t->run_daemon(\&udp_daemon, 8081, $t);
-$t->run_daemon(\&udp_daemon, 8082, $t);
+$t->run_daemon(\&udp_daemon, port(1), $t);
+$t->run_daemon(\&udp_daemon, port(2), $t);
 $t->try_run('no stream udp')->plan(2);
 
-$t->waitforfile($t->testdir . '/8081');
-$t->waitforfile($t->testdir . '/8082');
+$t->waitforfile($t->testdir . '/' . port(1));
+$t->waitforfile($t->testdir . '/' . port(2));
 
 ###############################################################################
 
-is(many('.', 10), '8081: 5, 8082: 5', 'balanced');
+my @ports = my ($port1, $port2) = (port(1), port(2));
+
+is(many(10), "$port1: 5, $port2: 5", 'balanced');
 
 my @sockets;
 for (1 .. 2) {
@@ -71,22 +73,23 @@ for (1 .. 2) {
 
 select undef, undef, undef, 0.2;
 
-is(many('.', 10), '8082: 10', 'least_conn');
+is(many(10), "$port2: 10", 'least_conn');
 
 ###############################################################################
 
 sub many {
-	my ($data, $count, %opts) = @_;
+	my ($count) = @_;
 	my (%ports);
 
 	for (1 .. $count) {
-		if (dgram()->io($data) =~ /(\d+)/) {
+		if (dgram()->io('.') =~ /(\d+)/) {
 			$ports{$1} = 0 unless defined $ports{$1};
 			$ports{$1}++;
 		}
 	}
 
-	return join ', ', map { $_ . ": " . $ports{$_} } sort keys %ports;
+	my @keys = map { my $p = $_; grep { $p == $_ } keys %ports } @ports;
+	return join ', ', map { $_ . ": " . $ports{$_} } @keys;
 }
 
 ###############################################################################
@@ -111,7 +114,7 @@ sub udp_daemon {
 
 		my $port = $server->sockport();
 
-		if ($buffer =~ /w/ && $port == 8081) {
+		if ($buffer =~ /w/ && $port == port(1)) {
 			select undef, undef, undef, 2.5;
 		}
 
--- a/stream_unix.t
+++ b/stream_unix.t
@@ -43,12 +43,12 @@ stream {
     }
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         proxy_pass   unix:%%TESTDIR%%/unix.sock;
     }
 
     server {
-        listen       127.0.0.1:8081;
+        listen       127.0.0.1:%%PORT_1%%;
         proxy_pass   u;
     }
 }
@@ -71,8 +71,8 @@ for (1 .. 50) {
 
 my $str = 'SEE-THIS';
 
-is(stream('127.0.0.1:8080')->io($str), $str, 'proxy');
-is(stream('127.0.0.1:8081')->io($str), $str, 'upstream');
+is(stream('127.0.0.1:' . port(0))->io($str), $str, 'proxy');
+is(stream('127.0.0.1:' . port(1))->io($str), $str, 'upstream');
 
 ###############################################################################
 
--- a/stream_upstream.t
+++ b/stream_upstream.t
@@ -37,82 +37,83 @@ events {
 
 stream {
     upstream u {
-        server 127.0.0.1:8087;
-        server 127.0.0.1:8088;
+        server 127.0.0.1:%%PORT_4%%;
+        server 127.0.0.1:%%PORT_5%%;
     }
 
     upstream u2 {
-        server 127.0.0.1:8089 down;
-        server 127.0.0.1:8089;
-        server 127.0.0.1:8087;
-        server 127.0.0.1:8088;
+        server 127.0.0.1:%%PORT_6%% down;
+        server 127.0.0.1:%%PORT_6%%;
+        server 127.0.0.1:%%PORT_4%%;
+        server 127.0.0.1:%%PORT_5%%;
     }
 
     upstream u3 {
-        server 127.0.0.1:8087;
-        server 127.0.0.1:8088 weight=2;
+        server 127.0.0.1:%%PORT_4%%;
+        server 127.0.0.1:%%PORT_5%% weight=2;
     }
 
     upstream u4 {
-        server 127.0.0.1:8089;
-        server 127.0.0.1:8087 backup;
+        server 127.0.0.1:%%PORT_6%%;
+        server 127.0.0.1:%%PORT_4%% backup;
     }
 
     proxy_connect_timeout 1s;
 
     server {
-        listen      127.0.0.1:8081;
+        listen      127.0.0.1:%%PORT_0%%;
         proxy_pass  u;
     }
 
     server {
-        listen      127.0.0.1:8082;
+        listen      127.0.0.1:%%PORT_1%%;
         proxy_pass  u2;
     }
 
     server {
-        listen      127.0.0.1:8083;
+        listen      127.0.0.1:%%PORT_2%%;
         proxy_pass  u3;
     }
 
     server {
-        listen      127.0.0.1:8084;
+        listen      127.0.0.1:%%PORT_3%%;
         proxy_pass  u4;
     }
 }
 
 EOF
 
-$t->run_daemon(\&stream_daemon, 8087);
-$t->run_daemon(\&stream_daemon, 8088);
+$t->run_daemon(\&stream_daemon, port(4));
+$t->run_daemon(\&stream_daemon, port(5));
 $t->run();
 
-$t->waitforsocket('127.0.0.1:8087');
-$t->waitforsocket('127.0.0.1:8088');
+$t->waitforsocket('127.0.0.1:' . port(4));
+$t->waitforsocket('127.0.0.1:' . port(5));
 
 ###############################################################################
 
-is(many('.', 30, peer => '127.0.0.1:8081'), '8087: 15, 8088: 15', 'balanced');
-is(many('.', 30, peer => '127.0.0.1:8082'), '8087: 15, 8088: 15', 'failures');
-is(many('.', 30, peer => '127.0.0.1:8083'), '8087: 10, 8088: 20', 'weight');
-is(many('.', 30, peer => '127.0.0.1:8084'), '8087: 30', 'backup');
+my @ports = my ($port4, $port5) = (port(4), port(5));
+
+is(many(30, port(0)), "$port4: 15, $port5: 15", 'balanced');
+is(many(30, port(1)), "$port4: 15, $port5: 15", 'failures');
+is(many(30, port(2)), "$port4: 10, $port5: 20", 'weight');
+is(many(30, port(3)), "$port4: 30", 'backup');
 
 ###############################################################################
 
 sub many {
-	my ($data, $count, %opts) = @_;
-	my (%ports, $peer);
-
-	$peer = $opts{peer};
+	my ($count, $port) = @_;
+	my (%ports);
 
 	for (1 .. $count) {
-		if (stream($peer)->io($data) =~ /(\d+)/) {
+		if (stream("127.0.0.1:$port")->io('.') =~ /(\d+)/) {
 			$ports{$1} = 0 unless defined $ports{$1};
 			$ports{$1}++;
 		}
 	}
 
-	return join ', ', map { $_ . ": " . $ports{$_} } sort keys %ports;
+	my @keys = map { my $p = $_; grep { $p == $_ } keys %ports } @ports;
+	return join ', ', map { $_ . ": " . $ports{$_} } @keys;
 }
 
 ###############################################################################
--- a/stream_upstream_hash.t
+++ b/stream_upstream_hash.t
@@ -39,57 +39,58 @@ events {
 stream {
     upstream hash {
         hash $remote_addr;
-        server 127.0.0.1:8087;
-        server 127.0.0.1:8088;
+        server 127.0.0.1:%%PORT_2%%;
+        server 127.0.0.1:%%PORT_3%%;
     }
 
     upstream cons {
         hash $remote_addr consistent;
-        server 127.0.0.1:8087;
-        server 127.0.0.1:8088;
+        server 127.0.0.1:%%PORT_2%%;
+        server 127.0.0.1:%%PORT_3%%;
     }
 
     server {
-        listen      127.0.0.1:8081;
+        listen      127.0.0.1:%%PORT_0%%;
         proxy_pass  hash;
     }
 
     server {
-        listen      127.0.0.1:8082;
+        listen      127.0.0.1:%%PORT_1%%;
         proxy_pass  cons;
     }
 }
 
 EOF
 
-$t->run_daemon(\&stream_daemon, 8087);
-$t->run_daemon(\&stream_daemon, 8088);
+$t->run_daemon(\&stream_daemon, port(2));
+$t->run_daemon(\&stream_daemon, port(3));
 $t->run();
 
-$t->waitforsocket('127.0.0.1:8087');
-$t->waitforsocket('127.0.0.1:8088');
+$t->waitforsocket('127.0.0.1:' . port(2));
+$t->waitforsocket('127.0.0.1:' . port(3));
 
 ###############################################################################
 
-is(many('.', 10, peer => '127.0.0.1:8081'), '8088: 10', 'hash');
-is(many('.', 10, peer => '127.0.0.1:8082'), '8088: 10', 'hash consistent');
+my @ports = my ($port2, $port3) = (port(2), port(3));
+
+is(many(10, port(0)), "$port3: 10", 'hash');
+like(many(10, port(1)), qr/($port2|$port3): 10/, 'hash consistent');
 
 ###############################################################################
 
 sub many {
-	my ($data, $count, %opts) = @_;
-	my (%ports, $peer);
-
-	$peer = $opts{peer};
+	my ($count, $port) = @_;
+	my (%ports);
 
 	for (1 .. $count) {
-		if (stream($peer)->io($data) =~ /(\d+)/) {
+		if (stream("127.0.0.1:$port")->io('.') =~ /(\d+)/) {
 			$ports{$1} = 0 unless defined $ports{$1};
 			$ports{$1}++;
 		}
 	}
 
-	return join ', ', map { $_ . ": " . $ports{$_} } sort keys %ports;
+	my @keys = map { my $p = $_; grep { $p == $_ } keys %ports } @ports;
+	return join ', ', map { $_ . ": " . $ports{$_} } @keys;
 }
 
 ###############################################################################
--- a/stream_upstream_least_conn.t
+++ b/stream_upstream_least_conn.t
@@ -38,28 +38,30 @@ events {
 stream {
     upstream u {
         least_conn;
-        server 127.0.0.1:8081;
-        server 127.0.0.1:8082;
+        server 127.0.0.1:%%PORT_1%%;
+        server 127.0.0.1:%%PORT_2%%;
     }
 
     server {
-        listen      127.0.0.1:8080;
+        listen      127.0.0.1:%%PORT_0%%;
         proxy_pass  u;
     }
 }
 
 EOF
 
-$t->run_daemon(\&stream_daemon, 8081);
-$t->run_daemon(\&stream_daemon, 8082);
+$t->run_daemon(\&stream_daemon, port(1));
+$t->run_daemon(\&stream_daemon, port(2));
 $t->run();
 
-$t->waitforsocket('127.0.0.1:8081');
-$t->waitforsocket('127.0.0.1:8082');
+$t->waitforsocket('127.0.0.1:' . port(1));
+$t->waitforsocket('127.0.0.1:' . port(2));
 
 ###############################################################################
 
-is(many('.', 10), '8081: 5, 8082: 5', 'balanced');
+my @ports = my ($port1, $port2) = (port(1), port(2));
+
+is(many(10), "$port1: 5, $port2: 5", 'balanced');
 
 my @sockets;
 for (1 .. 2) {
@@ -70,22 +72,23 @@ for (1 .. 2) {
 
 select undef, undef, undef, 0.2;
 
-is(many('.', 10), '8082: 10', 'least_conn');
+is(many(10), "$port2: 10", 'least_conn');
 
 ###############################################################################
 
 sub many {
-	my ($data, $count, %opts) = @_;
+	my ($count) = @_;
 	my (%ports);
 
 	for (1 .. $count) {
-		if (stream()->io($data) =~ /(\d+)/) {
+		if (stream()->io('.') =~ /(\d+)/) {
 			$ports{$1} = 0 unless defined $ports{$1};
 			$ports{$1}++;
 		}
 	}
 
-	return join ', ', map { $_ . ": " . $ports{$_} } sort keys %ports;
+	my @keys = map { my $p = $_; grep { $p == $_ } keys %ports } @ports;
+	return join ', ', map { $_ . ": " . $ports{$_} } @keys;
 }
 
 ###############################################################################
@@ -132,7 +135,7 @@ sub stream_handle_client {
 
 	my $port = $client->sockport();
 
-	if ($buffer =~ /w/ && $port == 8081) {
+	if ($buffer =~ /w/ && $port == port(1)) {
 		Test::Nginx::log_core('||', "$port: sleep(2.5)");
 		select undef, undef, undef, 2.5;
 	}
--- a/stream_upstream_zone_ssl.t
+++ b/stream_upstream_zone_ssl.t
@@ -40,34 +40,34 @@ stream {
 
     upstream u {
         zone u 32k;
-        server 127.0.0.1:8087;
+        server 127.0.0.1:%%PORT_4%%;
     }
 
     upstream u2 {
         zone u2 32k;
-        server 127.0.0.1:8087 backup;
-        server 127.0.0.1:8088 down;
+        server 127.0.0.1:%%PORT_4%% backup;
+        server 127.0.0.1:%%PORT_5%% down;
     }
 
     server {
-        listen      127.0.0.1:8080;
+        listen      127.0.0.1:%%PORT_0%%;
         proxy_pass  u;
         proxy_ssl_session_reuse off;
     }
 
     server {
-        listen      127.0.0.1:8081;
+        listen      127.0.0.1:%%PORT_1%%;
         proxy_pass  u;
     }
 
     server {
-        listen      127.0.0.1:8082;
+        listen      127.0.0.1:%%PORT_2%%;
         proxy_pass  u2;
         proxy_ssl_session_reuse off;
     }
 
     server {
-        listen      127.0.0.1:8083;
+        listen      127.0.0.1:%%PORT_3%%;
         proxy_pass  u2;
     }
 }
@@ -76,7 +76,7 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen 127.0.0.1:8087 ssl;
+        listen 127.0.0.1:%%PORT_4%% ssl;
 
         ssl_certificate_key localhost.key;
         ssl_certificate localhost.crt;
@@ -114,24 +114,22 @@ foreach my $name ('localhost') {
 
 ###############################################################################
 
-like(http_get('/', socket => getconn('127.0.0.1:8080')),
-	qr/200 OK.*X-Session: \./s, 'ssl');
-like(http_get('/', socket => getconn('127.0.0.1:8081')),
+like(http_get('/'), qr/200 OK.*X-Session: \./s, 'ssl');
+like(http_get('/', socket => getconn('127.0.0.1:' . port(1))),
 	qr/200 OK.*X-Session: \./s, 'ssl 2');
 
-like(http_get('/', socket => getconn('127.0.0.1:8080')),
-	qr/200 OK.*X-Session: \./s, 'ssl reuse session');
-like(http_get('/', socket => getconn('127.0.0.1:8081')),
+like(http_get('/'), qr/200 OK.*X-Session: \./s, 'ssl reuse session');
+like(http_get('/', socket => getconn('127.0.0.1:' . port(1))),
 	qr/200 OK.*X-Session: r/s, 'ssl reuse session 2');
 
-like(http_get('/', socket => getconn('127.0.0.1:8082')),
+like(http_get('/', socket => getconn('127.0.0.1:' . port(2))),
 	qr/200 OK.*X-Session: \./s, 'ssl backup');
-like(http_get('/', socket => getconn('127.0.0.1:8083')),
+like(http_get('/', socket => getconn('127.0.0.1:' . port(3))),
 	qr/200 OK.*X-Session: \./s, 'ssl backup 2');
 
-like(http_get('/', socket => getconn('127.0.0.1:8082')),
+like(http_get('/', socket => getconn('127.0.0.1:' . port(2))),
 	qr/200 OK.*X-Session: \./s, 'ssl reuse session backup');
-like(http_get('/', socket => getconn('127.0.0.1:8083')),
+like(http_get('/', socket => getconn('127.0.0.1:' . port(3))),
 	qr/200 OK.*X-Session: r/s, 'ssl reuse session backup 2');
 
 ###############################################################################
@@ -140,7 +138,7 @@ sub getconn {
 	my $peer = shift;
 	my $s = IO::Socket::INET->new(
 		Proto => 'tcp',
-		PeerAddr => $peer || '127.0.0.1:8080'
+		PeerAddr => $peer
 	)
 		or die "Can't connect to nginx: $!\n";
 
--- a/stub_status.t
+++ b/stub_status.t
@@ -37,7 +37,7 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         add_header X-Active $connections_active;
--- a/sub_filter.t
+++ b/sub_filter.t
@@ -35,7 +35,7 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         sub_filter_types *;
@@ -91,12 +91,12 @@ http {
 
         location /lm {
             sub_filter_last_modified on;
-            proxy_pass http://127.0.0.1:8081/;
+            proxy_pass http://127.0.0.1:%%PORT_1%%/;
         }
     }
 
     server {
-        listen       127.0.0.1:8081;
+        listen       127.0.0.1:%%PORT_1%%;
         server_name  localhost;
     }
 }
--- a/sub_filter_merge.t
+++ b/sub_filter_merge.t
@@ -42,7 +42,7 @@ http {
     sub_filter foo bar;
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         location / { }
--- a/sub_filter_multi.t
+++ b/sub_filter_multi.t
@@ -39,7 +39,7 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         sub_filter_types *;
@@ -198,7 +198,7 @@ http {
             sub_filter_once off;
             sub_filter abpatternyz +;
 
-            proxy_pass http://127.0.0.1:8081/;
+            proxy_pass http://127.0.0.1:%%PORT_1%%/;
             proxy_buffering off;
         }
 
@@ -207,7 +207,7 @@ http {
             sub_filter abpatternyz +;
             sub_filter abpaernyz -;
 
-            proxy_pass http://127.0.0.1:8081/;
+            proxy_pass http://127.0.0.1:%%PORT_1%%/;
             proxy_buffering off;
         }
 
@@ -217,7 +217,7 @@ http {
             sub_filter abpaernyz -;
             sub_filter _ *;
 
-            proxy_pass http://127.0.0.1:8081/;
+            proxy_pass http://127.0.0.1:%%PORT_1%%/;
             proxy_buffering off;
         }
 
@@ -225,7 +225,7 @@ http {
             sub_filter_once off;
             sub_filter patt +;
 
-            proxy_pass http://127.0.0.1:8081/;
+            proxy_pass http://127.0.0.1:%%PORT_1%%/;
             proxy_buffering off;
         }
 
@@ -235,13 +235,13 @@ http {
             sub_filter abpa -;
             sub_filter tter *;
 
-            proxy_pass http://127.0.0.1:8081/;
+            proxy_pass http://127.0.0.1:%%PORT_1%%/;
             proxy_buffering off;
         }
     }
 
     server {
-        listen       127.0.0.1:8081;
+        listen       127.0.0.1:%%PORT_1%%;
 
         limit_rate 4;
         limit_rate_after 160;
--- a/sub_filter_multi2.t
+++ b/sub_filter_multi2.t
@@ -36,7 +36,7 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         sub_filter_types *;
--- a/sub_filter_perl.t
+++ b/sub_filter_perl.t
@@ -35,7 +35,7 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         sub_filter_types *;
--- a/sub_filter_ssi.t
+++ b/sub_filter_ssi.t
@@ -40,7 +40,7 @@ http {
     }
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         location / {
--- a/syslog.t
+++ b/syslog.t
@@ -30,7 +30,7 @@ my $t = Test::Nginx->new()->has(qw/http 
 
 %%TEST_GLOBALS%%
 
-error_log syslog:server=127.0.0.1:8083 info;
+error_log syslog:server=127.0.0.1:%%PORT_1_UDP%% info;
 error_log %%TESTDIR%%/f_glob.log info;
 
 daemon off;
@@ -46,101 +46,102 @@ http {
     log_format empty "";
     log_format logf "$uri:$status";
 
-    error_log syslog:server=127.0.0.1:8084 info;
+    error_log syslog:server=127.0.0.1:%%PORT_2_UDP%% info;
     error_log %%TESTDIR%%/f_http.log info;
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         location /e {
-            error_log syslog:server=127.0.0.1:8080;
+            error_log syslog:server=127.0.0.1:%%PORT_4_UDP%%;
         }
         location /a {
-            access_log syslog:server=127.0.0.1:8080;
+            access_log syslog:server=127.0.0.1:%%PORT_4_UDP%%;
         }
         location /ef {
-            error_log syslog:server=127.0.0.1:8080,facility=user;
+            error_log syslog:server=127.0.0.1:%%PORT_4_UDP%%,facility=user;
         }
         location /es {
-            error_log syslog:server=127.0.0.1:8080,severity=alert;
+            error_log syslog:server=127.0.0.1:%%PORT_4_UDP%%,severity=alert;
         }
         location /et {
-            error_log syslog:server=127.0.0.1:8080,tag=SEETHIS;
+            error_log syslog:server=127.0.0.1:%%PORT_4_UDP%%,tag=SEETHIS;
         }
         location /af {
-            access_log syslog:server=127.0.0.1:8080,facility=user;
+            access_log syslog:server=127.0.0.1:%%PORT_4_UDP%%,facility=user;
         }
         location /as {
             # put severity inside to catch possible parsing programming errors
-            access_log syslog:severity=alert,server=127.0.0.1:8080;
+            access_log syslog:severity=alert,server=127.0.0.1:%%PORT_4_UDP%%;
         }
         location /at {
-            access_log syslog:server=127.0.0.1:8080,tag=SEETHIS;
+            access_log syslog:server=127.0.0.1:%%PORT_4_UDP%%,tag=SEETHIS;
         }
         location /e2 {
-            error_log syslog:server=127.0.0.1:8080;
-            error_log syslog:server=127.0.0.1:8080;
+            error_log syslog:server=127.0.0.1:%%PORT_4_UDP%%;
+            error_log syslog:server=127.0.0.1:%%PORT_4_UDP%%;
         }
         location /a2 {
-            access_log syslog:server=127.0.0.1:8080;
-            access_log syslog:server=127.0.0.1:8080;
+            access_log syslog:server=127.0.0.1:%%PORT_4_UDP%%;
+            access_log syslog:server=127.0.0.1:%%PORT_4_UDP%%;
         }
         location /a_logf {
-            access_log syslog:server=127.0.0.1:8080 logf;
+            access_log syslog:server=127.0.0.1:%%PORT_4_UDP%% logf;
         }
         location /if {
-            access_log syslog:server=127.0.0.1:8085 logf if=$arg_logme;
+            access_log syslog:server=127.0.0.1:%%PORT_3_UDP%% logf
+                if=$arg_logme;
         }
 
         location /nohostname {
-            access_log syslog:server=127.0.0.1:8080,nohostname;
+            access_log syslog:server=127.0.0.1:%%PORT_4_UDP%%,nohostname;
         }
 
         location /debug {
             limit_req zone=one;
-            error_log syslog:server=127.0.0.1:8080 debug;
+            error_log syslog:server=127.0.0.1:%%PORT_4_UDP%% debug;
         }
         location /info {
             limit_req zone=one;
             limit_req_log_level info;
-            error_log syslog:server=127.0.0.1:8080 info;
+            error_log syslog:server=127.0.0.1:%%PORT_4_UDP%% info;
         }
         location /notice {
             limit_req zone=one;
             limit_req_log_level notice;
-            error_log syslog:server=127.0.0.1:8080 notice;
+            error_log syslog:server=127.0.0.1:%%PORT_4_UDP%% notice;
         }
         location /warn {
             limit_req zone=one;
             limit_req_log_level warn;
-            error_log syslog:server=127.0.0.1:8080 warn;
+            error_log syslog:server=127.0.0.1:%%PORT_4_UDP%% warn;
         }
         location /error {
             limit_req zone=one;
             limit_req_log_level error;
-            error_log syslog:server=127.0.0.1:8080;
+            error_log syslog:server=127.0.0.1:%%PORT_4_UDP%%;
         }
         location /low {
-            error_log syslog:server=127.0.0.1:8080 warn;
-            error_log syslog:server=127.0.0.1:8080;
+            error_log syslog:server=127.0.0.1:%%PORT_4_UDP%% warn;
+            error_log syslog:server=127.0.0.1:%%PORT_4_UDP%%;
         }
         location /dup {
-            error_log syslog:server=127.0.0.1:8080;
-            error_log syslog:server=127.0.0.1:8080;
+            error_log syslog:server=127.0.0.1:%%PORT_4_UDP%%;
+            error_log syslog:server=127.0.0.1:%%PORT_4_UDP%%;
         }
         location /high {
-            error_log syslog:server=127.0.0.1:8080 emerg;
-            error_log syslog:server=127.0.0.1:8080;
+            error_log syslog:server=127.0.0.1:%%PORT_4_UDP%% emerg;
+            error_log syslog:server=127.0.0.1:%%PORT_4_UDP%%;
         }
     }
 }
 
 EOF
 
-$t->run_daemon(\&syslog_daemon, 8083, $t, 's_glob.log');
-$t->run_daemon(\&syslog_daemon, 8084, $t, 's_http.log');
-$t->run_daemon(\&syslog_daemon, 8085, $t, 's_if.log');
+$t->run_daemon(\&syslog_daemon, port(1), $t, 's_glob.log');
+$t->run_daemon(\&syslog_daemon, port(2), $t, 's_http.log');
+$t->run_daemon(\&syslog_daemon, port(3), $t, 's_if.log');
 
 $t->waitforfile($t->testdir . '/s_glob.log');
 $t->waitforfile($t->testdir . '/s_http.log');
@@ -226,7 +227,7 @@ like(get_syslog('/nohostname'),
 
 sub syslog_lines {
 	my ($uri, $pattern, $port) = @_;
-	return map { $_ =~ /\Q$pattern\E/g } (get_syslog($uri, $port));
+	return map { $_ =~ /\Q$pattern\E/g } (get_syslog($uri));
 }
 
 sub levels {
@@ -239,20 +240,18 @@ sub levels {
 }
 
 sub get_syslog {
-	my ($uri, $port) = @_;
+	my ($uri) = @_;
 	my ($s);
 	my $rfd = '';
 	my $data = '';
 
-	$port = 8080 unless defined $port;
-
 	eval {
 		local $SIG{ALRM} = sub { die "timeout\n" };
 		local $SIG{PIPE} = sub { die "sigpipe\n" };
 		alarm(1);
 		$s = IO::Socket::INET->new(
 			Proto => 'udp',
-			LocalAddr => "127.0.0.1:$port"
+			LocalAddr => '127.0.0.1:' . port(4)
 		);
 		alarm(0);
 	};
--- a/upstream.t
+++ b/upstream.t
@@ -36,17 +36,17 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     upstream u {
-        server 127.0.0.1:8081 max_fails=3 fail_timeout=10s;
-        server 127.0.0.1:8082 max_fails=3 fail_timeout=10s;
+        server 127.0.0.1:%%PORT_1%% max_fails=3 fail_timeout=10s;
+        server 127.0.0.1:%%PORT_2%% max_fails=3 fail_timeout=10s;
     }
 
     upstream u2 {
-        server 127.0.0.1:8081 max_fails=3 fail_timeout=10s;
-        server 127.0.0.1:8082 max_fails=3 fail_timeout=10s;
+        server 127.0.0.1:%%PORT_1%% max_fails=3 fail_timeout=10s;
+        server 127.0.0.1:%%PORT_2%% max_fails=3 fail_timeout=10s;
     }
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         location / {
@@ -60,22 +60,24 @@ http {
 
 EOF
 
-$t->run_daemon(\&http_daemon, 8081);
-$t->run_daemon(\&http_daemon, 8082);
+$t->run_daemon(\&http_daemon, port(1));
+$t->run_daemon(\&http_daemon, port(2));
 $t->run();
 
-$t->waitforsocket('127.0.0.1:8081');
-$t->waitforsocket('127.0.0.1:8082');
+$t->waitforsocket('127.0.0.1:' . port(1));
+$t->waitforsocket('127.0.0.1:' . port(2));
 
 ###############################################################################
 
-is(many('/', 30), '8081: 15, 8082: 15', 'balanced');
+my @ports = my ($p1, $p2) = (port(1), port(2));
 
-# from 9 first requests to 8081, only 6 will be successful,
+is(many('/', 30), "$p1: 15, $p2: 15", 'balanced');
+
+# from 9 first requests to the first port, only 6 will be successful,
 # 3rd, 6th, and 9th requests will fail; after this the backend
 # will be considered down and won't be used till fail_timeout passes
 
-is(many('/close', 30), '8081: 6, 8082: 24', 'failures');
+is(many('/close', 30), "$p1: 6, $p2: 24", 'failures');
 
 SKIP: {
 skip 'long test', 1 unless $ENV{TEST_NGINX_UNSAFE};
@@ -85,7 +87,7 @@ skip 'long test', 1 unless $ENV{TEST_NGI
 # delay added to make sure first 9 requests will take more than 1s;
 # note that the test is racy and may unexpectedly succeed
 
-is(many('/close2', 30, delay => 0.2), '8081: 6, 8082: 24', 'failures delay');
+is(many('/close2', 30, delay => 0.2), "$p1: 6, $p2: 24", 'failures delay');
 
 }
 
@@ -104,7 +106,8 @@ sub many {
 		select undef, undef, undef, $opts{delay} if $opts{delay};
 	}
 
-	return join ', ', map { $_ . ": " . $ports{$_} } sort keys %ports;
+	my @keys = map { my $p = $_; grep { $p == $_ } keys %ports } @ports;
+	return join ', ', map { $_ . ": " . $ports{$_} } @keys;
 }
 
 ###############################################################################
@@ -137,7 +140,7 @@ sub http_daemon {
 
 		$uri = $1 if $headers =~ /^\S+\s+([^ ]+)\s+HTTP/i;
 
-		if ($uri =~ 'close' && $port == 8081 && $count++ % 3 == 0) {
+		if ($uri =~ 'close' && $port == port(1) && $count++ % 3 == 0) {
 			next;
 		}
 
--- a/upstream_hash.t
+++ b/upstream_hash.t
@@ -38,57 +38,57 @@ http {
 
     upstream u {
         hash $arg_a;
-        server 127.0.0.1:8081;
-        server 127.0.0.1:8082;
-        server 127.0.0.1:8083;
+        server 127.0.0.1:%%PORT_1%%;
+        server 127.0.0.1:%%PORT_2%%;
+        server 127.0.0.1:%%PORT_3%%;
     }
 
     upstream u2 {
         hash $arg_a;
-        server 127.0.0.1:8081;
-        server 127.0.0.1:8083;
+        server 127.0.0.1:%%PORT_1%%;
+        server 127.0.0.1:%%PORT_3%%;
     }
 
     upstream cw {
         hash $arg_a consistent;
-        server 127.0.0.1:8081;
-        server 127.0.0.1:8082;
-        server 127.0.0.1:8083 weight=10;
+        server 127.0.0.1:%%PORT_1%%;
+        server 127.0.0.1:%%PORT_2%%;
+        server 127.0.0.1:%%PORT_3%% weight=10;
     }
 
     upstream cw2 {
         hash $arg_a consistent;
-        server 127.0.0.1:8081;
-        server 127.0.0.1:8083 weight=10;
+        server 127.0.0.1:%%PORT_1%%;
+        server 127.0.0.1:%%PORT_3%% weight=10;
     }
 
     upstream c {
         hash $arg_a consistent;
-        server 127.0.0.1:8081;
-        server 127.0.0.1:8082;
-        server 127.0.0.1:8083;
+        server 127.0.0.1:%%PORT_1%%;
+        server 127.0.0.1:%%PORT_2%%;
+        server 127.0.0.1:%%PORT_3%%;
     }
 
     upstream c2 {
         hash $arg_a consistent;
-        server 127.0.0.1:8081;
-        server 127.0.0.1:8083;
+        server 127.0.0.1:%%PORT_1%%;
+        server 127.0.0.1:%%PORT_3%%;
     }
 
     upstream bad {
         hash $arg_a;
-        server 127.0.0.1:8081;
-        server 127.0.0.1:8084;
+        server 127.0.0.1:%%PORT_1%%;
+        server 127.0.0.1:%%PORT_4%%;
     }
 
     upstream cbad {
         hash $arg_a consistent;
-        server 127.0.0.1:8081;
-        server 127.0.0.1:8084;
+        server 127.0.0.1:%%PORT_1%%;
+        server 127.0.0.1:%%PORT_4%%;
     }
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         location / {
@@ -122,9 +122,9 @@ http {
     }
 
     server {
-        listen       127.0.0.1:8081;
-        listen       127.0.0.1:8082;
-        listen       127.0.0.1:8083;
+        listen       127.0.0.1:%%PORT_1%%;
+        listen       127.0.0.1:%%PORT_2%%;
+        listen       127.0.0.1:%%PORT_3%%;
         server_name  localhost;
 
         add_header X-Port $server_port;
@@ -134,7 +134,7 @@ http {
         }
 
         location /502 {
-            if ($server_port = 8083) {
+            if ($server_port = %%PORT_3%%) {
                 return 502;
             }
             return 204;
@@ -142,7 +142,7 @@ http {
     }
 
     server {
-        listen       127.0.0.1:8084;
+        listen       127.0.0.1:%%PORT_4%%;
         server_name  localhost;
         return 444;
     }
@@ -154,21 +154,23 @@ EOF
 
 ###############################################################################
 
+my ($p1, $p2, $p3) = (port(1), port(2), port(3));
+
 # Only requests for absent peer are moved to other peers if hash is consistent.
 # Check this by comparing two upstreams with different number of peers.
 
-ok(!cmp_peers([iter('/', 20)], [iter('/2', 20)], 8082), 'inconsistent');
-ok(cmp_peers([iter('/c', 20)], [iter('/c2', 20)], 8082), 'consistent');
-ok(cmp_peers([iter('/cw', 20)], [iter('/cw2', 20)], 8082), 'consistent weight');
+ok(!cmp_peers([iter('/', 20)], [iter('/2', 20)], $p2), 'inconsistent');
+ok(cmp_peers([iter('/c', 20)], [iter('/c2', 20)], $p2), 'consistent');
+ok(cmp_peers([iter('/cw', 20)], [iter('/cw2', 20)], $p2), 'consistent weight');
 
-like(many('/?a=1', 10), qr/808\d: 10/, 'stable hash');
-like(many('/c?a=1', 10), qr/808\d: 10/, 'stable hash - consistent');
+like(many('/?a=1', 10), qr/($p1|$p2|$p3): 10/, 'stable hash');
+like(many('/c?a=1', 10), qr/($p1|$p2|$p3): 10/, 'stable hash - consistent');
 
 my @res = iter('/', 10);
 
 is(@res, 10, 'all hashed peers');
 
-@res = grep { $_ != 8083 } @res;
+@res = grep { $_ != $p3 } @res;
 my @res2 = iter('/502', 10);
 
 is_deeply(\@res, \@res2, 'no proxy_next_upstream');
@@ -176,10 +178,10 @@ isnt(@res2, 10, 'no proxy_next_upstream 
 
 is(iter('/pnu/502', 10), 10, 'proxy_next_upstream peers');
 
-@res = grep { $_ == 8081 } iter('/bad', 20);
+@res = grep { $_ == $p1 } iter('/bad', 20);
 is(@res, 20, 'all hashed peers - bad');
 
-@res = grep { $_ == 8081 } iter('/cbad', 20);
+@res = grep { $_ == $p1 } iter('/cbad', 20);
 is(@res, 20, 'all hashed peers - bad consistent');
 
 ###############################################################################
--- a/upstream_hash_memcached.t
+++ b/upstream_hash_memcached.t
@@ -47,34 +47,34 @@ http {
 
     upstream memd {
         hash $arg_a;
-        server 127.0.0.1:8081;
-        server 127.0.0.1:8082;
-        server 127.0.0.1:8083;
+        server 127.0.0.1:%%PORT_1%%;
+        server 127.0.0.1:%%PORT_2%%;
+        server 127.0.0.1:%%PORT_3%%;
     }
 
     upstream memd_c {
         hash $arg_a consistent;
-        server 127.0.0.1:8081;
-        server 127.0.0.1:8082;
-        server 127.0.0.1:8083;
+        server 127.0.0.1:%%PORT_1%%;
+        server 127.0.0.1:%%PORT_2%%;
+        server 127.0.0.1:%%PORT_3%%;
     }
 
     upstream memd_w {
         hash $arg_a;
-        server 127.0.0.1:8081 weight=2;
-        server 127.0.0.1:8082 weight=3;
-        server 127.0.0.1:8083;
+        server 127.0.0.1:%%PORT_1%% weight=2;
+        server 127.0.0.1:%%PORT_2%% weight=3;
+        server 127.0.0.1:%%PORT_3%%;
     }
 
     upstream memd_cw {
         hash $arg_a consistent;
-        server 127.0.0.1:8081 weight=2;
-        server 127.0.0.1:8082 weight=3;
-        server 127.0.0.1:8083;
+        server 127.0.0.1:%%PORT_1%% weight=2;
+        server 127.0.0.1:%%PORT_2%% weight=3;
+        server 127.0.0.1:%%PORT_3%%;
     }
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         set $memcached_key $arg_a;
@@ -108,37 +108,41 @@ if ($memhelp =~ /-U/) {
 	push @memopts, '-U', '0';
 }
 
-$t->run_daemon('memcached', '-l', '127.0.0.1', '-p', '8081', @memopts);
-$t->run_daemon('memcached', '-l', '127.0.0.1', '-p', '8082', @memopts);
-$t->run_daemon('memcached', '-l', '127.0.0.1', '-p', '8083', @memopts);
+$t->run_daemon('memcached', '-l', '127.0.0.1', '-p', port(1), @memopts);
+$t->run_daemon('memcached', '-l', '127.0.0.1', '-p', port(2), @memopts);
+$t->run_daemon('memcached', '-l', '127.0.0.1', '-p', port(3), @memopts);
 $t->run();
 
-$t->waitforsocket('127.0.0.1:8081') or die "Can't start memcached";
-$t->waitforsocket('127.0.0.1:8082') or die "Can't start memcached";
-$t->waitforsocket('127.0.0.1:8083') or die "Can't start memcached";
+$t->waitforsocket('127.0.0.1:' . port(1)) or die "Can't start memcached";
+$t->waitforsocket('127.0.0.1:' . port(2)) or die "Can't start memcached";
+$t->waitforsocket('127.0.0.1:' . port(3)) or die "Can't start memcached";
 
 ###############################################################################
 
-my $memd1 = Cache::Memcached->new(servers => [ '127.0.0.1:8081' ],
+my $memd1 = Cache::Memcached->new(servers => [ '127.0.0.1:' . port(1) ],
 	connect_timeout => 1.0);
-my $memd2 = Cache::Memcached->new(servers => [ '127.0.0.1:8082' ],
+my $memd2 = Cache::Memcached->new(servers => [ '127.0.0.1:' . port(2) ],
 	connect_timeout => 1.0);
-my $memd3 = Cache::Memcached->new(servers => [ '127.0.0.1:8083' ],
+my $memd3 = Cache::Memcached->new(servers => [ '127.0.0.1:' . port(3) ],
 	connect_timeout => 1.0);
 
 for my $i (1 .. 20) {
-	$memd1->set($i, '8081') or die "can't put value into memcached: $!";
-	$memd2->set($i, '8082') or die "can't put value into memcached: $!";
-	$memd3->set($i, '8083') or die "can't put value into memcached: $!";
+	$memd1->set($i, port(1)) or die "can't put value into memcached: $!";
+	$memd2->set($i, port(2)) or die "can't put value into memcached: $!";
+	$memd3->set($i, port(3)) or die "can't put value into memcached: $!";
 }
 
-my $memd = new Cache::Memcached(servers =>
-	[ '127.0.0.1:8081', '127.0.0.1:8082', '127.0.0.1:8083' ]);
+my $memd = new Cache::Memcached(servers => [
+	'127.0.0.1:' . port(1),
+	'127.0.0.1:' . port(2),
+	'127.0.0.1:' . port(3) ]);
 
 is_deeply(ngx('/'), mem($memd), 'cache::memcached');
 
-$memd = new Cache::Memcached::Fast({ ketama_points => 160, servers =>
-	[ '127.0.0.1:8081', '127.0.0.1:8082', '127.0.0.1:8083'] });
+$memd = new Cache::Memcached::Fast({ ketama_points => 160, servers => [
+	'127.0.0.1:' . port(1),
+	'127.0.0.1:' . port(2),
+	'127.0.0.1:' . port(3)] });
 
 TODO: {
 local $TODO = 'not yet' unless $Config{byteorder} =~ '1234'
@@ -149,16 +153,16 @@ is_deeply(ngx('/c'), mem($memd), 'cache:
 }
 
 $memd = new Cache::Memcached(servers => [
-	[ '127.0.0.1:8081', 2 ],
-	[ '127.0.0.1:8082', 3 ],
-	[ '127.0.0.1:8083', 1 ]]);
+	[ '127.0.0.1:' . port(1), 2 ],
+	[ '127.0.0.1:' . port(2), 3 ],
+	[ '127.0.0.1:' . port(3), 1 ]]);
 
 is_deeply(ngx('/w'), mem($memd), 'cache::memcached weight');
 
 $memd = new Cache::Memcached::Fast({ ketama_points => 160, servers => [
-	{ address => '127.0.0.1:8081', weight => 2 },
-	{ address => '127.0.0.1:8082', weight => 3 },
-	{ address => '127.0.0.1:8083', weight => 1 }] });
+	{ address => '127.0.0.1:' . port(1), weight => 2 },
+	{ address => '127.0.0.1:' . port(2), weight => 3 },
+	{ address => '127.0.0.1:' . port(3), weight => 1 }] });
 
 TODO: {
 local $TODO = 'not yet' unless $Config{byteorder} =~ '1234'
--- a/upstream_ip_hash.t
+++ b/upstream_ip_hash.t
@@ -38,19 +38,19 @@ http {
 
     upstream u {
         ip_hash;
-        server 127.0.0.1:8081;
-        server 127.0.0.1:8082;
+        server 127.0.0.1:%%PORT_1%%;
+        server 127.0.0.1:%%PORT_2%%;
     }
 
     upstream u2 {
         ip_hash;
-        server 127.0.0.1:8081;
-        server 127.0.0.1:8082;
-        server 127.0.0.1:8083;
+        server 127.0.0.1:%%PORT_1%%;
+        server 127.0.0.1:%%PORT_2%%;
+        server 127.0.0.1:%%PORT_3%%;
     }
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         set_real_ip_from 127.0.0.0/8;
@@ -65,9 +65,9 @@ http {
     }
 
     server {
-        listen       127.0.0.1:8081;
-        listen       127.0.0.1:8082;
-        listen       127.0.0.1:8083;
+        listen       127.0.0.1:%%PORT_1%%;
+        listen       127.0.0.1:%%PORT_2%%;
+        listen       127.0.0.1:%%PORT_3%%;
         server_name  localhost;
 
         location / {
@@ -86,8 +86,10 @@ plan(skip_all => 'no 127.0.0.1 on host')
 
 ###############################################################################
 
-is(many('/', 30), '8081: 15, 8082: 15', 'ip_hash');
-is(many('/u2', 30), '8081: 10, 8082: 10, 8083: 10', 'ip_hash 3 peers');
+my @ports = my ($port1, $port2, $port3) = (port(1), port(2), port(3));
+
+is(many('/', 30), "$port1: 15, $port2: 15", 'ip_hash');
+is(many('/u2', 30), "$port1: 10, $port2: 10, $port3: 10", 'ip_hash 3 peers');
 
 ###############################################################################
 
@@ -105,7 +107,8 @@ sub many {
 		}
 	}
 
-	return join ', ', map { $_ . ": " . $ports{$_} } sort keys %ports;
+	my @keys = map { my $p = $_; grep { $p == $_ } keys %ports } @ports;
+	return join ', ', map { $_ . ": " . $ports{$_} } @keys;
 }
 
 ###############################################################################
--- a/upstream_least_conn.t
+++ b/upstream_least_conn.t
@@ -37,12 +37,12 @@ http {
 
     upstream u {
         least_conn;
-        server 127.0.0.1:8081;
-        server 127.0.0.1:8082;
+        server 127.0.0.1:%%PORT_1%%;
+        server 127.0.0.1:%%PORT_2%%;
     }
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         location / {
@@ -53,16 +53,18 @@ http {
 
 EOF
 
-$t->run_daemon(\&http_daemon, 8081);
-$t->run_daemon(\&http_daemon, 8082);
+$t->run_daemon(\&http_daemon, port(1));
+$t->run_daemon(\&http_daemon, port(2));
 $t->run();
 
-$t->waitforsocket('127.0.0.1:8081');
-$t->waitforsocket('127.0.0.1:8082');
+$t->waitforsocket('127.0.0.1:' . port(1));
+$t->waitforsocket('127.0.0.1:' . port(2));
 
 ###############################################################################
 
-is(many('/', 10), '8081: 5, 8082: 5', 'balanced');
+my @ports = my ($port1, $port2) = (port(1), port(2));
+
+is(many('/', 10), "$port1: 5, $port2: 5", 'balanced');
 
 my @sockets;
 push(@sockets, http_get('/w', start => 1));
@@ -70,7 +72,7 @@ push(@sockets, http_get('/w', start => 1
 
 select undef, undef, undef, 0.2;
 
-is(many('/w', 10), '8082: 10', 'least conn');
+is(many('/w', 10), "$port2: 10", 'least conn');
 
 ###############################################################################
 
@@ -85,7 +87,8 @@ sub many {
 		}
 	}
 
-	return join ', ', map { $_ . ": " . $ports{$_} } sort keys %ports;
+	my @keys = map { my $p = $_; grep { $p == $_ } keys %ports } @ports;
+	return join ', ', map { $_ . ": " . $ports{$_} } @keys;
 }
 
 ###############################################################################
@@ -117,7 +120,7 @@ sub http_daemon {
 
 		$uri = $1 if $headers =~ /^\S+\s+([^ ]+)\s+HTTP/i;
 
-		if ($uri eq '/w' && $port == 8081) {
+		if ($uri eq '/w' && $port == port(1)) {
 			Test::Nginx::log_core('||', "$port: sleep(2.5)");
 			select undef, undef, undef, 2.5;
 		}
--- a/upstream_zone_ssl.t
+++ b/upstream_zone_ssl.t
@@ -37,17 +37,17 @@ http {
 
     upstream u {
         zone u 32k;
-        server 127.0.0.1:8081;
+        server 127.0.0.1:%%PORT_1%%;
     }
 
     upstream u2 {
         zone u;
-        server 127.0.0.1:8081 backup;
-        server 127.0.0.1:8082 down;
+        server 127.0.0.1:%%PORT_1%% backup;
+        server 127.0.0.1:%%PORT_2%% down;
     }
 
     server {
-        listen 127.0.0.1:8081 ssl;
+        listen 127.0.0.1:%%PORT_1%% ssl;
 
         ssl_certificate_key localhost.key;
         ssl_certificate localhost.crt;
@@ -59,7 +59,7 @@ http {
     }
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         proxy_ssl_session_reuse off;
--- a/userid.t
+++ b/userid.t
@@ -47,7 +47,7 @@ http {
     }
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         add_header X-Got $uid_got;
--- a/uwsgi.t
+++ b/uwsgi.t
@@ -35,15 +35,15 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     upstream u {
-        server 127.0.0.1:8081;
+        server 127.0.0.1:%%PORT_1%%;
     }
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         location / {
-            uwsgi_pass 127.0.0.1:8081;
+            uwsgi_pass 127.0.0.1:%%PORT_1%%;
             uwsgi_param SERVER_PROTOCOL $server_protocol;
             uwsgi_param HTTP_X_BLAH "blah";
         }
@@ -73,13 +73,13 @@ if ($uwsgihelp !~ /--wsgi-file/) {
 	push @uwsgiopts, '--plugin', 'python';
 }
 
-$t->run_daemon('uwsgi', '--socket', '127.0.0.1:8081', @uwsgiopts,
+$t->run_daemon('uwsgi', '--socket', '127.0.0.1:' . port(1), @uwsgiopts,
 	'--wsgi-file', $t->testdir() . '/uwsgi_test_app.py',
 	'--logto', $t->testdir() . '/uwsgi_log');
 
 $t->run();
 
-$t->waitforsocket('127.0.0.1:8081')
+$t->waitforsocket('127.0.0.1:' . port(1))
 	or die "Can't start uwsgi";
 
 ###############################################################################
@@ -90,7 +90,8 @@ unlike(http_head('/head'), qr/SEE-THIS/,
 like(http_get_headers('/headers'), qr/SEE-THIS/,
 	'uwsgi request with many ignored headers');
 
-like(http_get('/var?b=127.0.0.1:8081'), qr/SEE-THIS/, 'uwsgi with variables');
+like(http_get('/var?b=127.0.0.1:' . port(1)), qr/SEE-THIS/,
+	'uwsgi with variables');
 like(http_get('/var?b=u'), qr/SEE-THIS/, 'uwsgi with variables to upstream');
 
 ###############################################################################
--- a/xslt.t
+++ b/xslt.t
@@ -36,7 +36,7 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         default_type text/xml;
--- a/xslt_params.t
+++ b/xslt_params.t
@@ -36,7 +36,7 @@ http {
     %%TEST_GLOBALS_HTTP%%
 
     server {
-        listen       127.0.0.1:8080;
+        listen       127.0.0.1:%%PORT_0%%;
         server_name  localhost;
 
         default_type text/xml;