Skip to content

Commit e7951ee

Browse files
committed
dynamic port choice
also: better error messages in tests
1 parent 7009f65 commit e7951ee

File tree

8 files changed

+57
-32
lines changed

8 files changed

+57
-32
lines changed

sqlpage/templates/error.handlebars

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
<div class="text-muted">
1414
<p>We are sorry, but an error occurred while generating this page. You should contact the site's
1515
administrator.</p>
16-
<pre class="mt-2"><code>{{description}}</code></pre>
16+
<pre class="mt-2"><code class="sqlpage-error-description">{{description}}</code></pre>
1717
{{#if backtrace}}
1818
<details class="mt-2">
1919
<summary>Backtrace</summary>

tests/common/mod.rs

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -137,7 +137,9 @@ fn build_echo_response(body: Vec<u8>, meta: String) -> HttpResponse {
137137
.body(resp)
138138
}
139139

140-
pub fn start_echo_server(shutdown: oneshot::Receiver<()>) -> JoinHandle<()> {
140+
pub fn start_echo_server(shutdown: oneshot::Receiver<()>) -> (JoinHandle<()>, u16) {
141+
let listener = std::net::TcpListener::bind("localhost:0").unwrap();
142+
let port = listener.local_addr().unwrap().port();
141143
let server = HttpServer::new(|| {
142144
App::new().default_service(fn_service(|mut req: ServiceRequest| async move {
143145
let meta = format_request_line_and_headers(&req);
@@ -146,14 +148,15 @@ pub fn start_echo_server(shutdown: oneshot::Receiver<()>) -> JoinHandle<()> {
146148
Ok(req.into_response(resp))
147149
}))
148150
})
149-
.bind("localhost:62802")
151+
.listen(listener)
150152
.unwrap()
151153
.shutdown_timeout(1)
152154
.run();
153-
tokio::spawn(async move {
155+
let handle = tokio::spawn(async move {
154156
tokio::select! {
155157
_ = server => {},
156158
_ = shutdown => {},
157159
}
158-
})
160+
});
161+
(handle, port)
159162
}

tests/sql_test_files/it_works_native_json_array_impl.sql renamed to tests/sql_test_files/it_works_fetch_native_json_array_impl.sql

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,11 @@
1+
set url = 'http://localhost:' || $echo_port || '/post';
12
set res = sqlpage.fetch(json_object(
23
'method', 'POST',
3-
'url', 'http://localhost:62802/post',
4+
'url', $url,
45
'headers', json_object('x-custom', '1'),
56
'body', json_array('hello', 'world')
67
));
7-
set expected = 'POST /post|accept-encoding: br, gzip, deflate, zstd|content-length: 17|content-type: application/json|host: localhost:62802|user-agent: sqlpage|x-custom: 1|["hello","world"]';
8+
set expected = 'POST /post|accept-encoding: br, gzip, deflate, zstd|content-length: 17|content-type: application/json|host: localhost:' || $echo_port || '|user-agent: sqlpage|x-custom: 1|["hello","world"]';
89
select 'text' as component,
910
case $res
1011
when $expected then 'It works !'
Lines changed: 6 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,12 @@
1-
set res = sqlpage.fetch('{
2-
"method": "POST",
3-
"url": "http://localhost:62802/post",
4-
"headers": {"x-custom": "1"},
5-
"body": {"hello": "world"}
6-
}');
7-
set expected = 'POST /post|accept-encoding: br, gzip, deflate, zstd|content-length: 18|content-type: application/json|host: localhost:62802|user-agent: sqlpage|x-custom: 1|{"hello": "world"}';
1+
set url = 'http://localhost:' || $echo_port || '/post';
2+
set fetch_request = '{"method": "POST", "url": "' || $url || '", "headers": {"x-custom": "1"}, "body": {"hello": "world"}}';
3+
set res = sqlpage.fetch($fetch_request);
4+
set expected = 'POST /post|accept-encoding: br, gzip, deflate, zstd|content-length: 18|content-type: application/json|host: localhost:' || $echo_port || '|user-agent: sqlpage|x-custom: 1|{"hello": "world"}';
85
select 'text' as component,
96
case $res
107
when $expected then 'It works !'
118
else 'It failed ! Expected:
12-
' || $expected || '
9+
' || COALESCE($expected, 'null') || '
1310
Got:
14-
' || $res
11+
' || COALESCE($res, 'null')
1512
end as contents;

tests/sql_test_files/it_works_fetch_simple.sql

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1-
set res = sqlpage.fetch('http://localhost:62802/hello_world')
1+
set url = 'http://localhost:' || $echo_port || '/hello_world';
2+
set res = sqlpage.fetch($url);
23
select 'text' as component,
34
case
45
when $res LIKE 'GET /hello_world%' then 'It works !'

tests/sql_test_files/it_works_fetch_with_meta_simple.sql

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,12 @@
1-
set res = sqlpage.fetch_with_meta('{
1+
set url = 'http://localhost:' || $echo_port || '/hello_world';
2+
set fetch_req = '{
23
"method": "PUT",
3-
"url": "http://localhost:62802/hello_world",
4+
"url": "' || $url || '",
45
"headers": {
56
"user-agent": "myself"
67
}
7-
}');
8+
}';
9+
set res = sqlpage.fetch_with_meta($fetch_req);
810

911
select 'text' as component,
1012
case
Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
1+
set actual = sqlpage.link('', sqlpage.variables('get'));
2+
set expected = '?x=1';
13
SELECT
24
'text' AS component,
3-
CASE sqlpage.link('', sqlpage.variables('get'))
4-
WHEN '?x=1' THEN
5+
CASE $actual
6+
WHEN $expected THEN
57
'It works !'
68
ELSE
7-
'Expected "?x=1"'
9+
'Expected ' || COALESCE($expected, 'null') || ' but got ' || COALESCE($actual, 'null')
810
END AS contents
911
;

tests/sql_test_files/mod.rs

Lines changed: 28 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -12,13 +12,13 @@ async fn run_all_sql_test_files() {
1212
// Create a shutdown channel for the echo server
1313
let (shutdown_tx, shutdown_rx) = oneshot::channel();
1414
// Start echo server once for all tests
15-
let echo_handle = crate::common::start_echo_server(shutdown_rx);
15+
let (echo_handle, port) = crate::common::start_echo_server(shutdown_rx);
1616

1717
// Wait for echo server to be ready
18-
wait_for_echo_server().await;
18+
wait_for_echo_server(port).await;
1919

2020
for test_file in test_files {
21-
let test_result = run_sql_test(&test_file, &app_data, &echo_handle).await;
21+
let test_result = run_sql_test(&test_file, &app_data, &echo_handle, port).await;
2222
assert_test_result(test_result, &test_file);
2323
}
2424

@@ -31,13 +31,13 @@ async fn run_all_sql_test_files() {
3131
}
3232
}
3333

34-
async fn wait_for_echo_server() {
34+
async fn wait_for_echo_server(port: u16) {
3535
let client = awc::Client::default();
3636
let start = std::time::Instant::now();
3737
let timeout = Duration::from_secs(5);
3838

3939
while start.elapsed() < timeout {
40-
match client.get("http://localhost:62802/").send().await {
40+
match client.get(format!("http://localhost:{port}/")).send().await {
4141
Ok(_) => return,
4242
Err(_) => {
4343
tokio::time::sleep(Duration::from_millis(100)).await;
@@ -64,13 +64,20 @@ fn get_sql_test_files() -> Vec<std::path::PathBuf> {
6464
.collect()
6565
}
6666

67+
use std::fmt::Write;
68+
6769
async fn run_sql_test(
6870
test_file: &std::path::Path,
6971
app_data: &actix_web::web::Data<AppState>,
7072
_echo_handle: &JoinHandle<()>,
73+
port: u16,
7174
) -> anyhow::Result<String> {
7275
let test_file_path = test_file.to_string_lossy().replace('\\', "/");
73-
let req_str = format!("/{test_file_path}?x=1");
76+
let mut query_params = "x=1".to_string();
77+
if test_file_path.contains("fetch") {
78+
write!(query_params, "&echo_port={port}").unwrap();
79+
}
80+
let req_str = format!("/{test_file_path}?{query_params}");
7481

7582
let resp = tokio::time::timeout(
7683
Duration::from_secs(5),
@@ -114,11 +121,23 @@ fn assert_html_response(body: &str, test_file: &std::path::Path) {
114121
}
115122

116123
fn assert_it_works_tests(body: &str, lowercase_body: &str, test_file: &std::path::Path) {
124+
if body.contains("<code class=\"sqlpage-error-description\">") {
125+
let error_desc = body
126+
.split("<code class=\"sqlpage-error-description\">")
127+
.nth(1)
128+
.and_then(|s| s.split("</code>").next())
129+
.unwrap_or("Unknown error");
130+
panic!(
131+
"\n\n❌ TEST FAILED: {} ❌\n\nFull Response:\n{}\n\nError Description: {}\n",
132+
test_file.display(),
133+
error_desc,
134+
body
135+
);
136+
}
137+
117138
assert!(
118139
body.contains("It works !"),
119-
"{}\n{}\nexpected to contain: It works !",
120-
test_file.display(),
121-
body
140+
"{body}\n❌ Error in file {test_file:?} ❌\n",
122141
);
123142
assert!(
124143
!lowercase_body.contains("error"),

0 commit comments

Comments
 (0)