Skip to content
This repository was archived by the owner on Oct 10, 2025. It is now read-only.

Commit 80a5bd8

Browse files
committed
Add test for add/read/delete start_list_change_request
1 parent a3e2ab1 commit 80a5bd8

5 files changed

Lines changed: 174 additions & 44 deletions

File tree

src/auth.rs

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,17 @@ pub struct UserInfo {
1515
pub(crate) email: String,
1616
picture: String,
1717
}
18+
19+
impl UserInfo {
20+
#[cfg(test)]
21+
pub fn create_test_user_info() -> UserInfo {
22+
UserInfo{
23+
name: "John Doe".to_string(),
24+
email: "john@doe".to_string(),
25+
picture: "".to_string(),
26+
}
27+
}
28+
}
1829
impl TryFrom<&GoogleUserInfo> for UserInfo {
1930
type Error = anyhow::Error;
2031

@@ -46,12 +57,7 @@ pub fn generate_random_string(len: usize) -> String {
4657
})
4758
.collect()
4859
}
49-
// #[test]
50-
// fn test_generate_random_string() {
51-
// for _i in 0 .. 50 {
52-
// println!("{}", generate_random_string(10));
53-
// }
54-
// }
60+
5561
pub const QX_SESSION_ID: &str = "qx_session_id";
5662

5763
/// User information to be retrieved from the Google People API.

src/changes.rs

Lines changed: 30 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -135,7 +135,7 @@ pub async fn add_change(
135135
VALUES (?, ?, ?, ?, ?, ?, ?, ?) RETURNING id")
136136
.bind(&change.source)
137137
.bind(&change.data_type)
138-
.bind(&change.data_id)
138+
.bind(change.data_id)
139139
.bind(&change.data)
140140
.bind(&change.note)
141141
.bind(&change.user_id)
@@ -147,14 +147,21 @@ pub async fn add_change(
147147
Ok(id.0)
148148
}
149149

150-
#[get("/event/<event_id>/changes?<from_id>")]
151-
async fn get_changes(event_id: EventId, from_id: Option<i64>, session_id: MaybeSessionId, state: &State<SharedQxState>, gdb: &State<DbPool>) -> Result<Template, Custom<String>> {
150+
#[get("/event/<event_id>/changes?<from_id>&<limit>")]
151+
async fn get_changes(
152+
event_id: EventId,
153+
from_id: Option<i64>,
154+
limit: Option<i64>,
155+
session_id: MaybeSessionId,
156+
state: &State<SharedQxState>,
157+
gdb: &State<DbPool>
158+
) -> Result<Template, Custom<String>> {
152159
let event = load_event_info(event_id, gdb).await?;
153160
let user = user_info_opt(session_id.0.as_ref(), state).await.map_err(anyhow_to_custom_error)?;
154-
let from_id = from_id.unwrap_or(0);
155161
let edb = get_event_db(event_id, state).await.map_err(anyhow_to_custom_error)?;
156-
let records: Vec<ChangesRecord> = sqlx::query_as("SELECT * FROM changes WHERE id>=? ORDER BY created DESC LIMIT 1000")
157-
.bind(from_id)
162+
let records: Vec<ChangesRecord> = sqlx::query_as("SELECT * FROM changes WHERE id>=? ORDER BY created DESC LIMIT ?")
163+
.bind(from_id.unwrap_or(0))
164+
.bind(limit.unwrap_or(100))
158165
.fetch_all(&edb)
159166
.await
160167
.map_err(sqlx_to_custom_error)?;
@@ -192,10 +199,10 @@ pub async fn add_run_update_request_change(
192199
note: Option<&str>,
193200
data: Json<RunsRecord>,
194201
state: &State<SharedQxState>
195-
) -> Result<(), Custom<String>> {
202+
) -> Result<Json<i64>, Custom<String>> {
196203
let user = user_info(&session_id, state).await?;
197204
let data = ChangeData::RunUpdateRequest(data.into_inner());
198-
add_change(event_id, ChangesRecord{
205+
let change_id = add_change(event_id, ChangesRecord{
199206
id: 0,
200207
source: "www".to_string(),
201208
data_type: DataType::RunUpdateRequest,
@@ -207,7 +214,7 @@ pub async fn add_run_update_request_change(
207214
note: note.map(|s| s.to_string()),
208215
}, state).await.map_err(anyhow_to_custom_error)?;
209216
//state.read().await.broadcast_runs_change((event_id, data_id, data)).await.map_err(anyhow_to_custom_error)?;
210-
Ok(())
217+
Ok(Json(change_id))
211218
}
212219

213220
#[post("/api/event/current/changes/run-updated?<run_id>", data = "<change>")]
@@ -326,8 +333,15 @@ async fn changes_sse(event_id: EventId, state: &State<SharedQxState>) -> EventSt
326333
}
327334
}
328335

329-
#[get("/api/event/<event_id>/changes?<from_id>&<data_type>&<status>")]
330-
async fn api_changes_get(event_id: EventId, from_id: Option<i64>, data_type: Option<&str>, status: Option<&str>, state: &State<SharedQxState>) -> Result<Json<Vec<ChangesRecord>>, Custom<String>> {
336+
#[get("/api/event/<event_id>/changes?<from_id>&<limit>&<data_type>&<status>")]
337+
async fn api_changes_get(
338+
event_id: EventId,
339+
from_id: Option<i64>,
340+
limit: Option<i64>,
341+
data_type: Option<&str>,
342+
status: Option<&str>,
343+
state: &State<SharedQxState>
344+
) -> Result<Json<Vec<ChangesRecord>>, Custom<String>> {
331345
let edb = get_event_db(event_id, state).await.map_err(anyhow_to_custom_error)?;
332346

333347
let mut query_builder = QueryBuilder::new("SELECT * FROM changes WHERE id>=");
@@ -341,7 +355,11 @@ async fn api_changes_get(event_id: EventId, from_id: Option<i64>, data_type: Opt
341355
query_builder.push_bind(status);
342356
}
343357
query_builder.push(" ORDER BY created");
344-
358+
if let Some(limit) = limit {
359+
query_builder.push(" LIMIT ");
360+
query_builder.push_bind(limit);
361+
}
362+
345363
let query = query_builder.build_query_as::<ChangesRecord>();
346364
let records: Vec<_> = query.fetch_all(&edb).await.map_err(sqlx_to_custom_error)?;
347365
// info!("records: {:?}", records);

src/event.rs

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -88,8 +88,8 @@ pub(crate) async fn save_event(event: &EventRecord, db: &State<DbPool>) -> anyho
8888
query("UPDATE events SET name=?, place=?, stage=?, stage_count=?, start_time=? WHERE id=?")
8989
.bind(&event.name)
9090
.bind(&event.place)
91-
.bind(&event.stage)
92-
.bind(&event.stage_count)
91+
.bind(event.stage)
92+
.bind(event.stage_count)
9393
.bind(event.start_time.0)
9494
// .bind(&event.time_zone)
9595
.bind(event.id)
@@ -103,8 +103,8 @@ pub(crate) async fn save_event(event: &EventRecord, db: &State<DbPool>) -> anyho
103103
)
104104
.bind(&event.name)
105105
.bind(&event.place)
106-
.bind(&event.stage)
107-
.bind(&event.stage_count)
106+
.bind(event.stage)
107+
.bind(event.stage_count)
108108
.bind(event.start_time.0)
109109
.bind(&event.api_token.0)
110110
.bind(&event.owner)
@@ -479,14 +479,16 @@ pub async fn import_runs(edb: &SqlitePool) -> anyhow::Result<()> {
479479
Ok(())
480480
}
481481

482-
pub(crate) const TEST_API_TOKEN: &str = "plelababamak";
482+
pub(crate) const DEMO_API_TOKEN: &str = "plelababamak";
483+
#[cfg(test)]
484+
pub(crate) const TEST_SESSION_ID: &str = "123abc";
483485

484486
#[get("/event/create-demo")]
485487
async fn create_demo_event(state: &State<SharedQxState>, gdb: &State<DbPool>) -> Result<Redirect, Custom<String>> {
486488
let mut event_info = EventRecord::new("fanda.vacek@gmail.com");
487489
event_info.name = String::from("Demo event");
488490
event_info.place = String::from("Deep forest 42");
489-
event_info.api_token = QxApiToken(String::from(TEST_API_TOKEN));
491+
event_info.api_token = QxApiToken(String::from(DEMO_API_TOKEN));
490492
let event_id = save_event(&event_info, gdb).await.map_err(|e| Custom(Status::BadRequest, e.to_string()))?;
491493
{
492494
// upload demo start list

src/main.rs

Lines changed: 21 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,8 @@ use async_broadcast::{broadcast};
2525
use rocket_dyn_templates::handlebars::{Handlebars, Helper};
2626
use sqlx::sqlite::{SqliteArgumentValue};
2727

28+
#[cfg(test)]
29+
use crate::event::TEST_SESSION_ID;
2830
#[cfg(test)]
2931
mod tests;
3032
mod db;
@@ -62,7 +64,12 @@ impl<'r> request::FromRequest<'r> for QxSessionId {
6264
.guard::<&CookieJar<'_>>()
6365
.await
6466
.expect("request cookies");
65-
if let Some(cookie) = cookies.get_private(QX_SESSION_ID) {
67+
if cfg!(test) {
68+
// didn't find a way, how to use private cookies with tests
69+
if let Some(cookie) = cookies.get(QX_SESSION_ID) {
70+
return request::Outcome::Success(Self(cookie.value().to_string()));
71+
}
72+
} else if let Some(cookie) = cookies.get_private(QX_SESSION_ID) {
6673
return request::Outcome::Success(Self(cookie.value().to_string()));
6774
}
6875
request::Outcome::Forward(Status::Unauthorized)
@@ -224,10 +231,8 @@ fn rocket() -> _ {
224231
if left <= right {
225232
out.write("1")?;
226233
}
227-
} else {
228-
if left > right {
229-
out.write("1")?;
230-
}
234+
} else if left > right {
235+
out.write("1")?;
231236
}
232237
Ok(())
233238
}));
@@ -255,7 +260,16 @@ fn rocket() -> _ {
255260
let db_path = figment.extract_inner::<String>("db_path").expect("db_path");
256261

257262
let cfg = AppConfig{ server_address, server_port, db_path };
258-
let state = QxState::new(cfg);
259-
rocket.manage(SharedQxState::new(state))
263+
#[cfg(test)]
264+
{
265+
let mut state = QxState::new(cfg);
266+
state.sessions.insert(QxSessionId(TEST_SESSION_ID.into()), QxSession { user_info: UserInfo::create_test_user_info() });
267+
rocket.manage(SharedQxState::new(state))
268+
}
269+
#[cfg(not(test))]
270+
{
271+
let state = QxState::new(cfg);
272+
rocket.manage(SharedQxState::new(state))
273+
}
260274
}
261275

0 commit comments

Comments
 (0)