refactor: extract inline test modules to separate files
This commit is contained in:
@@ -58,24 +58,4 @@ impl ThoughtNote {
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn note_serializes_with_public_audience() {
|
||||
let note = ThoughtNote::new_public(
|
||||
"https://example.com/thoughts/1".parse().unwrap(),
|
||||
"https://example.com/users/alice".parse().unwrap(),
|
||||
"Hello world".to_string(),
|
||||
chrono::Utc::now(),
|
||||
None,
|
||||
false,
|
||||
None,
|
||||
"https://example.com/users/alice/followers".parse().unwrap(),
|
||||
);
|
||||
let json = serde_json::to_string(¬e).unwrap();
|
||||
assert!(json.contains(AS_PUBLIC));
|
||||
assert!(json.contains("Hello world"));
|
||||
assert!(json.contains("\"url\""));
|
||||
}
|
||||
}
|
||||
mod tests;
|
||||
19
crates/adapters/activitypub/src/note/tests.rs
Normal file
19
crates/adapters/activitypub/src/note/tests.rs
Normal file
@@ -0,0 +1,19 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn note_serializes_with_public_audience() {
|
||||
let note = ThoughtNote::new_public(
|
||||
"https://example.com/thoughts/1".parse().unwrap(),
|
||||
"https://example.com/users/alice".parse().unwrap(),
|
||||
"Hello world".to_string(),
|
||||
chrono::Utc::now(),
|
||||
None,
|
||||
false,
|
||||
None,
|
||||
"https://example.com/users/alice/followers".parse().unwrap(),
|
||||
);
|
||||
let json = serde_json::to_string(¬e).unwrap();
|
||||
assert!(json.contains(AS_PUBLIC));
|
||||
assert!(json.contains("Hello world"));
|
||||
assert!(json.contains("\"url\""));
|
||||
}
|
||||
@@ -33,25 +33,4 @@ impl ThoughtsUrls {
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn user_url_format() {
|
||||
let urls = ThoughtsUrls::new("https://example.com");
|
||||
assert_eq!(
|
||||
urls.user_url("alice").as_str(),
|
||||
"https://example.com/users/alice"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn thought_url_format() {
|
||||
let urls = ThoughtsUrls::new("https://example.com");
|
||||
let id = uuid::Uuid::nil();
|
||||
assert!(urls
|
||||
.thought_url(id)
|
||||
.as_str()
|
||||
.starts_with("https://example.com/thoughts/"));
|
||||
}
|
||||
}
|
||||
mod tests;
|
||||
20
crates/adapters/activitypub/src/urls/tests.rs
Normal file
20
crates/adapters/activitypub/src/urls/tests.rs
Normal file
@@ -0,0 +1,20 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn user_url_format() {
|
||||
let urls = ThoughtsUrls::new("https://example.com");
|
||||
assert_eq!(
|
||||
urls.user_url("alice").as_str(),
|
||||
"https://example.com/users/alice"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn thought_url_format() {
|
||||
let urls = ThoughtsUrls::new("https://example.com");
|
||||
let id = uuid::Uuid::nil();
|
||||
assert!(urls
|
||||
.thought_url(id)
|
||||
.as_str()
|
||||
.starts_with("https://example.com/thoughts/"));
|
||||
}
|
||||
@@ -1,89 +0,0 @@
|
||||
use async_trait::async_trait;
|
||||
use domain::{
|
||||
errors::DomainError,
|
||||
ports::{ApiKeyRepository, ApiKeyService},
|
||||
value_objects::UserId,
|
||||
};
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::sync::Arc;
|
||||
|
||||
pub struct ApiKeyServiceImpl {
|
||||
repo: Arc<dyn ApiKeyRepository>,
|
||||
}
|
||||
|
||||
impl ApiKeyServiceImpl {
|
||||
pub fn new(repo: Arc<dyn ApiKeyRepository>) -> Self {
|
||||
Self { repo }
|
||||
}
|
||||
|
||||
fn hash(raw: &str) -> String {
|
||||
hex::encode(Sha256::digest(raw.as_bytes()))
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl ApiKeyService for ApiKeyServiceImpl {
|
||||
async fn validate_key(&self, raw_key: &str) -> Result<Option<UserId>, DomainError> {
|
||||
let hash = Self::hash(raw_key);
|
||||
Ok(self.repo.find_by_hash(&hash).await?.map(|k| k.user_id))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use async_trait::async_trait;
|
||||
use chrono::Utc;
|
||||
use domain::{
|
||||
errors::DomainError,
|
||||
models::api_key::ApiKey,
|
||||
ports::ApiKeyRepository,
|
||||
value_objects::{ApiKeyId, UserId},
|
||||
};
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
struct FakeApiKeyRepo(Mutex<Vec<ApiKey>>);
|
||||
|
||||
#[async_trait]
|
||||
impl ApiKeyRepository for FakeApiKeyRepo {
|
||||
async fn save(&self, key: &ApiKey) -> Result<(), DomainError> {
|
||||
self.0.lock().unwrap().push(key.clone());
|
||||
Ok(())
|
||||
}
|
||||
async fn find_by_hash(&self, hash: &str) -> Result<Option<ApiKey>, DomainError> {
|
||||
Ok(self.0.lock().unwrap().iter().find(|k| k.key_hash == hash).cloned())
|
||||
}
|
||||
async fn list_for_user(&self, _uid: &UserId) -> Result<Vec<ApiKey>, DomainError> {
|
||||
Ok(vec![])
|
||||
}
|
||||
async fn delete(&self, _id: &ApiKeyId, _uid: &UserId) -> Result<(), DomainError> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn validate_known_key_returns_user_id() {
|
||||
let uid = UserId::new();
|
||||
let raw = "super-secret-key";
|
||||
let hash = ApiKeyServiceImpl::hash(raw);
|
||||
let key = ApiKey {
|
||||
id: ApiKeyId::new(),
|
||||
user_id: uid.clone(),
|
||||
key_hash: hash,
|
||||
name: "test".into(),
|
||||
created_at: Utc::now(),
|
||||
};
|
||||
let repo = Arc::new(FakeApiKeyRepo(Mutex::new(vec![key])));
|
||||
let svc = ApiKeyServiceImpl::new(repo);
|
||||
let result = svc.validate_key(raw).await.unwrap();
|
||||
assert_eq!(result.unwrap().as_uuid(), uid.as_uuid());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn validate_unknown_key_returns_none() {
|
||||
let repo = Arc::new(FakeApiKeyRepo(Mutex::new(vec![])));
|
||||
let svc = ApiKeyServiceImpl::new(repo);
|
||||
let result = svc.validate_key("unknown-key").await.unwrap();
|
||||
assert!(result.is_none());
|
||||
}
|
||||
}
|
||||
33
crates/adapters/auth/src/api_key_service/mod.rs
Normal file
33
crates/adapters/auth/src/api_key_service/mod.rs
Normal file
@@ -0,0 +1,33 @@
|
||||
use async_trait::async_trait;
|
||||
use domain::{
|
||||
errors::DomainError,
|
||||
ports::{ApiKeyRepository, ApiKeyService},
|
||||
value_objects::UserId,
|
||||
};
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::sync::Arc;
|
||||
|
||||
pub struct ApiKeyServiceImpl {
|
||||
repo: Arc<dyn ApiKeyRepository>,
|
||||
}
|
||||
|
||||
impl ApiKeyServiceImpl {
|
||||
pub fn new(repo: Arc<dyn ApiKeyRepository>) -> Self {
|
||||
Self { repo }
|
||||
}
|
||||
|
||||
fn hash(raw: &str) -> String {
|
||||
hex::encode(Sha256::digest(raw.as_bytes()))
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl ApiKeyService for ApiKeyServiceImpl {
|
||||
async fn validate_key(&self, raw_key: &str) -> Result<Option<UserId>, DomainError> {
|
||||
let hash = Self::hash(raw_key);
|
||||
Ok(self.repo.find_by_hash(&hash).await?.map(|k| k.user_id))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
55
crates/adapters/auth/src/api_key_service/tests.rs
Normal file
55
crates/adapters/auth/src/api_key_service/tests.rs
Normal file
@@ -0,0 +1,55 @@
|
||||
use super::*;
|
||||
use async_trait::async_trait;
|
||||
use chrono::Utc;
|
||||
use domain::{
|
||||
errors::DomainError,
|
||||
models::api_key::ApiKey,
|
||||
ports::ApiKeyRepository,
|
||||
value_objects::{ApiKeyId, UserId},
|
||||
};
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
struct FakeApiKeyRepo(Mutex<Vec<ApiKey>>);
|
||||
|
||||
#[async_trait]
|
||||
impl ApiKeyRepository for FakeApiKeyRepo {
|
||||
async fn save(&self, key: &ApiKey) -> Result<(), DomainError> {
|
||||
self.0.lock().unwrap().push(key.clone());
|
||||
Ok(())
|
||||
}
|
||||
async fn find_by_hash(&self, hash: &str) -> Result<Option<ApiKey>, DomainError> {
|
||||
Ok(self.0.lock().unwrap().iter().find(|k| k.key_hash == hash).cloned())
|
||||
}
|
||||
async fn list_for_user(&self, _uid: &UserId) -> Result<Vec<ApiKey>, DomainError> {
|
||||
Ok(vec![])
|
||||
}
|
||||
async fn delete(&self, _id: &ApiKeyId, _uid: &UserId) -> Result<(), DomainError> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn validate_known_key_returns_user_id() {
|
||||
let uid = UserId::new();
|
||||
let raw = "super-secret-key";
|
||||
let hash = ApiKeyServiceImpl::hash(raw);
|
||||
let key = ApiKey {
|
||||
id: ApiKeyId::new(),
|
||||
user_id: uid.clone(),
|
||||
key_hash: hash,
|
||||
name: "test".into(),
|
||||
created_at: Utc::now(),
|
||||
};
|
||||
let repo = Arc::new(FakeApiKeyRepo(Mutex::new(vec![key])));
|
||||
let svc = ApiKeyServiceImpl::new(repo);
|
||||
let result = svc.validate_key(raw).await.unwrap();
|
||||
assert_eq!(result.unwrap().as_uuid(), uid.as_uuid());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn validate_unknown_key_returns_none() {
|
||||
let repo = Arc::new(FakeApiKeyRepo(Mutex::new(vec![])));
|
||||
let svc = ApiKeyServiceImpl::new(repo);
|
||||
let result = svc.validate_key("unknown-key").await.unwrap();
|
||||
assert!(result.is_none());
|
||||
}
|
||||
@@ -93,31 +93,4 @@ impl PasswordHasher for Argon2PasswordHasher {
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use domain::ports::AuthService;
|
||||
|
||||
#[test]
|
||||
fn generate_and_validate_token() {
|
||||
let svc = JwtAuthService::new("a-secret-that-is-at-least-32-bytes!!".into(), 3600);
|
||||
let id = UserId::new();
|
||||
let tok = svc.generate_token(&id).unwrap();
|
||||
let parsed = svc.validate_token(&tok.token).unwrap();
|
||||
assert_eq!(parsed.as_uuid(), id.as_uuid());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_token_returns_unauthorized() {
|
||||
let svc = JwtAuthService::new("a-secret-that-is-at-least-32-bytes!!".into(), 3600);
|
||||
let err = svc.validate_token("not.a.token").unwrap_err();
|
||||
assert!(matches!(err, DomainError::Unauthorized));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn hash_and_verify() {
|
||||
let hasher = Argon2PasswordHasher;
|
||||
let hash = hasher.hash("mypassword").await.unwrap();
|
||||
assert!(hasher.verify("mypassword", &hash).await.unwrap());
|
||||
assert!(!hasher.verify("wrongpassword", &hash).await.unwrap());
|
||||
}
|
||||
}
|
||||
mod tests;
|
||||
|
||||
26
crates/adapters/auth/src/tests.rs
Normal file
26
crates/adapters/auth/src/tests.rs
Normal file
@@ -0,0 +1,26 @@
|
||||
use super::*;
|
||||
use domain::ports::AuthService;
|
||||
|
||||
#[test]
|
||||
fn generate_and_validate_token() {
|
||||
let svc = JwtAuthService::new("a-secret-that-is-at-least-32-bytes!!".into(), 3600);
|
||||
let id = UserId::new();
|
||||
let tok = svc.generate_token(&id).unwrap();
|
||||
let parsed = svc.validate_token(&tok.token).unwrap();
|
||||
assert_eq!(parsed.as_uuid(), id.as_uuid());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_token_returns_unauthorized() {
|
||||
let svc = JwtAuthService::new("a-secret-that-is-at-least-32-bytes!!".into(), 3600);
|
||||
let err = svc.validate_token("not.a.token").unwrap_err();
|
||||
assert!(matches!(err, DomainError::Unauthorized));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn hash_and_verify() {
|
||||
let hasher = Argon2PasswordHasher;
|
||||
let hash = hasher.hash("mypassword").await.unwrap();
|
||||
assert!(hasher.verify("mypassword", &hash).await.unwrap());
|
||||
assert!(!hasher.verify("wrongpassword", &hash).await.unwrap());
|
||||
}
|
||||
@@ -356,91 +356,6 @@ impl TryFrom<EventPayload> for DomainEvent {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn thought_created_roundtrip() {
|
||||
let p = EventPayload::ThoughtCreated {
|
||||
thought_id: "abc".into(),
|
||||
user_id: "def".into(),
|
||||
in_reply_to_id: None,
|
||||
};
|
||||
let json = serde_json::to_string(&p).unwrap();
|
||||
let back: EventPayload = serde_json::from_str(&json).unwrap();
|
||||
assert_eq!(back.subject(), "thoughts.created");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn all_subjects_are_unique() {
|
||||
let samples: &[EventPayload] = &[
|
||||
EventPayload::ThoughtCreated {
|
||||
thought_id: "a".into(),
|
||||
user_id: "b".into(),
|
||||
in_reply_to_id: None,
|
||||
},
|
||||
EventPayload::ThoughtDeleted {
|
||||
thought_id: "a".into(),
|
||||
user_id: "b".into(),
|
||||
},
|
||||
EventPayload::ThoughtUpdated {
|
||||
thought_id: "a".into(),
|
||||
user_id: "b".into(),
|
||||
},
|
||||
EventPayload::LikeAdded {
|
||||
like_id: "a".into(),
|
||||
user_id: "b".into(),
|
||||
thought_id: "c".into(),
|
||||
},
|
||||
EventPayload::LikeRemoved {
|
||||
user_id: "b".into(),
|
||||
thought_id: "c".into(),
|
||||
},
|
||||
EventPayload::BoostAdded {
|
||||
boost_id: "a".into(),
|
||||
user_id: "b".into(),
|
||||
thought_id: "c".into(),
|
||||
},
|
||||
EventPayload::BoostRemoved {
|
||||
user_id: "b".into(),
|
||||
thought_id: "c".into(),
|
||||
},
|
||||
EventPayload::FollowRequested {
|
||||
follower_id: "a".into(),
|
||||
following_id: "b".into(),
|
||||
},
|
||||
EventPayload::FollowAccepted {
|
||||
follower_id: "a".into(),
|
||||
following_id: "b".into(),
|
||||
},
|
||||
EventPayload::FollowRejected {
|
||||
follower_id: "a".into(),
|
||||
following_id: "b".into(),
|
||||
},
|
||||
EventPayload::Unfollowed {
|
||||
follower_id: "a".into(),
|
||||
following_id: "b".into(),
|
||||
},
|
||||
EventPayload::UserBlocked {
|
||||
blocker_id: "a".into(),
|
||||
blocked_id: "b".into(),
|
||||
},
|
||||
EventPayload::UserUnblocked {
|
||||
blocker_id: "a".into(),
|
||||
blocked_id: "b".into(),
|
||||
},
|
||||
EventPayload::UserRegistered {
|
||||
user_id: "a".into(),
|
||||
},
|
||||
];
|
||||
let mut subjects: Vec<&str> = samples.iter().map(|p| p.subject()).collect();
|
||||
subjects.sort();
|
||||
subjects.dedup();
|
||||
assert_eq!(
|
||||
subjects.len(),
|
||||
samples.len(),
|
||||
"each event must have a unique subject"
|
||||
);
|
||||
}
|
||||
}
|
||||
mod tests;
|
||||
|
||||
85
crates/adapters/event-payload/src/tests.rs
Normal file
85
crates/adapters/event-payload/src/tests.rs
Normal file
@@ -0,0 +1,85 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn thought_created_roundtrip() {
|
||||
let p = EventPayload::ThoughtCreated {
|
||||
thought_id: "abc".into(),
|
||||
user_id: "def".into(),
|
||||
in_reply_to_id: None,
|
||||
};
|
||||
let json = serde_json::to_string(&p).unwrap();
|
||||
let back: EventPayload = serde_json::from_str(&json).unwrap();
|
||||
assert_eq!(back.subject(), "thoughts.created");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn all_subjects_are_unique() {
|
||||
let samples: &[EventPayload] = &[
|
||||
EventPayload::ThoughtCreated {
|
||||
thought_id: "a".into(),
|
||||
user_id: "b".into(),
|
||||
in_reply_to_id: None,
|
||||
},
|
||||
EventPayload::ThoughtDeleted {
|
||||
thought_id: "a".into(),
|
||||
user_id: "b".into(),
|
||||
},
|
||||
EventPayload::ThoughtUpdated {
|
||||
thought_id: "a".into(),
|
||||
user_id: "b".into(),
|
||||
},
|
||||
EventPayload::LikeAdded {
|
||||
like_id: "a".into(),
|
||||
user_id: "b".into(),
|
||||
thought_id: "c".into(),
|
||||
},
|
||||
EventPayload::LikeRemoved {
|
||||
user_id: "b".into(),
|
||||
thought_id: "c".into(),
|
||||
},
|
||||
EventPayload::BoostAdded {
|
||||
boost_id: "a".into(),
|
||||
user_id: "b".into(),
|
||||
thought_id: "c".into(),
|
||||
},
|
||||
EventPayload::BoostRemoved {
|
||||
user_id: "b".into(),
|
||||
thought_id: "c".into(),
|
||||
},
|
||||
EventPayload::FollowRequested {
|
||||
follower_id: "a".into(),
|
||||
following_id: "b".into(),
|
||||
},
|
||||
EventPayload::FollowAccepted {
|
||||
follower_id: "a".into(),
|
||||
following_id: "b".into(),
|
||||
},
|
||||
EventPayload::FollowRejected {
|
||||
follower_id: "a".into(),
|
||||
following_id: "b".into(),
|
||||
},
|
||||
EventPayload::Unfollowed {
|
||||
follower_id: "a".into(),
|
||||
following_id: "b".into(),
|
||||
},
|
||||
EventPayload::UserBlocked {
|
||||
blocker_id: "a".into(),
|
||||
blocked_id: "b".into(),
|
||||
},
|
||||
EventPayload::UserUnblocked {
|
||||
blocker_id: "a".into(),
|
||||
blocked_id: "b".into(),
|
||||
},
|
||||
EventPayload::UserRegistered {
|
||||
user_id: "a".into(),
|
||||
},
|
||||
];
|
||||
let mut subjects: Vec<&str> = samples.iter().map(|p| p.subject()).collect();
|
||||
subjects.sort();
|
||||
subjects.dedup();
|
||||
assert_eq!(
|
||||
subjects.len(),
|
||||
samples.len(),
|
||||
"each event must have a unique subject"
|
||||
);
|
||||
}
|
||||
@@ -109,128 +109,6 @@ impl<S: MessageSource> EventConsumer for EventConsumerAdapter<S> {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use async_trait::async_trait;
|
||||
use domain::value_objects::{ThoughtId, UserId};
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
struct SpyTransport {
|
||||
calls: Arc<Mutex<Vec<(String, Vec<u8>)>>>,
|
||||
}
|
||||
impl SpyTransport {
|
||||
fn new() -> (Self, Arc<Mutex<Vec<(String, Vec<u8>)>>>) {
|
||||
let calls = Arc::new(Mutex::new(vec![]));
|
||||
(
|
||||
Self {
|
||||
calls: calls.clone(),
|
||||
},
|
||||
calls,
|
||||
)
|
||||
}
|
||||
}
|
||||
#[async_trait]
|
||||
impl Transport for SpyTransport {
|
||||
async fn publish_bytes(&self, subject: &str, bytes: &[u8]) -> Result<(), DomainError> {
|
||||
self.calls
|
||||
.lock()
|
||||
.unwrap()
|
||||
.push((subject.to_string(), bytes.to_vec()));
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn thought_created_routes_to_correct_subject() {
|
||||
let (spy, calls) = SpyTransport::new();
|
||||
let publisher = EventPublisherAdapter::new(spy);
|
||||
publisher
|
||||
.publish(&DomainEvent::ThoughtCreated {
|
||||
thought_id: ThoughtId::new(),
|
||||
user_id: UserId::new(),
|
||||
in_reply_to_id: None,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
let calls = calls.lock().unwrap();
|
||||
assert_eq!(calls.len(), 1);
|
||||
assert_eq!(calls[0].0, "thoughts.created");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn serialized_payload_is_valid_json() {
|
||||
let (spy, calls) = SpyTransport::new();
|
||||
let publisher = EventPublisherAdapter::new(spy);
|
||||
publisher
|
||||
.publish(&DomainEvent::UserBlocked {
|
||||
blocker_id: UserId::new(),
|
||||
blocked_id: UserId::new(),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
let bytes = calls.lock().unwrap()[0].1.clone();
|
||||
let json: serde_json::Value = serde_json::from_slice(&bytes).expect("valid JSON");
|
||||
assert_eq!(json["type"], "UserBlocked");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn consumer_adapter_deserializes_and_yields_event() {
|
||||
use domain::value_objects::ThoughtId;
|
||||
use futures::StreamExt;
|
||||
|
||||
let event = DomainEvent::ThoughtCreated {
|
||||
thought_id: ThoughtId::new(),
|
||||
user_id: UserId::new(),
|
||||
in_reply_to_id: None,
|
||||
};
|
||||
let payload = EventPayload::from(&event);
|
||||
let bytes = serde_json::to_vec(&payload).unwrap();
|
||||
|
||||
struct OneMessageSource {
|
||||
bytes: Vec<u8>,
|
||||
}
|
||||
#[async_trait::async_trait]
|
||||
impl MessageSource for OneMessageSource {
|
||||
fn messages(&self) -> futures::stream::BoxStream<'_, Result<RawMessage, DomainError>> {
|
||||
let msg = RawMessage {
|
||||
subject: "thoughts.created".to_string(),
|
||||
payload: self.bytes.clone(),
|
||||
delivery_count: 1,
|
||||
ack: Box::new(|| {}),
|
||||
nack: Box::new(|| {}),
|
||||
};
|
||||
Box::pin(futures::stream::once(async { Ok(msg) }))
|
||||
}
|
||||
}
|
||||
|
||||
let adapter = EventConsumerAdapter::new(OneMessageSource { bytes });
|
||||
let mut stream = adapter.consume();
|
||||
let envelope = stream.next().await.unwrap().unwrap();
|
||||
assert!(matches!(envelope.event, DomainEvent::ThoughtCreated { .. }));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn consumer_adapter_skips_invalid_payloads() {
|
||||
use futures::StreamExt;
|
||||
|
||||
struct BadMessageSource;
|
||||
#[async_trait::async_trait]
|
||||
impl MessageSource for BadMessageSource {
|
||||
fn messages(&self) -> futures::stream::BoxStream<'_, Result<RawMessage, DomainError>> {
|
||||
let msg = RawMessage {
|
||||
subject: "bad".to_string(),
|
||||
payload: b"not valid json".to_vec(),
|
||||
delivery_count: 1,
|
||||
ack: Box::new(|| {}),
|
||||
nack: Box::new(|| {}),
|
||||
};
|
||||
Box::pin(futures::stream::once(async { Ok(msg) }))
|
||||
}
|
||||
}
|
||||
|
||||
let adapter = EventConsumerAdapter::new(BadMessageSource);
|
||||
let mut stream = adapter.consume();
|
||||
assert!(stream.next().await.is_none());
|
||||
}
|
||||
}
|
||||
mod tests;
|
||||
|
||||
122
crates/adapters/event-transport/src/tests.rs
Normal file
122
crates/adapters/event-transport/src/tests.rs
Normal file
@@ -0,0 +1,122 @@
|
||||
use super::*;
|
||||
use async_trait::async_trait;
|
||||
use domain::value_objects::{ThoughtId, UserId};
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
struct SpyTransport {
|
||||
calls: Arc<Mutex<Vec<(String, Vec<u8>)>>>,
|
||||
}
|
||||
impl SpyTransport {
|
||||
fn new() -> (Self, Arc<Mutex<Vec<(String, Vec<u8>)>>>) {
|
||||
let calls = Arc::new(Mutex::new(vec![]));
|
||||
(
|
||||
Self {
|
||||
calls: calls.clone(),
|
||||
},
|
||||
calls,
|
||||
)
|
||||
}
|
||||
}
|
||||
#[async_trait]
|
||||
impl Transport for SpyTransport {
|
||||
async fn publish_bytes(&self, subject: &str, bytes: &[u8]) -> Result<(), DomainError> {
|
||||
self.calls
|
||||
.lock()
|
||||
.unwrap()
|
||||
.push((subject.to_string(), bytes.to_vec()));
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn thought_created_routes_to_correct_subject() {
|
||||
let (spy, calls) = SpyTransport::new();
|
||||
let publisher = EventPublisherAdapter::new(spy);
|
||||
publisher
|
||||
.publish(&DomainEvent::ThoughtCreated {
|
||||
thought_id: ThoughtId::new(),
|
||||
user_id: UserId::new(),
|
||||
in_reply_to_id: None,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
let calls = calls.lock().unwrap();
|
||||
assert_eq!(calls.len(), 1);
|
||||
assert_eq!(calls[0].0, "thoughts.created");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn serialized_payload_is_valid_json() {
|
||||
let (spy, calls) = SpyTransport::new();
|
||||
let publisher = EventPublisherAdapter::new(spy);
|
||||
publisher
|
||||
.publish(&DomainEvent::UserBlocked {
|
||||
blocker_id: UserId::new(),
|
||||
blocked_id: UserId::new(),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
let bytes = calls.lock().unwrap()[0].1.clone();
|
||||
let json: serde_json::Value = serde_json::from_slice(&bytes).expect("valid JSON");
|
||||
assert_eq!(json["type"], "UserBlocked");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn consumer_adapter_deserializes_and_yields_event() {
|
||||
use domain::value_objects::ThoughtId;
|
||||
use futures::StreamExt;
|
||||
|
||||
let event = DomainEvent::ThoughtCreated {
|
||||
thought_id: ThoughtId::new(),
|
||||
user_id: UserId::new(),
|
||||
in_reply_to_id: None,
|
||||
};
|
||||
let payload = EventPayload::from(&event);
|
||||
let bytes = serde_json::to_vec(&payload).unwrap();
|
||||
|
||||
struct OneMessageSource {
|
||||
bytes: Vec<u8>,
|
||||
}
|
||||
#[async_trait::async_trait]
|
||||
impl MessageSource for OneMessageSource {
|
||||
fn messages(&self) -> futures::stream::BoxStream<'_, Result<RawMessage, DomainError>> {
|
||||
let msg = RawMessage {
|
||||
subject: "thoughts.created".to_string(),
|
||||
payload: self.bytes.clone(),
|
||||
delivery_count: 1,
|
||||
ack: Box::new(|| {}),
|
||||
nack: Box::new(|| {}),
|
||||
};
|
||||
Box::pin(futures::stream::once(async { Ok(msg) }))
|
||||
}
|
||||
}
|
||||
|
||||
let adapter = EventConsumerAdapter::new(OneMessageSource { bytes });
|
||||
let mut stream = adapter.consume();
|
||||
let envelope = stream.next().await.unwrap().unwrap();
|
||||
assert!(matches!(envelope.event, DomainEvent::ThoughtCreated { .. }));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn consumer_adapter_skips_invalid_payloads() {
|
||||
use futures::StreamExt;
|
||||
|
||||
struct BadMessageSource;
|
||||
#[async_trait::async_trait]
|
||||
impl MessageSource for BadMessageSource {
|
||||
fn messages(&self) -> futures::stream::BoxStream<'_, Result<RawMessage, DomainError>> {
|
||||
let msg = RawMessage {
|
||||
subject: "bad".to_string(),
|
||||
payload: b"not valid json".to_vec(),
|
||||
delivery_count: 1,
|
||||
ack: Box::new(|| {}),
|
||||
nack: Box::new(|| {}),
|
||||
};
|
||||
Box::pin(futures::stream::once(async { Ok(msg) }))
|
||||
}
|
||||
}
|
||||
|
||||
let adapter = EventConsumerAdapter::new(BadMessageSource);
|
||||
let mut stream = adapter.consume();
|
||||
assert!(stream.next().await.is_none());
|
||||
}
|
||||
@@ -239,47 +239,6 @@ impl MessageSource for NatsMessageSource {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use domain::{
|
||||
events::DomainEvent,
|
||||
value_objects::{LikeId, ThoughtId, UserId},
|
||||
};
|
||||
use event_payload::EventPayload;
|
||||
|
||||
#[test]
|
||||
fn payload_from_domain_event_has_correct_subject() {
|
||||
let event = DomainEvent::ThoughtCreated {
|
||||
thought_id: ThoughtId::new(),
|
||||
user_id: UserId::new(),
|
||||
in_reply_to_id: None,
|
||||
};
|
||||
let payload = EventPayload::from(&event);
|
||||
assert_eq!(payload.subject(), "thoughts.created");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn domain_event_roundtrip_via_payload() {
|
||||
let uid = UserId::new();
|
||||
let tid = ThoughtId::new();
|
||||
let event = DomainEvent::LikeAdded {
|
||||
like_id: LikeId::new(),
|
||||
user_id: uid.clone(),
|
||||
thought_id: tid.clone(),
|
||||
};
|
||||
let payload = EventPayload::from(&event);
|
||||
let back = DomainEvent::try_from(payload).unwrap();
|
||||
if let DomainEvent::LikeAdded {
|
||||
user_id,
|
||||
thought_id,
|
||||
..
|
||||
} = back
|
||||
{
|
||||
assert_eq!(user_id, uid);
|
||||
assert_eq!(thought_id, tid);
|
||||
} else {
|
||||
panic!("wrong variant");
|
||||
}
|
||||
}
|
||||
}
|
||||
mod tests;
|
||||
|
||||
41
crates/adapters/nats/src/tests.rs
Normal file
41
crates/adapters/nats/src/tests.rs
Normal file
@@ -0,0 +1,41 @@
|
||||
use super::*;
|
||||
use domain::{
|
||||
events::DomainEvent,
|
||||
value_objects::{LikeId, ThoughtId, UserId},
|
||||
};
|
||||
use event_payload::EventPayload;
|
||||
|
||||
#[test]
|
||||
fn payload_from_domain_event_has_correct_subject() {
|
||||
let event = DomainEvent::ThoughtCreated {
|
||||
thought_id: ThoughtId::new(),
|
||||
user_id: UserId::new(),
|
||||
in_reply_to_id: None,
|
||||
};
|
||||
let payload = EventPayload::from(&event);
|
||||
assert_eq!(payload.subject(), "thoughts.created");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn domain_event_roundtrip_via_payload() {
|
||||
let uid = UserId::new();
|
||||
let tid = ThoughtId::new();
|
||||
let event = DomainEvent::LikeAdded {
|
||||
like_id: LikeId::new(),
|
||||
user_id: uid.clone(),
|
||||
thought_id: tid.clone(),
|
||||
};
|
||||
let payload = EventPayload::from(&event);
|
||||
let back = DomainEvent::try_from(payload).unwrap();
|
||||
if let DomainEvent::LikeAdded {
|
||||
user_id,
|
||||
thought_id,
|
||||
..
|
||||
} = back
|
||||
{
|
||||
assert_eq!(user_id, uid);
|
||||
assert_eq!(thought_id, tid);
|
||||
} else {
|
||||
panic!("wrong variant");
|
||||
}
|
||||
}
|
||||
@@ -205,168 +205,4 @@ impl SearchPort for PgSearchRepository {
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use domain::{
|
||||
models::{
|
||||
thought::{Thought, Visibility},
|
||||
user::User,
|
||||
},
|
||||
ports::{SearchPort, ThoughtRepository, UserWriter},
|
||||
value_objects::*,
|
||||
};
|
||||
|
||||
async fn seed_thought(pool: &sqlx::PgPool, username: &str, content: &str) -> (User, Thought) {
|
||||
use postgres::{thought::PgThoughtRepository, user::PgUserRepository};
|
||||
let urepo = PgUserRepository::new(pool.clone());
|
||||
let trepo = PgThoughtRepository::new(pool.clone());
|
||||
let u = User::new_local(
|
||||
UserId::new(),
|
||||
Username::new(username).unwrap(),
|
||||
Email::new(format!("{username}@ex.com")).unwrap(),
|
||||
PasswordHash("h".into()),
|
||||
);
|
||||
urepo.save(&u).await.unwrap();
|
||||
let t = Thought::new_local(
|
||||
ThoughtId::new(),
|
||||
u.id.clone(),
|
||||
Content::new_local(content).unwrap(),
|
||||
None,
|
||||
Visibility::Public,
|
||||
None,
|
||||
false,
|
||||
);
|
||||
trepo.save(&t).await.unwrap();
|
||||
(u, t)
|
||||
}
|
||||
|
||||
#[sqlx::test(migrations = "../postgres/migrations")]
|
||||
async fn search_thoughts_finds_by_keyword(pool: sqlx::PgPool) {
|
||||
seed_thought(&pool, "alice", "hello world").await;
|
||||
seed_thought(&pool, "bob", "goodbye universe").await;
|
||||
let repo = PgSearchRepository::new(pool);
|
||||
let result = repo
|
||||
.search_thoughts(
|
||||
"hello world",
|
||||
&PageParams {
|
||||
page: 1,
|
||||
per_page: 20,
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(result.total, 1);
|
||||
assert_eq!(result.items[0].thought.content.as_str(), "hello world");
|
||||
}
|
||||
|
||||
#[sqlx::test(migrations = "../postgres/migrations")]
|
||||
async fn search_users_finds_by_username(pool: sqlx::PgPool) {
|
||||
use postgres::user::PgUserRepository;
|
||||
let urepo = PgUserRepository::new(pool.clone());
|
||||
let alice = User::new_local(
|
||||
UserId::new(),
|
||||
Username::new("alice_search").unwrap(),
|
||||
Email::new("alice@ex.com").unwrap(),
|
||||
PasswordHash("h".into()),
|
||||
);
|
||||
urepo.save(&alice).await.unwrap();
|
||||
let repo = PgSearchRepository::new(pool);
|
||||
let result = repo
|
||||
.search_users(
|
||||
"alice",
|
||||
&PageParams {
|
||||
page: 1,
|
||||
per_page: 20,
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(!result.items.is_empty());
|
||||
assert!(result
|
||||
.items
|
||||
.iter()
|
||||
.any(|u| u.username.as_str() == "alice_search"));
|
||||
}
|
||||
|
||||
#[sqlx::test(migrations = "../postgres/migrations")]
|
||||
async fn search_thoughts_returns_empty_for_no_match(pool: sqlx::PgPool) {
|
||||
seed_thought(&pool, "alice", "hello world").await;
|
||||
let repo = PgSearchRepository::new(pool);
|
||||
let result = repo
|
||||
.search_thoughts(
|
||||
"zzzzzzzzz",
|
||||
&PageParams {
|
||||
page: 1,
|
||||
per_page: 20,
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(result.total, 0);
|
||||
}
|
||||
|
||||
#[sqlx::test(migrations = "../postgres/migrations")]
|
||||
async fn search_thoughts_viewer_context(pool: sqlx::PgPool) {
|
||||
use domain::models::social::Like;
|
||||
use domain::ports::{LikeRepository, UserWriter};
|
||||
use domain::value_objects::LikeId;
|
||||
use postgres::{like::PgLikeRepository, user::PgUserRepository};
|
||||
|
||||
let (alice, thought) = seed_thought(&pool, "alice", "hello world").await;
|
||||
|
||||
// alice likes her own thought
|
||||
let like_repo = PgLikeRepository::new(pool.clone());
|
||||
like_repo
|
||||
.save(&Like {
|
||||
id: LikeId::new(),
|
||||
user_id: alice.id.clone(),
|
||||
thought_id: thought.id.clone(),
|
||||
ap_id: None,
|
||||
created_at: chrono::Utc::now(),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let repo = PgSearchRepository::new(pool);
|
||||
|
||||
// with viewer — should see liked = true
|
||||
let authed = repo
|
||||
.search_thoughts(
|
||||
"hello",
|
||||
&PageParams {
|
||||
page: 1,
|
||||
per_page: 20,
|
||||
},
|
||||
Some(&alice.id),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(authed.items.len(), 1);
|
||||
let ctx = authed.items[0]
|
||||
.viewer
|
||||
.as_ref()
|
||||
.expect("viewer context present");
|
||||
assert!(ctx.liked, "alice should see the thought as liked");
|
||||
assert!(!ctx.boosted);
|
||||
|
||||
// without viewer — viewer should be None
|
||||
let anon = repo
|
||||
.search_thoughts(
|
||||
"hello",
|
||||
&PageParams {
|
||||
page: 1,
|
||||
per_page: 20,
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(anon.items.len(), 1);
|
||||
assert!(
|
||||
anon.items[0].viewer.is_none(),
|
||||
"anonymous request has no viewer context"
|
||||
);
|
||||
}
|
||||
}
|
||||
mod tests;
|
||||
|
||||
163
crates/adapters/postgres-search/src/tests.rs
Normal file
163
crates/adapters/postgres-search/src/tests.rs
Normal file
@@ -0,0 +1,163 @@
|
||||
use super::*;
|
||||
use domain::{
|
||||
models::{
|
||||
thought::{Thought, Visibility},
|
||||
user::User,
|
||||
},
|
||||
ports::{SearchPort, ThoughtRepository, UserWriter},
|
||||
value_objects::*,
|
||||
};
|
||||
|
||||
async fn seed_thought(pool: &sqlx::PgPool, username: &str, content: &str) -> (User, Thought) {
|
||||
use postgres::{thought::PgThoughtRepository, user::PgUserRepository};
|
||||
let urepo = PgUserRepository::new(pool.clone());
|
||||
let trepo = PgThoughtRepository::new(pool.clone());
|
||||
let u = User::new_local(
|
||||
UserId::new(),
|
||||
Username::new(username).unwrap(),
|
||||
Email::new(format!("{username}@ex.com")).unwrap(),
|
||||
PasswordHash("h".into()),
|
||||
);
|
||||
urepo.save(&u).await.unwrap();
|
||||
let t = Thought::new_local(
|
||||
ThoughtId::new(),
|
||||
u.id.clone(),
|
||||
Content::new_local(content).unwrap(),
|
||||
None,
|
||||
Visibility::Public,
|
||||
None,
|
||||
false,
|
||||
);
|
||||
trepo.save(&t).await.unwrap();
|
||||
(u, t)
|
||||
}
|
||||
|
||||
#[sqlx::test(migrations = "../postgres/migrations")]
|
||||
async fn search_thoughts_finds_by_keyword(pool: sqlx::PgPool) {
|
||||
seed_thought(&pool, "alice", "hello world").await;
|
||||
seed_thought(&pool, "bob", "goodbye universe").await;
|
||||
let repo = PgSearchRepository::new(pool);
|
||||
let result = repo
|
||||
.search_thoughts(
|
||||
"hello world",
|
||||
&PageParams {
|
||||
page: 1,
|
||||
per_page: 20,
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(result.total, 1);
|
||||
assert_eq!(result.items[0].thought.content.as_str(), "hello world");
|
||||
}
|
||||
|
||||
#[sqlx::test(migrations = "../postgres/migrations")]
|
||||
async fn search_users_finds_by_username(pool: sqlx::PgPool) {
|
||||
use postgres::user::PgUserRepository;
|
||||
let urepo = PgUserRepository::new(pool.clone());
|
||||
let alice = User::new_local(
|
||||
UserId::new(),
|
||||
Username::new("alice_search").unwrap(),
|
||||
Email::new("alice@ex.com").unwrap(),
|
||||
PasswordHash("h".into()),
|
||||
);
|
||||
urepo.save(&alice).await.unwrap();
|
||||
let repo = PgSearchRepository::new(pool);
|
||||
let result = repo
|
||||
.search_users(
|
||||
"alice",
|
||||
&PageParams {
|
||||
page: 1,
|
||||
per_page: 20,
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(!result.items.is_empty());
|
||||
assert!(result
|
||||
.items
|
||||
.iter()
|
||||
.any(|u| u.username.as_str() == "alice_search"));
|
||||
}
|
||||
|
||||
#[sqlx::test(migrations = "../postgres/migrations")]
|
||||
async fn search_thoughts_returns_empty_for_no_match(pool: sqlx::PgPool) {
|
||||
seed_thought(&pool, "alice", "hello world").await;
|
||||
let repo = PgSearchRepository::new(pool);
|
||||
let result = repo
|
||||
.search_thoughts(
|
||||
"zzzzzzzzz",
|
||||
&PageParams {
|
||||
page: 1,
|
||||
per_page: 20,
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(result.total, 0);
|
||||
}
|
||||
|
||||
#[sqlx::test(migrations = "../postgres/migrations")]
|
||||
async fn search_thoughts_viewer_context(pool: sqlx::PgPool) {
|
||||
use domain::models::social::Like;
|
||||
use domain::ports::{LikeRepository, UserWriter};
|
||||
use domain::value_objects::LikeId;
|
||||
use postgres::{like::PgLikeRepository, user::PgUserRepository};
|
||||
|
||||
let (alice, thought) = seed_thought(&pool, "alice", "hello world").await;
|
||||
|
||||
// alice likes her own thought
|
||||
let like_repo = PgLikeRepository::new(pool.clone());
|
||||
like_repo
|
||||
.save(&Like {
|
||||
id: LikeId::new(),
|
||||
user_id: alice.id.clone(),
|
||||
thought_id: thought.id.clone(),
|
||||
ap_id: None,
|
||||
created_at: chrono::Utc::now(),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let repo = PgSearchRepository::new(pool);
|
||||
|
||||
// with viewer — should see liked = true
|
||||
let authed = repo
|
||||
.search_thoughts(
|
||||
"hello",
|
||||
&PageParams {
|
||||
page: 1,
|
||||
per_page: 20,
|
||||
},
|
||||
Some(&alice.id),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(authed.items.len(), 1);
|
||||
let ctx = authed.items[0]
|
||||
.viewer
|
||||
.as_ref()
|
||||
.expect("viewer context present");
|
||||
assert!(ctx.liked, "alice should see the thought as liked");
|
||||
assert!(!ctx.boosted);
|
||||
|
||||
// without viewer — viewer should be None
|
||||
let anon = repo
|
||||
.search_thoughts(
|
||||
"hello",
|
||||
&PageParams {
|
||||
page: 1,
|
||||
per_page: 20,
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(anon.items.len(), 1);
|
||||
assert!(
|
||||
anon.items[0].viewer.is_none(),
|
||||
"anonymous request has no viewer context"
|
||||
);
|
||||
}
|
||||
@@ -334,73 +334,4 @@ impl ActivityPubRepository for PgActivityPubRepository {
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use activitypub_base::ActivityPubRepository;
|
||||
|
||||
#[sqlx::test(migrations = "./migrations")]
|
||||
async fn intern_remote_actor_is_idempotent(pool: sqlx::PgPool) {
|
||||
let repo = PgActivityPubRepository::new(pool);
|
||||
let url = "https://mastodon.social/users/alice";
|
||||
let id1 = repo.intern_remote_actor(url).await.unwrap();
|
||||
let id2 = repo.intern_remote_actor(url).await.unwrap();
|
||||
assert_eq!(id1, id2);
|
||||
}
|
||||
|
||||
#[sqlx::test(migrations = "./migrations")]
|
||||
async fn accept_and_retract_note(pool: sqlx::PgPool) {
|
||||
let repo = PgActivityPubRepository::new(pool);
|
||||
let actor_url = "https://remote.example/users/bob";
|
||||
let ap_id = "https://remote.example/notes/1";
|
||||
let author = repo.intern_remote_actor(actor_url).await.unwrap();
|
||||
repo.accept_note(
|
||||
ap_id,
|
||||
&author,
|
||||
"hello from remote",
|
||||
chrono::Utc::now(),
|
||||
false,
|
||||
None,
|
||||
"public",
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
repo.retract_note(ap_id).await.unwrap();
|
||||
}
|
||||
|
||||
#[sqlx::test(migrations = "./migrations")]
|
||||
async fn count_local_notes_excludes_remote(pool: sqlx::PgPool) {
|
||||
let repo = PgActivityPubRepository::new(pool);
|
||||
assert_eq!(repo.count_local_notes().await.unwrap(), 0);
|
||||
}
|
||||
|
||||
#[sqlx::test(migrations = "./migrations")]
|
||||
async fn accept_note_returns_thought_id(pool: sqlx::PgPool) {
|
||||
let repo = PgActivityPubRepository::new(pool.clone());
|
||||
let actor_user_id = repo
|
||||
.intern_remote_actor("https://remote.example/users/alice")
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let thought_id = repo
|
||||
.accept_note(
|
||||
"https://remote.example/notes/1",
|
||||
&actor_user_id,
|
||||
"Hello #rust world",
|
||||
chrono::Utc::now(),
|
||||
false,
|
||||
None,
|
||||
"public",
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let row: (uuid::Uuid,) = sqlx::query_as("SELECT id FROM thoughts WHERE ap_id=$1")
|
||||
.bind("https://remote.example/notes/1")
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(thought_id.as_uuid(), row.0);
|
||||
}
|
||||
}
|
||||
mod tests;
|
||||
68
crates/adapters/postgres/src/activitypub/tests.rs
Normal file
68
crates/adapters/postgres/src/activitypub/tests.rs
Normal file
@@ -0,0 +1,68 @@
|
||||
use super::*;
|
||||
use activitypub_base::ActivityPubRepository;
|
||||
|
||||
#[sqlx::test(migrations = "./migrations")]
|
||||
async fn intern_remote_actor_is_idempotent(pool: sqlx::PgPool) {
|
||||
let repo = PgActivityPubRepository::new(pool);
|
||||
let url = "https://mastodon.social/users/alice";
|
||||
let id1 = repo.intern_remote_actor(url).await.unwrap();
|
||||
let id2 = repo.intern_remote_actor(url).await.unwrap();
|
||||
assert_eq!(id1, id2);
|
||||
}
|
||||
|
||||
#[sqlx::test(migrations = "./migrations")]
|
||||
async fn accept_and_retract_note(pool: sqlx::PgPool) {
|
||||
let repo = PgActivityPubRepository::new(pool);
|
||||
let actor_url = "https://remote.example/users/bob";
|
||||
let ap_id = "https://remote.example/notes/1";
|
||||
let author = repo.intern_remote_actor(actor_url).await.unwrap();
|
||||
repo.accept_note(
|
||||
ap_id,
|
||||
&author,
|
||||
"hello from remote",
|
||||
chrono::Utc::now(),
|
||||
false,
|
||||
None,
|
||||
"public",
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
repo.retract_note(ap_id).await.unwrap();
|
||||
}
|
||||
|
||||
#[sqlx::test(migrations = "./migrations")]
|
||||
async fn count_local_notes_excludes_remote(pool: sqlx::PgPool) {
|
||||
let repo = PgActivityPubRepository::new(pool);
|
||||
assert_eq!(repo.count_local_notes().await.unwrap(), 0);
|
||||
}
|
||||
|
||||
#[sqlx::test(migrations = "./migrations")]
|
||||
async fn accept_note_returns_thought_id(pool: sqlx::PgPool) {
|
||||
let repo = PgActivityPubRepository::new(pool.clone());
|
||||
let actor_user_id = repo
|
||||
.intern_remote_actor("https://remote.example/users/alice")
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let thought_id = repo
|
||||
.accept_note(
|
||||
"https://remote.example/notes/1",
|
||||
&actor_user_id,
|
||||
"Hello #rust world",
|
||||
chrono::Utc::now(),
|
||||
false,
|
||||
None,
|
||||
"public",
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let row: (uuid::Uuid,) = sqlx::query_as("SELECT id FROM thoughts WHERE ap_id=$1")
|
||||
.bind("https://remote.example/notes/1")
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(thought_id.as_uuid(), row.0);
|
||||
}
|
||||
@@ -89,54 +89,4 @@ impl ApiKeyRepository for PgApiKeyRepository {
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::user::PgUserRepository;
|
||||
use chrono::Utc;
|
||||
use domain::ports::UserWriter;
|
||||
use domain::{models::user::User, value_objects::*};
|
||||
|
||||
async fn seed_user(pool: &sqlx::PgPool) -> User {
|
||||
let repo = PgUserRepository::new(pool.clone());
|
||||
let u = User::new_local(
|
||||
UserId::new(),
|
||||
Username::new("alice").unwrap(),
|
||||
Email::new("alice@ex.com").unwrap(),
|
||||
PasswordHash("h".into()),
|
||||
);
|
||||
repo.save(&u).await.unwrap();
|
||||
u
|
||||
}
|
||||
|
||||
#[sqlx::test(migrations = "./migrations")]
|
||||
async fn save_and_find_by_hash(pool: sqlx::PgPool) {
|
||||
let user = seed_user(&pool).await;
|
||||
let repo = PgApiKeyRepository::new(pool);
|
||||
let key = ApiKey {
|
||||
id: ApiKeyId::new(),
|
||||
user_id: user.id.clone(),
|
||||
key_hash: "abc123".into(),
|
||||
name: "test".into(),
|
||||
created_at: Utc::now(),
|
||||
};
|
||||
repo.save(&key).await.unwrap();
|
||||
let found = repo.find_by_hash("abc123").await.unwrap().unwrap();
|
||||
assert_eq!(found.name, "test");
|
||||
}
|
||||
|
||||
#[sqlx::test(migrations = "./migrations")]
|
||||
async fn delete_key(pool: sqlx::PgPool) {
|
||||
let user = seed_user(&pool).await;
|
||||
let repo = PgApiKeyRepository::new(pool);
|
||||
let key = ApiKey {
|
||||
id: ApiKeyId::new(),
|
||||
user_id: user.id.clone(),
|
||||
key_hash: "def456".into(),
|
||||
name: "key2".into(),
|
||||
created_at: Utc::now(),
|
||||
};
|
||||
repo.save(&key).await.unwrap();
|
||||
repo.delete(&key.id, &user.id).await.unwrap();
|
||||
assert!(repo.find_by_hash("def456").await.unwrap().is_none());
|
||||
}
|
||||
}
|
||||
mod tests;
|
||||
49
crates/adapters/postgres/src/api_key/tests.rs
Normal file
49
crates/adapters/postgres/src/api_key/tests.rs
Normal file
@@ -0,0 +1,49 @@
|
||||
use super::*;
|
||||
use crate::user::PgUserRepository;
|
||||
use chrono::Utc;
|
||||
use domain::ports::UserWriter;
|
||||
use domain::{models::user::User, value_objects::*};
|
||||
|
||||
async fn seed_user(pool: &sqlx::PgPool) -> User {
|
||||
let repo = PgUserRepository::new(pool.clone());
|
||||
let u = User::new_local(
|
||||
UserId::new(),
|
||||
Username::new("alice").unwrap(),
|
||||
Email::new("alice@ex.com").unwrap(),
|
||||
PasswordHash("h".into()),
|
||||
);
|
||||
repo.save(&u).await.unwrap();
|
||||
u
|
||||
}
|
||||
|
||||
#[sqlx::test(migrations = "./migrations")]
|
||||
async fn save_and_find_by_hash(pool: sqlx::PgPool) {
|
||||
let user = seed_user(&pool).await;
|
||||
let repo = PgApiKeyRepository::new(pool);
|
||||
let key = ApiKey {
|
||||
id: ApiKeyId::new(),
|
||||
user_id: user.id.clone(),
|
||||
key_hash: "abc123".into(),
|
||||
name: "test".into(),
|
||||
created_at: Utc::now(),
|
||||
};
|
||||
repo.save(&key).await.unwrap();
|
||||
let found = repo.find_by_hash("abc123").await.unwrap().unwrap();
|
||||
assert_eq!(found.name, "test");
|
||||
}
|
||||
|
||||
#[sqlx::test(migrations = "./migrations")]
|
||||
async fn delete_key(pool: sqlx::PgPool) {
|
||||
let user = seed_user(&pool).await;
|
||||
let repo = PgApiKeyRepository::new(pool);
|
||||
let key = ApiKey {
|
||||
id: ApiKeyId::new(),
|
||||
user_id: user.id.clone(),
|
||||
key_hash: "def456".into(),
|
||||
name: "key2".into(),
|
||||
created_at: Utc::now(),
|
||||
};
|
||||
repo.save(&key).await.unwrap();
|
||||
repo.delete(&key.id, &user.id).await.unwrap();
|
||||
assert!(repo.find_by_hash("def456").await.unwrap().is_none());
|
||||
}
|
||||
@@ -52,39 +52,4 @@ impl BlockRepository for PgBlockRepository {
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::test_helpers::seed_user;
|
||||
use chrono::Utc;
|
||||
use domain::value_objects::*;
|
||||
|
||||
#[sqlx::test(migrations = "./migrations")]
|
||||
async fn block_exists(pool: sqlx::PgPool) {
|
||||
let alice = seed_user(&pool, "alice", "alice@ex.com").await;
|
||||
let bob = seed_user(&pool, "bob", "bob@ex.com").await;
|
||||
let repo = PgBlockRepository::new(pool);
|
||||
let block = Block {
|
||||
blocker_id: alice.id.clone(),
|
||||
blocked_id: bob.id.clone(),
|
||||
created_at: Utc::now(),
|
||||
};
|
||||
repo.save(&block).await.unwrap();
|
||||
assert!(repo.exists(&alice.id, &bob.id).await.unwrap());
|
||||
assert!(!repo.exists(&bob.id, &alice.id).await.unwrap());
|
||||
}
|
||||
|
||||
#[sqlx::test(migrations = "./migrations")]
|
||||
async fn unblock(pool: sqlx::PgPool) {
|
||||
let alice = seed_user(&pool, "alice", "alice@ex.com").await;
|
||||
let bob = seed_user(&pool, "bob", "bob@ex.com").await;
|
||||
let repo = PgBlockRepository::new(pool);
|
||||
let block = Block {
|
||||
blocker_id: alice.id.clone(),
|
||||
blocked_id: bob.id.clone(),
|
||||
created_at: Utc::now(),
|
||||
};
|
||||
repo.save(&block).await.unwrap();
|
||||
repo.delete(&alice.id, &bob.id).await.unwrap();
|
||||
assert!(!repo.exists(&alice.id, &bob.id).await.unwrap());
|
||||
}
|
||||
}
|
||||
mod tests;
|
||||
34
crates/adapters/postgres/src/block/tests.rs
Normal file
34
crates/adapters/postgres/src/block/tests.rs
Normal file
@@ -0,0 +1,34 @@
|
||||
use super::*;
|
||||
use crate::test_helpers::seed_user;
|
||||
use chrono::Utc;
|
||||
use domain::value_objects::*;
|
||||
|
||||
#[sqlx::test(migrations = "./migrations")]
|
||||
async fn block_exists(pool: sqlx::PgPool) {
|
||||
let alice = seed_user(&pool, "alice", "alice@ex.com").await;
|
||||
let bob = seed_user(&pool, "bob", "bob@ex.com").await;
|
||||
let repo = PgBlockRepository::new(pool);
|
||||
let block = Block {
|
||||
blocker_id: alice.id.clone(),
|
||||
blocked_id: bob.id.clone(),
|
||||
created_at: Utc::now(),
|
||||
};
|
||||
repo.save(&block).await.unwrap();
|
||||
assert!(repo.exists(&alice.id, &bob.id).await.unwrap());
|
||||
assert!(!repo.exists(&bob.id, &alice.id).await.unwrap());
|
||||
}
|
||||
|
||||
#[sqlx::test(migrations = "./migrations")]
|
||||
async fn unblock(pool: sqlx::PgPool) {
|
||||
let alice = seed_user(&pool, "alice", "alice@ex.com").await;
|
||||
let bob = seed_user(&pool, "bob", "bob@ex.com").await;
|
||||
let repo = PgBlockRepository::new(pool);
|
||||
let block = Block {
|
||||
blocker_id: alice.id.clone(),
|
||||
blocked_id: bob.id.clone(),
|
||||
created_at: Utc::now(),
|
||||
};
|
||||
repo.save(&block).await.unwrap();
|
||||
repo.delete(&alice.id, &bob.id).await.unwrap();
|
||||
assert!(!repo.exists(&alice.id, &bob.id).await.unwrap());
|
||||
}
|
||||
@@ -71,40 +71,4 @@ impl BoostRepository for PgBoostRepository {
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::test_helpers::seed_user_and_thought;
|
||||
use chrono::Utc;
|
||||
use domain::value_objects::*;
|
||||
|
||||
#[sqlx::test(migrations = "./migrations")]
|
||||
async fn boost_and_count(pool: sqlx::PgPool) {
|
||||
let (user, thought) = seed_user_and_thought(&pool).await;
|
||||
let repo = PgBoostRepository::new(pool);
|
||||
let boost = Boost {
|
||||
id: BoostId::new(),
|
||||
user_id: user.id.clone(),
|
||||
thought_id: thought.id.clone(),
|
||||
ap_id: None,
|
||||
created_at: Utc::now(),
|
||||
};
|
||||
repo.save(&boost).await.unwrap();
|
||||
assert_eq!(repo.count_for_thought(&thought.id).await.unwrap(), 1);
|
||||
}
|
||||
|
||||
#[sqlx::test(migrations = "./migrations")]
|
||||
async fn unboost(pool: sqlx::PgPool) {
|
||||
let (user, thought) = seed_user_and_thought(&pool).await;
|
||||
let repo = PgBoostRepository::new(pool);
|
||||
let boost = Boost {
|
||||
id: BoostId::new(),
|
||||
user_id: user.id.clone(),
|
||||
thought_id: thought.id.clone(),
|
||||
ap_id: None,
|
||||
created_at: Utc::now(),
|
||||
};
|
||||
repo.save(&boost).await.unwrap();
|
||||
repo.delete(&user.id, &thought.id).await.unwrap();
|
||||
assert_eq!(repo.count_for_thought(&thought.id).await.unwrap(), 0);
|
||||
}
|
||||
}
|
||||
mod tests;
|
||||
35
crates/adapters/postgres/src/boost/tests.rs
Normal file
35
crates/adapters/postgres/src/boost/tests.rs
Normal file
@@ -0,0 +1,35 @@
|
||||
use super::*;
|
||||
use crate::test_helpers::seed_user_and_thought;
|
||||
use chrono::Utc;
|
||||
use domain::value_objects::*;
|
||||
|
||||
#[sqlx::test(migrations = "./migrations")]
|
||||
async fn boost_and_count(pool: sqlx::PgPool) {
|
||||
let (user, thought) = seed_user_and_thought(&pool).await;
|
||||
let repo = PgBoostRepository::new(pool);
|
||||
let boost = Boost {
|
||||
id: BoostId::new(),
|
||||
user_id: user.id.clone(),
|
||||
thought_id: thought.id.clone(),
|
||||
ap_id: None,
|
||||
created_at: Utc::now(),
|
||||
};
|
||||
repo.save(&boost).await.unwrap();
|
||||
assert_eq!(repo.count_for_thought(&thought.id).await.unwrap(), 1);
|
||||
}
|
||||
|
||||
#[sqlx::test(migrations = "./migrations")]
|
||||
async fn unboost(pool: sqlx::PgPool) {
|
||||
let (user, thought) = seed_user_and_thought(&pool).await;
|
||||
let repo = PgBoostRepository::new(pool);
|
||||
let boost = Boost {
|
||||
id: BoostId::new(),
|
||||
user_id: user.id.clone(),
|
||||
thought_id: thought.id.clone(),
|
||||
ap_id: None,
|
||||
created_at: Utc::now(),
|
||||
};
|
||||
repo.save(&boost).await.unwrap();
|
||||
repo.delete(&user.id, &thought.id).await.unwrap();
|
||||
assert_eq!(repo.count_for_thought(&thought.id).await.unwrap(), 0);
|
||||
}
|
||||
@@ -326,74 +326,4 @@ impl FeedRepository for PgFeedRepository {
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::{thought::PgThoughtRepository, user::PgUserRepository};
|
||||
use domain::{
|
||||
models::{
|
||||
feed::PageParams,
|
||||
thought::{Thought, Visibility},
|
||||
user::User,
|
||||
},
|
||||
ports::{FeedQuery, ThoughtRepository, UserWriter},
|
||||
value_objects::*,
|
||||
};
|
||||
|
||||
async fn seed(pool: &sqlx::PgPool, username: &str, content: &str) -> (User, Thought) {
|
||||
let urepo = PgUserRepository::new(pool.clone());
|
||||
let trepo = PgThoughtRepository::new(pool.clone());
|
||||
let u = User::new_local(
|
||||
UserId::new(),
|
||||
Username::new(username).unwrap(),
|
||||
Email::new(format!("{username}@ex.com")).unwrap(),
|
||||
PasswordHash("h".into()),
|
||||
);
|
||||
urepo.save(&u).await.unwrap();
|
||||
let t = Thought::new_local(
|
||||
ThoughtId::new(),
|
||||
u.id.clone(),
|
||||
Content::new_local(content).unwrap(),
|
||||
None,
|
||||
Visibility::Public,
|
||||
None,
|
||||
false,
|
||||
);
|
||||
trepo.save(&t).await.unwrap();
|
||||
(u, t)
|
||||
}
|
||||
|
||||
#[sqlx::test(migrations = "./migrations")]
|
||||
async fn public_feed_returns_local_thoughts(pool: sqlx::PgPool) {
|
||||
let (_, _) = seed(&pool, "alice", "hello").await;
|
||||
let repo = PgFeedRepository::new(pool);
|
||||
let result = repo
|
||||
.query(&FeedQuery::public(
|
||||
PageParams { page: 1, per_page: 20 },
|
||||
None,
|
||||
))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(result.total, 1);
|
||||
assert_eq!(result.items[0].thought.content.as_str(), "hello");
|
||||
}
|
||||
|
||||
#[sqlx::test(migrations = "./migrations")]
|
||||
async fn search_returns_matching_thoughts(pool: sqlx::PgPool) {
|
||||
let (_, _) = seed(&pool, "alice", "hello world").await;
|
||||
let (_, _) = seed(&pool, "bob", "goodbye world").await;
|
||||
let repo = PgFeedRepository::new(pool);
|
||||
let result = repo
|
||||
.query(&FeedQuery::search(
|
||||
"hello world",
|
||||
PageParams { page: 1, per_page: 20 },
|
||||
None,
|
||||
))
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(result.total >= 1);
|
||||
assert!(result
|
||||
.items
|
||||
.iter()
|
||||
.any(|e| e.thought.content.as_str() == "hello world"));
|
||||
}
|
||||
}
|
||||
mod tests;
|
||||
69
crates/adapters/postgres/src/feed/tests.rs
Normal file
69
crates/adapters/postgres/src/feed/tests.rs
Normal file
@@ -0,0 +1,69 @@
|
||||
use super::*;
|
||||
use crate::{thought::PgThoughtRepository, user::PgUserRepository};
|
||||
use domain::{
|
||||
models::{
|
||||
feed::PageParams,
|
||||
thought::{Thought, Visibility},
|
||||
user::User,
|
||||
},
|
||||
ports::{FeedQuery, ThoughtRepository, UserWriter},
|
||||
value_objects::*,
|
||||
};
|
||||
|
||||
async fn seed(pool: &sqlx::PgPool, username: &str, content: &str) -> (User, Thought) {
|
||||
let urepo = PgUserRepository::new(pool.clone());
|
||||
let trepo = PgThoughtRepository::new(pool.clone());
|
||||
let u = User::new_local(
|
||||
UserId::new(),
|
||||
Username::new(username).unwrap(),
|
||||
Email::new(format!("{username}@ex.com")).unwrap(),
|
||||
PasswordHash("h".into()),
|
||||
);
|
||||
urepo.save(&u).await.unwrap();
|
||||
let t = Thought::new_local(
|
||||
ThoughtId::new(),
|
||||
u.id.clone(),
|
||||
Content::new_local(content).unwrap(),
|
||||
None,
|
||||
Visibility::Public,
|
||||
None,
|
||||
false,
|
||||
);
|
||||
trepo.save(&t).await.unwrap();
|
||||
(u, t)
|
||||
}
|
||||
|
||||
#[sqlx::test(migrations = "./migrations")]
|
||||
async fn public_feed_returns_local_thoughts(pool: sqlx::PgPool) {
|
||||
let (_, _) = seed(&pool, "alice", "hello").await;
|
||||
let repo = PgFeedRepository::new(pool);
|
||||
let result = repo
|
||||
.query(&FeedQuery::public(
|
||||
PageParams { page: 1, per_page: 20 },
|
||||
None,
|
||||
))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(result.total, 1);
|
||||
assert_eq!(result.items[0].thought.content.as_str(), "hello");
|
||||
}
|
||||
|
||||
#[sqlx::test(migrations = "./migrations")]
|
||||
async fn search_returns_matching_thoughts(pool: sqlx::PgPool) {
|
||||
let (_, _) = seed(&pool, "alice", "hello world").await;
|
||||
let (_, _) = seed(&pool, "bob", "goodbye world").await;
|
||||
let repo = PgFeedRepository::new(pool);
|
||||
let result = repo
|
||||
.query(&FeedQuery::search(
|
||||
"hello world",
|
||||
PageParams { page: 1, per_page: 20 },
|
||||
None,
|
||||
))
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(result.total >= 1);
|
||||
assert!(result
|
||||
.items
|
||||
.iter()
|
||||
.any(|e| e.thought.content.as_str() == "hello world"));
|
||||
}
|
||||
@@ -190,63 +190,4 @@ impl FollowRepository for PgFollowRepository {
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::test_helpers::seed_user;
|
||||
use chrono::Utc;
|
||||
use domain::value_objects::*;
|
||||
|
||||
#[sqlx::test(migrations = "./migrations")]
|
||||
async fn save_and_find_follow(pool: sqlx::PgPool) {
|
||||
let alice = seed_user(&pool, "alice", "alice@ex.com").await;
|
||||
let bob = seed_user(&pool, "bob", "bob@ex.com").await;
|
||||
let repo = PgFollowRepository::new(pool);
|
||||
let follow = Follow {
|
||||
follower_id: alice.id.clone(),
|
||||
following_id: bob.id.clone(),
|
||||
state: FollowState::Accepted,
|
||||
ap_id: None,
|
||||
created_at: Utc::now(),
|
||||
};
|
||||
repo.save(&follow).await.unwrap();
|
||||
let found = repo.find(&alice.id, &bob.id).await.unwrap().unwrap();
|
||||
assert_eq!(found.state, FollowState::Accepted);
|
||||
}
|
||||
|
||||
#[sqlx::test(migrations = "./migrations")]
|
||||
async fn update_state(pool: sqlx::PgPool) {
|
||||
let alice = seed_user(&pool, "alice", "alice@ex.com").await;
|
||||
let bob = seed_user(&pool, "bob", "bob@ex.com").await;
|
||||
let repo = PgFollowRepository::new(pool);
|
||||
let follow = Follow {
|
||||
follower_id: alice.id.clone(),
|
||||
following_id: bob.id.clone(),
|
||||
state: FollowState::Pending,
|
||||
ap_id: None,
|
||||
created_at: Utc::now(),
|
||||
};
|
||||
repo.save(&follow).await.unwrap();
|
||||
repo.update_state(&alice.id, &bob.id, &FollowState::Accepted)
|
||||
.await
|
||||
.unwrap();
|
||||
let found = repo.find(&alice.id, &bob.id).await.unwrap().unwrap();
|
||||
assert_eq!(found.state, FollowState::Accepted);
|
||||
}
|
||||
|
||||
#[sqlx::test(migrations = "./migrations")]
|
||||
async fn get_accepted_following_ids(pool: sqlx::PgPool) {
|
||||
let alice = seed_user(&pool, "alice", "alice@ex.com").await;
|
||||
let bob = seed_user(&pool, "bob", "bob@ex.com").await;
|
||||
let repo = PgFollowRepository::new(pool);
|
||||
let follow = Follow {
|
||||
follower_id: alice.id.clone(),
|
||||
following_id: bob.id.clone(),
|
||||
state: FollowState::Accepted,
|
||||
ap_id: None,
|
||||
created_at: Utc::now(),
|
||||
};
|
||||
repo.save(&follow).await.unwrap();
|
||||
let ids = repo.get_accepted_following_ids(&alice.id).await.unwrap();
|
||||
assert_eq!(ids, vec![bob.id]);
|
||||
}
|
||||
}
|
||||
mod tests;
|
||||
58
crates/adapters/postgres/src/follow/tests.rs
Normal file
58
crates/adapters/postgres/src/follow/tests.rs
Normal file
@@ -0,0 +1,58 @@
|
||||
use super::*;
|
||||
use crate::test_helpers::seed_user;
|
||||
use chrono::Utc;
|
||||
use domain::value_objects::*;
|
||||
|
||||
#[sqlx::test(migrations = "./migrations")]
|
||||
async fn save_and_find_follow(pool: sqlx::PgPool) {
|
||||
let alice = seed_user(&pool, "alice", "alice@ex.com").await;
|
||||
let bob = seed_user(&pool, "bob", "bob@ex.com").await;
|
||||
let repo = PgFollowRepository::new(pool);
|
||||
let follow = Follow {
|
||||
follower_id: alice.id.clone(),
|
||||
following_id: bob.id.clone(),
|
||||
state: FollowState::Accepted,
|
||||
ap_id: None,
|
||||
created_at: Utc::now(),
|
||||
};
|
||||
repo.save(&follow).await.unwrap();
|
||||
let found = repo.find(&alice.id, &bob.id).await.unwrap().unwrap();
|
||||
assert_eq!(found.state, FollowState::Accepted);
|
||||
}
|
||||
|
||||
#[sqlx::test(migrations = "./migrations")]
|
||||
async fn update_state(pool: sqlx::PgPool) {
|
||||
let alice = seed_user(&pool, "alice", "alice@ex.com").await;
|
||||
let bob = seed_user(&pool, "bob", "bob@ex.com").await;
|
||||
let repo = PgFollowRepository::new(pool);
|
||||
let follow = Follow {
|
||||
follower_id: alice.id.clone(),
|
||||
following_id: bob.id.clone(),
|
||||
state: FollowState::Pending,
|
||||
ap_id: None,
|
||||
created_at: Utc::now(),
|
||||
};
|
||||
repo.save(&follow).await.unwrap();
|
||||
repo.update_state(&alice.id, &bob.id, &FollowState::Accepted)
|
||||
.await
|
||||
.unwrap();
|
||||
let found = repo.find(&alice.id, &bob.id).await.unwrap().unwrap();
|
||||
assert_eq!(found.state, FollowState::Accepted);
|
||||
}
|
||||
|
||||
#[sqlx::test(migrations = "./migrations")]
|
||||
async fn get_accepted_following_ids(pool: sqlx::PgPool) {
|
||||
let alice = seed_user(&pool, "alice", "alice@ex.com").await;
|
||||
let bob = seed_user(&pool, "bob", "bob@ex.com").await;
|
||||
let repo = PgFollowRepository::new(pool);
|
||||
let follow = Follow {
|
||||
follower_id: alice.id.clone(),
|
||||
following_id: bob.id.clone(),
|
||||
state: FollowState::Accepted,
|
||||
ap_id: None,
|
||||
created_at: Utc::now(),
|
||||
};
|
||||
repo.save(&follow).await.unwrap();
|
||||
let ids = repo.get_accepted_following_ids(&alice.id).await.unwrap();
|
||||
assert_eq!(ids, vec![bob.id]);
|
||||
}
|
||||
@@ -71,40 +71,4 @@ impl LikeRepository for PgLikeRepository {
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::test_helpers::seed_user_and_thought;
|
||||
use chrono::Utc;
|
||||
use domain::value_objects::*;
|
||||
|
||||
#[sqlx::test(migrations = "./migrations")]
|
||||
async fn like_and_count(pool: sqlx::PgPool) {
|
||||
let (user, thought) = seed_user_and_thought(&pool).await;
|
||||
let repo = PgLikeRepository::new(pool);
|
||||
let like = Like {
|
||||
id: LikeId::new(),
|
||||
user_id: user.id.clone(),
|
||||
thought_id: thought.id.clone(),
|
||||
ap_id: None,
|
||||
created_at: Utc::now(),
|
||||
};
|
||||
repo.save(&like).await.unwrap();
|
||||
assert_eq!(repo.count_for_thought(&thought.id).await.unwrap(), 1);
|
||||
}
|
||||
|
||||
#[sqlx::test(migrations = "./migrations")]
|
||||
async fn unlike(pool: sqlx::PgPool) {
|
||||
let (user, thought) = seed_user_and_thought(&pool).await;
|
||||
let repo = PgLikeRepository::new(pool);
|
||||
let like = Like {
|
||||
id: LikeId::new(),
|
||||
user_id: user.id.clone(),
|
||||
thought_id: thought.id.clone(),
|
||||
ap_id: None,
|
||||
created_at: Utc::now(),
|
||||
};
|
||||
repo.save(&like).await.unwrap();
|
||||
repo.delete(&user.id, &thought.id).await.unwrap();
|
||||
assert_eq!(repo.count_for_thought(&thought.id).await.unwrap(), 0);
|
||||
}
|
||||
}
|
||||
mod tests;
|
||||
35
crates/adapters/postgres/src/like/tests.rs
Normal file
35
crates/adapters/postgres/src/like/tests.rs
Normal file
@@ -0,0 +1,35 @@
|
||||
use super::*;
|
||||
use crate::test_helpers::seed_user_and_thought;
|
||||
use chrono::Utc;
|
||||
use domain::value_objects::*;
|
||||
|
||||
#[sqlx::test(migrations = "./migrations")]
|
||||
async fn like_and_count(pool: sqlx::PgPool) {
|
||||
let (user, thought) = seed_user_and_thought(&pool).await;
|
||||
let repo = PgLikeRepository::new(pool);
|
||||
let like = Like {
|
||||
id: LikeId::new(),
|
||||
user_id: user.id.clone(),
|
||||
thought_id: thought.id.clone(),
|
||||
ap_id: None,
|
||||
created_at: Utc::now(),
|
||||
};
|
||||
repo.save(&like).await.unwrap();
|
||||
assert_eq!(repo.count_for_thought(&thought.id).await.unwrap(), 1);
|
||||
}
|
||||
|
||||
#[sqlx::test(migrations = "./migrations")]
|
||||
async fn unlike(pool: sqlx::PgPool) {
|
||||
let (user, thought) = seed_user_and_thought(&pool).await;
|
||||
let repo = PgLikeRepository::new(pool);
|
||||
let like = Like {
|
||||
id: LikeId::new(),
|
||||
user_id: user.id.clone(),
|
||||
thought_id: thought.id.clone(),
|
||||
ap_id: None,
|
||||
created_at: Utc::now(),
|
||||
};
|
||||
repo.save(&like).await.unwrap();
|
||||
repo.delete(&user.id, &thought.id).await.unwrap();
|
||||
assert_eq!(repo.count_for_thought(&thought.id).await.unwrap(), 0);
|
||||
}
|
||||
@@ -159,72 +159,4 @@ impl NotificationRepository for PgNotificationRepository {
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::test_helpers;
|
||||
use chrono::Utc;
|
||||
use domain::{
|
||||
models::{notification::NotificationKind, user::User},
|
||||
value_objects::*,
|
||||
};
|
||||
|
||||
#[sqlx::test(migrations = "./migrations")]
|
||||
async fn save_and_list(pool: sqlx::PgPool) {
|
||||
let user = test_helpers::seed_user(&pool, "alice", "alice@ex.com").await;
|
||||
let from_user = test_helpers::seed_user(&pool, "bob", "bob@ex.com").await;
|
||||
let repo = PgNotificationRepository::new(pool);
|
||||
use domain::models::feed::PageParams;
|
||||
let n = Notification {
|
||||
id: NotificationId::new(),
|
||||
user_id: user.id.clone(),
|
||||
kind: NotificationKind::Follow {
|
||||
from_user_id: from_user.id.clone(),
|
||||
},
|
||||
read: false,
|
||||
created_at: Utc::now(),
|
||||
};
|
||||
repo.save(&n).await.unwrap();
|
||||
let page = repo
|
||||
.list_for_user(
|
||||
&user.id,
|
||||
&PageParams {
|
||||
page: 1,
|
||||
per_page: 20,
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(page.total, 1);
|
||||
assert!(!page.items[0].read);
|
||||
}
|
||||
|
||||
#[sqlx::test(migrations = "./migrations")]
|
||||
async fn mark_all_read(pool: sqlx::PgPool) {
|
||||
let user = test_helpers::seed_user(&pool, "alice", "alice@ex.com").await;
|
||||
let from_user = test_helpers::seed_user(&pool, "bob", "bob@ex.com").await;
|
||||
let repo = PgNotificationRepository::new(pool);
|
||||
use domain::models::feed::PageParams;
|
||||
let n = Notification {
|
||||
id: NotificationId::new(),
|
||||
user_id: user.id.clone(),
|
||||
kind: NotificationKind::Follow {
|
||||
from_user_id: from_user.id.clone(),
|
||||
},
|
||||
read: false,
|
||||
created_at: Utc::now(),
|
||||
};
|
||||
repo.save(&n).await.unwrap();
|
||||
repo.mark_all_read(&user.id).await.unwrap();
|
||||
let page = repo
|
||||
.list_for_user(
|
||||
&user.id,
|
||||
&PageParams {
|
||||
page: 1,
|
||||
per_page: 20,
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(page.items[0].read);
|
||||
}
|
||||
}
|
||||
mod tests;
|
||||
67
crates/adapters/postgres/src/notification/tests.rs
Normal file
67
crates/adapters/postgres/src/notification/tests.rs
Normal file
@@ -0,0 +1,67 @@
|
||||
use super::*;
|
||||
use crate::test_helpers;
|
||||
use chrono::Utc;
|
||||
use domain::{
|
||||
models::{notification::NotificationKind, user::User},
|
||||
value_objects::*,
|
||||
};
|
||||
|
||||
#[sqlx::test(migrations = "./migrations")]
|
||||
async fn save_and_list(pool: sqlx::PgPool) {
|
||||
let user = test_helpers::seed_user(&pool, "alice", "alice@ex.com").await;
|
||||
let from_user = test_helpers::seed_user(&pool, "bob", "bob@ex.com").await;
|
||||
let repo = PgNotificationRepository::new(pool);
|
||||
use domain::models::feed::PageParams;
|
||||
let n = Notification {
|
||||
id: NotificationId::new(),
|
||||
user_id: user.id.clone(),
|
||||
kind: NotificationKind::Follow {
|
||||
from_user_id: from_user.id.clone(),
|
||||
},
|
||||
read: false,
|
||||
created_at: Utc::now(),
|
||||
};
|
||||
repo.save(&n).await.unwrap();
|
||||
let page = repo
|
||||
.list_for_user(
|
||||
&user.id,
|
||||
&PageParams {
|
||||
page: 1,
|
||||
per_page: 20,
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(page.total, 1);
|
||||
assert!(!page.items[0].read);
|
||||
}
|
||||
|
||||
#[sqlx::test(migrations = "./migrations")]
|
||||
async fn mark_all_read(pool: sqlx::PgPool) {
|
||||
let user = test_helpers::seed_user(&pool, "alice", "alice@ex.com").await;
|
||||
let from_user = test_helpers::seed_user(&pool, "bob", "bob@ex.com").await;
|
||||
let repo = PgNotificationRepository::new(pool);
|
||||
use domain::models::feed::PageParams;
|
||||
let n = Notification {
|
||||
id: NotificationId::new(),
|
||||
user_id: user.id.clone(),
|
||||
kind: NotificationKind::Follow {
|
||||
from_user_id: from_user.id.clone(),
|
||||
},
|
||||
read: false,
|
||||
created_at: Utc::now(),
|
||||
};
|
||||
repo.save(&n).await.unwrap();
|
||||
repo.mark_all_read(&user.id).await.unwrap();
|
||||
let page = repo
|
||||
.list_for_user(
|
||||
&user.id,
|
||||
&PageParams {
|
||||
page: 1,
|
||||
per_page: 20,
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(page.items[0].read);
|
||||
}
|
||||
@@ -132,53 +132,4 @@ impl TagRepository for PgTagRepository {
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::{thought::PgThoughtRepository, user::PgUserRepository};
|
||||
use domain::ports::{ThoughtRepository, UserWriter};
|
||||
use domain::{
|
||||
models::{
|
||||
thought::{Thought, Visibility},
|
||||
user::User,
|
||||
},
|
||||
value_objects::*,
|
||||
};
|
||||
|
||||
#[sqlx::test(migrations = "./migrations")]
|
||||
async fn find_or_create_tag(pool: sqlx::PgPool) {
|
||||
let repo = PgTagRepository::new(pool);
|
||||
let t1 = repo.find_or_create("rust").await.unwrap();
|
||||
let t2 = repo.find_or_create("rust").await.unwrap();
|
||||
assert_eq!(t1.id, t2.id);
|
||||
assert_eq!(t1.name, "rust");
|
||||
}
|
||||
|
||||
#[sqlx::test(migrations = "./migrations")]
|
||||
async fn attach_and_list(pool: sqlx::PgPool) {
|
||||
let urepo = PgUserRepository::new(pool.clone());
|
||||
let trepo = PgThoughtRepository::new(pool.clone());
|
||||
let u = User::new_local(
|
||||
UserId::new(),
|
||||
Username::new("alice").unwrap(),
|
||||
Email::new("alice@ex.com").unwrap(),
|
||||
PasswordHash("h".into()),
|
||||
);
|
||||
urepo.save(&u).await.unwrap();
|
||||
let t = Thought::new_local(
|
||||
ThoughtId::new(),
|
||||
u.id.clone(),
|
||||
Content::new_local("hi").unwrap(),
|
||||
None,
|
||||
Visibility::Public,
|
||||
None,
|
||||
false,
|
||||
);
|
||||
trepo.save(&t).await.unwrap();
|
||||
let repo = PgTagRepository::new(pool);
|
||||
let tag = repo.find_or_create("greetings").await.unwrap();
|
||||
repo.attach_to_thought(&t.id, tag.id).await.unwrap();
|
||||
let tags = repo.list_for_thought(&t.id).await.unwrap();
|
||||
assert_eq!(tags.len(), 1);
|
||||
assert_eq!(tags[0].name, "greetings");
|
||||
}
|
||||
}
|
||||
mod tests;
|
||||
48
crates/adapters/postgres/src/tag/tests.rs
Normal file
48
crates/adapters/postgres/src/tag/tests.rs
Normal file
@@ -0,0 +1,48 @@
|
||||
use super::*;
|
||||
use crate::{thought::PgThoughtRepository, user::PgUserRepository};
|
||||
use domain::ports::{ThoughtRepository, UserWriter};
|
||||
use domain::{
|
||||
models::{
|
||||
thought::{Thought, Visibility},
|
||||
user::User,
|
||||
},
|
||||
value_objects::*,
|
||||
};
|
||||
|
||||
#[sqlx::test(migrations = "./migrations")]
|
||||
async fn find_or_create_tag(pool: sqlx::PgPool) {
|
||||
let repo = PgTagRepository::new(pool);
|
||||
let t1 = repo.find_or_create("rust").await.unwrap();
|
||||
let t2 = repo.find_or_create("rust").await.unwrap();
|
||||
assert_eq!(t1.id, t2.id);
|
||||
assert_eq!(t1.name, "rust");
|
||||
}
|
||||
|
||||
#[sqlx::test(migrations = "./migrations")]
|
||||
async fn attach_and_list(pool: sqlx::PgPool) {
|
||||
let urepo = PgUserRepository::new(pool.clone());
|
||||
let trepo = PgThoughtRepository::new(pool.clone());
|
||||
let u = User::new_local(
|
||||
UserId::new(),
|
||||
Username::new("alice").unwrap(),
|
||||
Email::new("alice@ex.com").unwrap(),
|
||||
PasswordHash("h".into()),
|
||||
);
|
||||
urepo.save(&u).await.unwrap();
|
||||
let t = Thought::new_local(
|
||||
ThoughtId::new(),
|
||||
u.id.clone(),
|
||||
Content::new_local("hi").unwrap(),
|
||||
None,
|
||||
Visibility::Public,
|
||||
None,
|
||||
false,
|
||||
);
|
||||
trepo.save(&t).await.unwrap();
|
||||
let repo = PgTagRepository::new(pool);
|
||||
let tag = repo.find_or_create("greetings").await.unwrap();
|
||||
repo.attach_to_thought(&t.id, tag.id).await.unwrap();
|
||||
let tags = repo.list_for_thought(&t.id).await.unwrap();
|
||||
assert_eq!(tags.len(), 1);
|
||||
assert_eq!(tags[0].name, "greetings");
|
||||
}
|
||||
@@ -168,95 +168,4 @@ impl ThoughtRepository for PgThoughtRepository {
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::test_helpers::seed_user;
|
||||
use domain::{
|
||||
models::thought::{Thought, Visibility},
|
||||
value_objects::*,
|
||||
};
|
||||
|
||||
#[sqlx::test(migrations = "./migrations")]
|
||||
async fn save_and_find_thought(pool: sqlx::PgPool) {
|
||||
let user = seed_user(&pool, "alice", "alice@ex.com").await;
|
||||
let repo = PgThoughtRepository::new(pool);
|
||||
let t = Thought::new_local(
|
||||
ThoughtId::new(),
|
||||
user.id.clone(),
|
||||
Content::new_local("hello world").unwrap(),
|
||||
None,
|
||||
Visibility::Public,
|
||||
None,
|
||||
false,
|
||||
);
|
||||
repo.save(&t).await.unwrap();
|
||||
let found = repo.find_by_id(&t.id).await.unwrap().unwrap();
|
||||
assert_eq!(found.content.as_str(), "hello world");
|
||||
assert!(found.local);
|
||||
}
|
||||
|
||||
#[sqlx::test(migrations = "./migrations")]
|
||||
async fn delete_thought(pool: sqlx::PgPool) {
|
||||
let user = seed_user(&pool, "bob", "bob@ex.com").await;
|
||||
let repo = PgThoughtRepository::new(pool);
|
||||
let t = Thought::new_local(
|
||||
ThoughtId::new(),
|
||||
user.id.clone(),
|
||||
Content::new_local("bye").unwrap(),
|
||||
None,
|
||||
Visibility::Public,
|
||||
None,
|
||||
false,
|
||||
);
|
||||
repo.save(&t).await.unwrap();
|
||||
repo.delete(&t.id, &user.id).await.unwrap();
|
||||
assert!(repo.find_by_id(&t.id).await.unwrap().is_none());
|
||||
}
|
||||
|
||||
#[sqlx::test(migrations = "./migrations")]
|
||||
async fn delete_wrong_owner_returns_not_found(pool: sqlx::PgPool) {
|
||||
let alice = seed_user(&pool, "alice", "alice@ex.com").await;
|
||||
let bob = seed_user(&pool, "bob", "bob@ex.com").await;
|
||||
let repo = PgThoughtRepository::new(pool);
|
||||
let t = Thought::new_local(
|
||||
ThoughtId::new(),
|
||||
alice.id.clone(),
|
||||
Content::new_local("secret").unwrap(),
|
||||
None,
|
||||
Visibility::Public,
|
||||
None,
|
||||
false,
|
||||
);
|
||||
repo.save(&t).await.unwrap();
|
||||
let err = repo.delete(&t.id, &bob.id).await.unwrap_err();
|
||||
assert!(matches!(err, DomainError::NotFound));
|
||||
}
|
||||
|
||||
#[sqlx::test(migrations = "./migrations")]
|
||||
async fn get_thread_returns_root_and_replies(pool: sqlx::PgPool) {
|
||||
let user = seed_user(&pool, "charlie", "charlie@ex.com").await;
|
||||
let repo = PgThoughtRepository::new(pool);
|
||||
let root = Thought::new_local(
|
||||
ThoughtId::new(),
|
||||
user.id.clone(),
|
||||
Content::new_local("root").unwrap(),
|
||||
None,
|
||||
Visibility::Public,
|
||||
None,
|
||||
false,
|
||||
);
|
||||
let reply = Thought::new_local(
|
||||
ThoughtId::new(),
|
||||
user.id.clone(),
|
||||
Content::new_local("reply").unwrap(),
|
||||
Some(root.id.clone()),
|
||||
Visibility::Public,
|
||||
None,
|
||||
false,
|
||||
);
|
||||
repo.save(&root).await.unwrap();
|
||||
repo.save(&reply).await.unwrap();
|
||||
let thread = repo.get_thread(&root.id).await.unwrap();
|
||||
assert_eq!(thread.len(), 2);
|
||||
}
|
||||
}
|
||||
mod tests;
|
||||
90
crates/adapters/postgres/src/thought/tests.rs
Normal file
90
crates/adapters/postgres/src/thought/tests.rs
Normal file
@@ -0,0 +1,90 @@
|
||||
use super::*;
|
||||
use crate::test_helpers::seed_user;
|
||||
use domain::{
|
||||
models::thought::{Thought, Visibility},
|
||||
value_objects::*,
|
||||
};
|
||||
|
||||
#[sqlx::test(migrations = "./migrations")]
|
||||
async fn save_and_find_thought(pool: sqlx::PgPool) {
|
||||
let user = seed_user(&pool, "alice", "alice@ex.com").await;
|
||||
let repo = PgThoughtRepository::new(pool);
|
||||
let t = Thought::new_local(
|
||||
ThoughtId::new(),
|
||||
user.id.clone(),
|
||||
Content::new_local("hello world").unwrap(),
|
||||
None,
|
||||
Visibility::Public,
|
||||
None,
|
||||
false,
|
||||
);
|
||||
repo.save(&t).await.unwrap();
|
||||
let found = repo.find_by_id(&t.id).await.unwrap().unwrap();
|
||||
assert_eq!(found.content.as_str(), "hello world");
|
||||
assert!(found.local);
|
||||
}
|
||||
|
||||
#[sqlx::test(migrations = "./migrations")]
|
||||
async fn delete_thought(pool: sqlx::PgPool) {
|
||||
let user = seed_user(&pool, "bob", "bob@ex.com").await;
|
||||
let repo = PgThoughtRepository::new(pool);
|
||||
let t = Thought::new_local(
|
||||
ThoughtId::new(),
|
||||
user.id.clone(),
|
||||
Content::new_local("bye").unwrap(),
|
||||
None,
|
||||
Visibility::Public,
|
||||
None,
|
||||
false,
|
||||
);
|
||||
repo.save(&t).await.unwrap();
|
||||
repo.delete(&t.id, &user.id).await.unwrap();
|
||||
assert!(repo.find_by_id(&t.id).await.unwrap().is_none());
|
||||
}
|
||||
|
||||
#[sqlx::test(migrations = "./migrations")]
|
||||
async fn delete_wrong_owner_returns_not_found(pool: sqlx::PgPool) {
|
||||
let alice = seed_user(&pool, "alice", "alice@ex.com").await;
|
||||
let bob = seed_user(&pool, "bob", "bob@ex.com").await;
|
||||
let repo = PgThoughtRepository::new(pool);
|
||||
let t = Thought::new_local(
|
||||
ThoughtId::new(),
|
||||
alice.id.clone(),
|
||||
Content::new_local("secret").unwrap(),
|
||||
None,
|
||||
Visibility::Public,
|
||||
None,
|
||||
false,
|
||||
);
|
||||
repo.save(&t).await.unwrap();
|
||||
let err = repo.delete(&t.id, &bob.id).await.unwrap_err();
|
||||
assert!(matches!(err, DomainError::NotFound));
|
||||
}
|
||||
|
||||
#[sqlx::test(migrations = "./migrations")]
|
||||
async fn get_thread_returns_root_and_replies(pool: sqlx::PgPool) {
|
||||
let user = seed_user(&pool, "charlie", "charlie@ex.com").await;
|
||||
let repo = PgThoughtRepository::new(pool);
|
||||
let root = Thought::new_local(
|
||||
ThoughtId::new(),
|
||||
user.id.clone(),
|
||||
Content::new_local("root").unwrap(),
|
||||
None,
|
||||
Visibility::Public,
|
||||
None,
|
||||
false,
|
||||
);
|
||||
let reply = Thought::new_local(
|
||||
ThoughtId::new(),
|
||||
user.id.clone(),
|
||||
Content::new_local("reply").unwrap(),
|
||||
Some(root.id.clone()),
|
||||
Visibility::Public,
|
||||
None,
|
||||
false,
|
||||
);
|
||||
repo.save(&root).await.unwrap();
|
||||
repo.save(&reply).await.unwrap();
|
||||
let thread = repo.get_thread(&root.id).await.unwrap();
|
||||
assert_eq!(thread.len(), 2);
|
||||
}
|
||||
@@ -104,52 +104,4 @@ impl TopFriendRepository for PgTopFriendRepository {
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::user::PgUserRepository;
|
||||
use domain::ports::UserWriter;
|
||||
use domain::{models::user::User, value_objects::*};
|
||||
|
||||
async fn seed_user(pool: &sqlx::PgPool, username: &str, email: &str) -> User {
|
||||
let repo = PgUserRepository::new(pool.clone());
|
||||
let u = User::new_local(
|
||||
UserId::new(),
|
||||
Username::new(username).unwrap(),
|
||||
Email::new(email).unwrap(),
|
||||
PasswordHash("h".into()),
|
||||
);
|
||||
repo.save(&u).await.unwrap();
|
||||
u
|
||||
}
|
||||
|
||||
#[sqlx::test(migrations = "./migrations")]
|
||||
async fn set_and_list_top_friends(pool: sqlx::PgPool) {
|
||||
let alice = seed_user(&pool, "alice", "alice@ex.com").await;
|
||||
let bob = seed_user(&pool, "bob", "bob@ex.com").await;
|
||||
let repo = PgTopFriendRepository::new(pool);
|
||||
repo.set_top_friends(&alice.id, vec![(bob.id.clone(), 1)])
|
||||
.await
|
||||
.unwrap();
|
||||
let friends = repo.list_for_user(&alice.id).await.unwrap();
|
||||
assert_eq!(friends.len(), 1);
|
||||
assert_eq!(friends[0].0.position, 1);
|
||||
assert_eq!(friends[0].1.username.as_str(), "bob");
|
||||
}
|
||||
|
||||
#[sqlx::test(migrations = "./migrations")]
|
||||
async fn replace_top_friends(pool: sqlx::PgPool) {
|
||||
let alice = seed_user(&pool, "alice", "alice@ex.com").await;
|
||||
let bob = seed_user(&pool, "bob", "bob@ex.com").await;
|
||||
let carol = seed_user(&pool, "carol", "carol@ex.com").await;
|
||||
let repo = PgTopFriendRepository::new(pool);
|
||||
repo.set_top_friends(&alice.id, vec![(bob.id.clone(), 1)])
|
||||
.await
|
||||
.unwrap();
|
||||
repo.set_top_friends(&alice.id, vec![(carol.id.clone(), 1)])
|
||||
.await
|
||||
.unwrap();
|
||||
let friends = repo.list_for_user(&alice.id).await.unwrap();
|
||||
assert_eq!(friends.len(), 1);
|
||||
assert_eq!(friends[0].1.username.as_str(), "carol");
|
||||
}
|
||||
}
|
||||
mod tests;
|
||||
47
crates/adapters/postgres/src/top_friend/tests.rs
Normal file
47
crates/adapters/postgres/src/top_friend/tests.rs
Normal file
@@ -0,0 +1,47 @@
|
||||
use super::*;
|
||||
use crate::user::PgUserRepository;
|
||||
use domain::ports::UserWriter;
|
||||
use domain::{models::user::User, value_objects::*};
|
||||
|
||||
async fn seed_user(pool: &sqlx::PgPool, username: &str, email: &str) -> User {
|
||||
let repo = PgUserRepository::new(pool.clone());
|
||||
let u = User::new_local(
|
||||
UserId::new(),
|
||||
Username::new(username).unwrap(),
|
||||
Email::new(email).unwrap(),
|
||||
PasswordHash("h".into()),
|
||||
);
|
||||
repo.save(&u).await.unwrap();
|
||||
u
|
||||
}
|
||||
|
||||
#[sqlx::test(migrations = "./migrations")]
|
||||
async fn set_and_list_top_friends(pool: sqlx::PgPool) {
|
||||
let alice = seed_user(&pool, "alice", "alice@ex.com").await;
|
||||
let bob = seed_user(&pool, "bob", "bob@ex.com").await;
|
||||
let repo = PgTopFriendRepository::new(pool);
|
||||
repo.set_top_friends(&alice.id, vec![(bob.id.clone(), 1)])
|
||||
.await
|
||||
.unwrap();
|
||||
let friends = repo.list_for_user(&alice.id).await.unwrap();
|
||||
assert_eq!(friends.len(), 1);
|
||||
assert_eq!(friends[0].0.position, 1);
|
||||
assert_eq!(friends[0].1.username.as_str(), "bob");
|
||||
}
|
||||
|
||||
#[sqlx::test(migrations = "./migrations")]
|
||||
async fn replace_top_friends(pool: sqlx::PgPool) {
|
||||
let alice = seed_user(&pool, "alice", "alice@ex.com").await;
|
||||
let bob = seed_user(&pool, "bob", "bob@ex.com").await;
|
||||
let carol = seed_user(&pool, "carol", "carol@ex.com").await;
|
||||
let repo = PgTopFriendRepository::new(pool);
|
||||
repo.set_top_friends(&alice.id, vec![(bob.id.clone(), 1)])
|
||||
.await
|
||||
.unwrap();
|
||||
repo.set_top_friends(&alice.id, vec![(carol.id.clone(), 1)])
|
||||
.await
|
||||
.unwrap();
|
||||
let friends = repo.list_for_user(&alice.id).await.unwrap();
|
||||
assert_eq!(friends.len(), 1);
|
||||
assert_eq!(friends[0].1.username.as_str(), "carol");
|
||||
}
|
||||
@@ -279,74 +279,4 @@ impl UserWriter for PgUserRepository {
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use domain::{models::user::User, value_objects::*};
|
||||
|
||||
#[sqlx::test(migrations = "./migrations")]
|
||||
async fn save_and_find_by_id(pool: sqlx::PgPool) {
|
||||
let repo = PgUserRepository::new(pool);
|
||||
let user = User::new_local(
|
||||
UserId::new(),
|
||||
Username::new("alice").unwrap(),
|
||||
Email::new("alice@ex.com").unwrap(),
|
||||
PasswordHash("hash".into()),
|
||||
);
|
||||
repo.save(&user).await.unwrap();
|
||||
let found = repo.find_by_id(&user.id).await.unwrap().unwrap();
|
||||
assert_eq!(found.username.as_str(), "alice");
|
||||
assert_eq!(found.email.as_str(), "alice@ex.com");
|
||||
}
|
||||
|
||||
#[sqlx::test(migrations = "./migrations")]
|
||||
async fn find_by_username_returns_none_when_missing(pool: sqlx::PgPool) {
|
||||
let repo = PgUserRepository::new(pool);
|
||||
let result = repo
|
||||
.find_by_username(&Username::new("ghost").unwrap())
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(result.is_none());
|
||||
}
|
||||
|
||||
#[sqlx::test(migrations = "./migrations")]
|
||||
async fn find_by_email(pool: sqlx::PgPool) {
|
||||
let repo = PgUserRepository::new(pool);
|
||||
let user = User::new_local(
|
||||
UserId::new(),
|
||||
Username::new("bob").unwrap(),
|
||||
Email::new("bob@ex.com").unwrap(),
|
||||
PasswordHash("hash".into()),
|
||||
);
|
||||
repo.save(&user).await.unwrap();
|
||||
let found = repo
|
||||
.find_by_email(&Email::new("bob@ex.com").unwrap())
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(found.is_some());
|
||||
}
|
||||
|
||||
#[sqlx::test(migrations = "./migrations")]
|
||||
async fn update_profile_changes_fields(pool: sqlx::PgPool) {
|
||||
let repo = PgUserRepository::new(pool);
|
||||
let user = User::new_local(
|
||||
UserId::new(),
|
||||
Username::new("charlie").unwrap(),
|
||||
Email::new("charlie@ex.com").unwrap(),
|
||||
PasswordHash("hash".into()),
|
||||
);
|
||||
repo.save(&user).await.unwrap();
|
||||
repo.update_profile(
|
||||
&user.id,
|
||||
Some("Charlie".into()),
|
||||
Some("bio".into()),
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let found = repo.find_by_id(&user.id).await.unwrap().unwrap();
|
||||
assert_eq!(found.display_name.as_deref(), Some("Charlie"));
|
||||
assert_eq!(found.bio.as_deref(), Some("bio"));
|
||||
}
|
||||
}
|
||||
mod tests;
|
||||
69
crates/adapters/postgres/src/user/tests.rs
Normal file
69
crates/adapters/postgres/src/user/tests.rs
Normal file
@@ -0,0 +1,69 @@
|
||||
use super::*;
|
||||
use domain::{models::user::User, value_objects::*};
|
||||
|
||||
#[sqlx::test(migrations = "./migrations")]
|
||||
async fn save_and_find_by_id(pool: sqlx::PgPool) {
|
||||
let repo = PgUserRepository::new(pool);
|
||||
let user = User::new_local(
|
||||
UserId::new(),
|
||||
Username::new("alice").unwrap(),
|
||||
Email::new("alice@ex.com").unwrap(),
|
||||
PasswordHash("hash".into()),
|
||||
);
|
||||
repo.save(&user).await.unwrap();
|
||||
let found = repo.find_by_id(&user.id).await.unwrap().unwrap();
|
||||
assert_eq!(found.username.as_str(), "alice");
|
||||
assert_eq!(found.email.as_str(), "alice@ex.com");
|
||||
}
|
||||
|
||||
#[sqlx::test(migrations = "./migrations")]
|
||||
async fn find_by_username_returns_none_when_missing(pool: sqlx::PgPool) {
|
||||
let repo = PgUserRepository::new(pool);
|
||||
let result = repo
|
||||
.find_by_username(&Username::new("ghost").unwrap())
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(result.is_none());
|
||||
}
|
||||
|
||||
#[sqlx::test(migrations = "./migrations")]
|
||||
async fn find_by_email(pool: sqlx::PgPool) {
|
||||
let repo = PgUserRepository::new(pool);
|
||||
let user = User::new_local(
|
||||
UserId::new(),
|
||||
Username::new("bob").unwrap(),
|
||||
Email::new("bob@ex.com").unwrap(),
|
||||
PasswordHash("hash".into()),
|
||||
);
|
||||
repo.save(&user).await.unwrap();
|
||||
let found = repo
|
||||
.find_by_email(&Email::new("bob@ex.com").unwrap())
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(found.is_some());
|
||||
}
|
||||
|
||||
#[sqlx::test(migrations = "./migrations")]
|
||||
async fn update_profile_changes_fields(pool: sqlx::PgPool) {
|
||||
let repo = PgUserRepository::new(pool);
|
||||
let user = User::new_local(
|
||||
UserId::new(),
|
||||
Username::new("charlie").unwrap(),
|
||||
Email::new("charlie@ex.com").unwrap(),
|
||||
PasswordHash("hash".into()),
|
||||
);
|
||||
repo.save(&user).await.unwrap();
|
||||
repo.update_profile(
|
||||
&user.id,
|
||||
Some("Charlie".into()),
|
||||
Some("bio".into()),
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let found = repo.find_by_id(&user.id).await.unwrap().unwrap();
|
||||
assert_eq!(found.display_name.as_deref(), Some("Charlie"));
|
||||
assert_eq!(found.bio.as_deref(), Some("bio"));
|
||||
}
|
||||
Reference in New Issue
Block a user