Skip to content

Commit f54f357

Browse files
[ci]: bugfix in post api test
1 parent 9426c3e commit f54f357

File tree

5 files changed

+38
-29
lines changed

5 files changed

+38
-29
lines changed

src/components/blob_storage.rs

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -9,15 +9,15 @@ const COMMENTS_DIR: &str = "comments";
99

1010
pub struct LocalStorageDriver {
1111
blob_path: PathBuf,
12-
saved: bool,
12+
try_saving: bool,
1313
confirm: bool,
1414
}
1515

1616
impl LocalStorageDriver {
1717
pub fn new(blob_path: PathBuf) -> Self {
1818
Self {
1919
blob_path,
20-
saved: false,
20+
try_saving: false,
2121
confirm: false,
2222
}
2323
}
@@ -30,12 +30,12 @@ impl LocalStorageDriver {
3030
Ok(())
3131
}
3232

33-
pub fn confirm(&mut self) {
33+
pub fn confirm_saved(&mut self) {
3434
self.confirm = true;
3535
}
3636

3737
pub fn post_save_content(&mut self, file_name: &str, content: &str) -> std::io::Result<()> {
38-
self.saved = true;
38+
self.try_saving = true;
3939
let path = self.blob_path.join(file_name);
4040
let mut file = std::fs::File::create(path)?;
4141
file.write_all(content.as_bytes())?;
@@ -47,7 +47,7 @@ impl LocalStorageDriver {
4747
file_name: &str,
4848
attachment: TempFile,
4949
) -> std::io::Result<()> {
50-
self.saved = true;
50+
self.try_saving = true;
5151
let save_path = self.blob_path.join(file_name);
5252
fs::copy(attachment.file.path(), save_path)?;
5353
Ok(())
@@ -61,7 +61,7 @@ impl LocalStorageDriver {
6161
// TODO: TEST drop log ok
6262
impl Drop for LocalStorageDriver {
6363
fn drop(&mut self) {
64-
if self.saved && !self.confirm {
64+
if self.try_saving && !self.confirm {
6565
if let Err(e) = fs::remove_dir_all(&self.blob_path) {
6666
tracing::error!("Failed to clean up directory {:?}: {:?}", self.blob_path, e);
6767
}

src/routes/posts/mod.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -58,9 +58,9 @@ async fn read_file_to_string(path: &Path) -> Result<String, PostsError> {
5858
async fn locate_post_content_file(blob: &str, blob_storage: &BlobStorage) -> Option<PathBuf> {
5959
let post_dir = blob_storage.single_post_dir(blob);
6060

61-
let mut entries = tokio::fs::read_dir(post_dir)
61+
let mut entries = tokio::fs::read_dir(post_dir.clone())
6262
.await
63-
.context("Failed to read post directory")
63+
.context(format!("Failed to read post directory: {post_dir:?}"))
6464
.inspect_err(|e| tracing::error!("{e:?}"))
6565
.ok()?;
6666

@@ -118,7 +118,7 @@ fn persist_post_and_attachments(
118118
}
119119
}
120120

121-
local_driver.confirm();
121+
local_driver.confirm_saved();
122122

123123
Ok(())
124124
}

src/routes/posts/upload.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@ pub async fn upload_post(
6868
.context("Failed to commit transaction")
6969
.inspect_err(|e| tracing::error!("{e:?}"))?;
7070

71-
Ok(HttpResponse::Ok().json(serde_json::json!(
71+
Ok(HttpResponse::Created().json(serde_json::json!(
7272
{
7373
"slug": uniq_slug,
7474
"id": id

tests/api/posts/mod.rs

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ use pine_tails::domain::posts::{Post, PostBuilder};
99

1010
use crate::utils::TestApp;
1111

12-
async fn insert_post(pool: &PgPool, post: &Post) {
12+
async fn insert_post(pool: &PgPool, post: &Post) -> uuid::Uuid {
1313
let id = uuid::Uuid::new_v4();
1414
sqlx::query!(
1515
"INSERT INTO posts (id, slug, title, content, date, blob) VALUES ($1, $2, $3, $4, $5, $6)",
@@ -23,6 +23,8 @@ async fn insert_post(pool: &PgPool, post: &Post) {
2323
.execute(pool)
2424
.await
2525
.unwrap();
26+
27+
id
2628
}
2729

2830
#[tokio::test]
@@ -32,8 +34,16 @@ async fn get_post_with_existing_slug_should_return_ok() {
3234
.with_title("hello there")
3335
.with_content("some content");
3436
let api_addr = format!("{}/posts/slug/hello-there", app.address);
37+
let post = pb.build();
3538

36-
insert_post(&app.db_pool, &pb.build()).await;
39+
let id = insert_post(&app.db_pool, &post).await;
40+
41+
let mut local_driver = app.blob_storage.post_storage_driver(&id.to_string());
42+
local_driver.try_init().unwrap();
43+
local_driver
44+
.post_save_content("hello-there.md", &post.content)
45+
.unwrap();
46+
local_driver.confirm_saved();
3747

3848
let response = app
3949
.client

tests/api/utils/mod.rs

Lines changed: 16 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ pub mod email_service_mocking;
33
use base64::prelude::*;
44
use mail_parser::MessageParser;
55
use once_cell::sync::Lazy;
6+
use pine_tails::components::blob_storage::BlobStorage;
67
use reqwest::Url;
78
use secrecy::ExposeSecret;
89
use sqlx::{Connection, Executor, PgConnection, PgPool};
@@ -17,25 +18,14 @@ use pine_tails::startup::prepare::{
1718
use pine_tails::telemetry::{get_subscriber, init_subscriber, LoggerFormat, LoggerOutbound};
1819

1920
static TRACING: Lazy<()> = Lazy::new(|| {
20-
let use_test_log = std::env::var("TEST_LOG").map_or(false, |x| {
21-
matches!(x.as_str(), "1" | "true" | "yes" | "TRUE")
22-
});
23-
24-
let valid_levels = ["info", "error", "trace", "warn", "debug"];
25-
let level = std::env::var("LOG_LEVEL").ok();
26-
let log_level = level
27-
.as_deref()
28-
.filter(|lvl| valid_levels.contains(lvl))
29-
.unwrap_or("error");
21+
let use_test_log = std::env::var("TEST_LOG")
22+
.is_ok_and(|x| matches!(x.as_str(), "1" | "true" | "yes" | "TRUE"));
3023

3124
let format = LoggerFormat::Pretty;
3225

3326
if use_test_log {
34-
let subscriber = get_subscriber(
35-
log_level.into(),
36-
format,
37-
LoggerOutbound::new(std::io::stderr),
38-
);
27+
let subscriber =
28+
get_subscriber("error".into(), format, LoggerOutbound::new(std::io::stderr));
3929
init_subscriber(subscriber);
4030
} else {
4131
let subscriber = get_subscriber("debug".into(), format, LoggerOutbound::new(std::io::sink));
@@ -45,11 +35,15 @@ static TRACING: Lazy<()> = Lazy::new(|| {
4535

4636
pub struct TestApp {
4737
pub address: String,
48-
pub db_pool: PgPool,
49-
pub email_server: MockServer,
5038
pub email_api: String,
5139
pub refresh_api: String,
5240
pub client: reqwest::Client,
41+
// NOTE: there are two connections to database
42+
// one is this db_pool, acting as backdoor of our TEST
43+
// the other is created when starting the web server
44+
pub db_pool: PgPool,
45+
pub email_server: MockServer,
46+
pub blob_storage: BlobStorage,
5347
}
5448

5549
pub struct ConfirmationLinks {
@@ -83,6 +77,10 @@ impl TestApp {
8377
temp_config
8478
};
8579

80+
let span = tracing::info_span!("Spawn test server");
81+
let _enter = span.enter();
82+
tracing::info!("Spawning server with configuration: {configuration:#?}");
83+
8684
let db_pool = Self::pool_to_uniq_database(&configuration.database).await;
8785
let test_app = TestApp {
8886
address,
@@ -93,6 +91,7 @@ impl TestApp {
9391
email_api,
9492
refresh_api: token_api,
9593
client: reqwest::Client::new(),
94+
blob_storage: prepare_blob_storage(&configuration).unwrap(),
9695
};
9796

9897
let kits = Kits::new(

0 commit comments

Comments
 (0)