diff --git a/jarust/tests/connection.rs b/jarust/tests/connection.rs index ea5160c..c92dad0 100644 --- a/jarust/tests/connection.rs +++ b/jarust/tests/connection.rs @@ -3,17 +3,16 @@ mod mocks; #[cfg(test)] mod tests { - use crate::mocks::mock_connection::mock_connection; use crate::mocks::mock_generate_transaction::MockGenerateTransaction; use crate::mocks::mock_interface::MockInterface; use jarust::error::JaError; use jarust::jaconnection::CreateConnectionParams; + use jarust::prelude::JaResponse; use jarust_transport::error::JaTransportError; use jarust_transport::interface::janus_interface::ConnectionParams; use jarust_transport::interface::janus_interface::JanusInterface; use jarust_transport::japrotocol::ErrorResponse; use jarust_transport::japrotocol::JaData; - use jarust_transport::japrotocol::JaResponse; use jarust_transport::japrotocol::JaSuccessProtocol; use jarust_transport::japrotocol::ResponseType; use std::time::Duration; @@ -36,23 +35,30 @@ mod tests { #[tokio::test] async fn it_successfully_creates_session() { - let (interface, server) = MockInterface::interface_server_pair().await.unwrap(); - let mut generator = MockGenerateTransaction::new(); - generator.next_transaction("abc123"); - let mut connection = mock_connection(interface).await.unwrap(); + let conn_params = ConnectionParams { + url: "mock://some.janus.com".to_string(), + capacity: 10, + apisecret: None, + namespace: "mock".to_string(), + }; + let transaction_generator = MockGenerateTransaction::new(); + let interface = MockInterface::make_interface(conn_params, transaction_generator) + .await + .unwrap(); + let mut connection = jarust::custom_connect(interface.clone()).await.unwrap(); - let msg = serde_json::to_string(&JaResponse { + let response = JaResponse { janus: ResponseType::Success(JaSuccessProtocol::Data { - data: JaData { id: 2 }, + data: JaData { id: 73 }, }), transaction: Some("abc123".to_string()), session_id: None, sender: None, establishment_protocol: None, - }) - .unwrap(); + }; + + interface.mock_create_rsp(response).await; - server.mock_send_to_client(&msg).await; let session = connection .create(CreateConnectionParams { ka_interval: 10, @@ -65,12 +71,19 @@ mod tests { #[tokio::test] async fn it_fails_to_create_session_with_janus_error() { - let (interface, server) = MockInterface::interface_server_pair().await.unwrap(); - let mut generator = MockGenerateTransaction::new(); - generator.next_transaction("abc123"); - let mut connection = mock_connection(interface).await.unwrap(); + let conn_params = ConnectionParams { + url: "mock://some.janus.com".to_string(), + capacity: 10, + apisecret: None, + namespace: "mock".to_string(), + }; + let transaction_generator = MockGenerateTransaction::new(); + let interface = MockInterface::make_interface(conn_params, transaction_generator) + .await + .unwrap(); + let mut connection = jarust::custom_connect(interface.clone()).await.unwrap(); - let msg = serde_json::to_string(&JaResponse { + let response = JaResponse { janus: ResponseType::Error { error: ErrorResponse { code: 0, @@ -81,10 +94,10 @@ mod tests { session_id: None, sender: None, establishment_protocol: None, - }) - .unwrap(); + }; + + interface.mock_create_rsp(response).await; - server.mock_send_to_client(&msg).await; let session = connection .create(CreateConnectionParams { ka_interval: 10, diff --git a/jarust/tests/handle.rs b/jarust/tests/handle.rs index 2494b28..7c89a7c 100644 --- a/jarust/tests/handle.rs +++ b/jarust/tests/handle.rs @@ -3,71 +3,89 @@ mod mocks; #[cfg(test)] mod tests { - use crate::fixtures::FIXTURE_HANDLE_ID; - use crate::fixtures::FIXTURE_KA_INTERVAL; - use crate::fixtures::FIXTURE_PLUGIN_ID; - use crate::fixtures::FIXTURE_SESSION_ID; - use crate::fixtures::FIXTURE_TIMEOUT; - use crate::mocks::mock_connection::mock_connection; use crate::mocks::mock_generate_transaction::MockGenerateTransaction; - use crate::mocks::mock_handle::mock_handle; - use crate::mocks::mock_handle::MockHandleConfig; use crate::mocks::mock_interface::MockInterface; - use crate::mocks::mock_session::mock_session; - use crate::mocks::mock_session::MockSessionConfig; + use jarust::jaconnection::CreateConnectionParams; + use jarust::japlugin::AttachHandleParams; + use jarust::prelude::Attach; + use jarust::prelude::JaResponse; + use jarust_transport::interface::janus_interface::ConnectionParams; + use jarust_transport::interface::janus_interface::JanusInterface; use jarust_transport::japrotocol::GenericEvent; + use jarust_transport::japrotocol::JaData; use jarust_transport::japrotocol::JaHandleEvent; - use jarust_transport::japrotocol::JaResponse; + use jarust_transport::japrotocol::JaSuccessProtocol; use jarust_transport::japrotocol::ResponseType; + use std::time::Duration; #[tokio::test] async fn it_receives_incoming_handle_events() { - let (interface, server) = MockInterface::interface_server_pair().await.unwrap(); - let mut generator = MockGenerateTransaction::new(); - generator.next_transaction("mock-connection-transaction"); - let connection = mock_connection(interface).await.unwrap(); + let conn_params = ConnectionParams { + url: "mock://some.janus.com".to_string(), + capacity: 10, + apisecret: None, + namespace: "mock".to_string(), + }; + let transaction_generator = MockGenerateTransaction::new(); + let interface = MockInterface::make_interface(conn_params, transaction_generator) + .await + .unwrap(); + let mut connection = jarust::custom_connect(interface.clone()).await.unwrap(); - generator.next_transaction("mock-session-transaction"); - let session = mock_session( - connection, - &server, - MockSessionConfig { - session_id: FIXTURE_SESSION_ID, - ka_interval: FIXTURE_KA_INTERVAL, - timeout: FIXTURE_TIMEOUT, - }, - "mock-session-transaction", - ) - .await - .unwrap(); + let session_id = 73; + let handle_id = 77; - generator.next_transaction("mock-handle-transaction"); - let (_handle, mut stream) = mock_handle( - session, - &server, - MockHandleConfig { - session_id: FIXTURE_SESSION_ID, - handle_id: FIXTURE_HANDLE_ID, - plugin_id: FIXTURE_PLUGIN_ID.to_string(), - timeout: FIXTURE_TIMEOUT, - }, - "mock-handle-transaction", - ) - .await - .unwrap(); + let response = JaResponse { + janus: ResponseType::Success(JaSuccessProtocol::Data { + data: JaData { id: session_id }, + }), + transaction: Some("abc123".to_string()), + session_id: None, + sender: None, + establishment_protocol: None, + }; + interface.mock_create_rsp(response).await; + + let session = connection + .create(CreateConnectionParams { + ka_interval: 10, + timeout: Duration::from_secs(10), + }) + .await + .unwrap(); - let event = serde_json::to_string(&JaResponse { - janus: ResponseType::Event(JaHandleEvent::GenericEvent(GenericEvent::Detached)), - transaction: Some("mock-event-transaction".to_string()), - session_id: Some(FIXTURE_SESSION_ID), - sender: Some(FIXTURE_HANDLE_ID), + let response = JaResponse { + janus: ResponseType::Success(JaSuccessProtocol::Data { + data: JaData { id: 77 }, + }), + transaction: Some("mock-attach-plugin-transaction".to_string()), + session_id: Some(session_id), + sender: None, establishment_protocol: None, - }) - .unwrap(); - server.mock_send_to_client(&event).await; + }; + interface.mock_attach_rsp(response).await; - let incoming_event = stream.recv().await.unwrap(); + let (_handle, mut stream) = session + .attach(AttachHandleParams { + plugin_id: "mock.plugin.test".to_string(), + timeout: Duration::from_secs(5), + }) + .await + .unwrap(); + interface + .mock_event( + 77, + JaResponse { + janus: ResponseType::Event(JaHandleEvent::GenericEvent(GenericEvent::Detached)), + transaction: Some("mock-event-transaction".to_string()), + session_id: Some(session_id), + sender: Some(handle_id), + establishment_protocol: None, + }, + ) + .await; + let incoming_event = stream.recv().await.unwrap(); assert_eq!( incoming_event.janus, ResponseType::Event(JaHandleEvent::GenericEvent(GenericEvent::Detached)) diff --git a/jarust/tests/mocks/mock_connection.rs b/jarust/tests/mocks/mock_connection.rs deleted file mode 100644 index 59d5cfb..0000000 --- a/jarust/tests/mocks/mock_connection.rs +++ /dev/null @@ -1,9 +0,0 @@ -use super::mock_interface::MockInterface; -use jarust::jaconnection::JaConnection; -use jarust::prelude::JaResult; - -#[allow(dead_code)] -pub async fn mock_connection(interface: MockInterface) -> JaResult { - let connection = jarust::custom_connect(interface).await?; - Ok(connection) -} diff --git a/jarust/tests/mocks/mock_generate_transaction.rs b/jarust/tests/mocks/mock_generate_transaction.rs index 83561fc..63e01ed 100644 --- a/jarust/tests/mocks/mock_generate_transaction.rs +++ b/jarust/tests/mocks/mock_generate_transaction.rs @@ -21,6 +21,7 @@ impl MockGenerateTransaction { } } + #[allow(dead_code)] pub fn next_transaction(&mut self, transaction: &str) { self.inner.lock().unwrap().next_transaction = Some(transaction.to_string()); } diff --git a/jarust/tests/mocks/mock_handle.rs b/jarust/tests/mocks/mock_handle.rs deleted file mode 100644 index 042411f..0000000 --- a/jarust/tests/mocks/mock_handle.rs +++ /dev/null @@ -1,45 +0,0 @@ -use super::mock_interface::MockServer; -use jarust::japlugin::AttachHandleParams; -use jarust::prelude::*; -use jarust_transport::japrotocol::JaData; -use jarust_transport::japrotocol::JaSuccessProtocol; -use jarust_transport::japrotocol::ResponseType; -use std::time::Duration; -use tokio::sync::mpsc; - -pub struct MockHandleConfig { - pub session_id: u64, - pub handle_id: u64, - pub plugin_id: String, - pub timeout: Duration, -} - -#[allow(dead_code)] -pub async fn mock_handle( - session: JaSession, - server: &MockServer, - config: MockHandleConfig, - expected_transaction: &str, -) -> JaResult<(JaHandle, mpsc::UnboundedReceiver)> { - let attachment_msg = serde_json::to_string(&JaResponse { - janus: ResponseType::Success(JaSuccessProtocol::Data { - data: JaData { - id: config.handle_id, - }, - }), - transaction: Some(expected_transaction.to_string()), - session_id: Some(config.session_id), - sender: None, - establishment_protocol: None, - }) - .unwrap(); - server.mock_send_to_client(&attachment_msg).await; - let (handle, stream) = session - .attach(AttachHandleParams { - plugin_id: config.plugin_id, - timeout: config.timeout, - }) - .await?; - - Ok((handle, stream)) -} diff --git a/jarust/tests/mocks/mock_interface.rs b/jarust/tests/mocks/mock_interface.rs index f0455ae..4c18f86 100644 --- a/jarust/tests/mocks/mock_interface.rs +++ b/jarust/tests/mocks/mock_interface.rs @@ -1,11 +1,5 @@ -use super::mock_generate_transaction::MockGenerateTransaction; use async_trait::async_trait; -use bytes::BufMut; -use bytes::Bytes; -use bytes::BytesMut; -use jarust::error::JaError; use jarust::prelude::JaResponse; -use jarust::prelude::JaResult; use jarust::GenerateTransaction; use jarust_transport::error::JaTransportError; use jarust_transport::handle_msg::HandleMessage; @@ -14,50 +8,48 @@ use jarust_transport::handle_msg::HandleMessageWithEstablishmentAndTimeout; use jarust_transport::handle_msg::HandleMessageWithTimeout; use jarust_transport::interface::janus_interface::ConnectionParams; use jarust_transport::interface::janus_interface::JanusInterface; +use jarust_transport::japrotocol::JaSuccessProtocol; +use jarust_transport::japrotocol::ResponseType; use jarust_transport::prelude::JaTransportResult; use jarust_transport::respones::ServerInfoRsp; +use std::collections::HashMap; use std::fmt::Debug; +use std::sync::Arc; use std::time::Duration; use tokio::sync::mpsc; - -#[derive(Debug)] -pub struct MockServer { - tx: mpsc::UnboundedSender, +use tokio::sync::mpsc::UnboundedSender; +use tokio::sync::Mutex; + +#[derive(Debug, Default)] +pub struct Exclusive { + create_rsp: Option, + attach_rsp: Option, + handles_rx: HashMap>, } -impl MockServer { - pub async fn mock_send_to_client(&self, msg: &str) { - let mut bytes = BytesMut::new(); - bytes.put_slice(msg.as_bytes()); - self.tx.send(bytes.into()).unwrap(); - } +#[derive(Debug, Default)] +pub struct InnerMockInterface { + exclusive: Mutex, } -#[derive(Debug)] +#[derive(Debug, Default, Clone)] pub struct MockInterface { - server: Option, + inner: Arc, } +#[allow(dead_code)] impl MockInterface { - pub fn get_mock_server(&mut self) -> Option { - self.server.take() + pub async fn mock_create_rsp(&self, rsp: JaResponse) { + self.inner.exclusive.lock().await.create_rsp = Some(rsp); } - pub async fn interface_server_pair() -> JaResult<(Self, MockServer)> { - let conn_params = ConnectionParams { - url: "mock://some.janus.com".to_string(), - capacity: 10, - apisecret: None, - namespace: "mock".to_string(), - }; - let transaction_generator = MockGenerateTransaction::new(); - let mut interface = - MockInterface::make_interface(conn_params, transaction_generator).await?; - match interface.get_mock_server() { - Some(server) => Ok((interface, server)), - None => Err(JaError::JanusTransport( - JaTransportError::TransportNotOpened, - )), + pub async fn mock_attach_rsp(&self, rsp: JaResponse) { + self.inner.exclusive.lock().await.attach_rsp = Some(rsp); + } + + pub async fn mock_event(&self, handle_id: u64, rsp: JaResponse) { + if let Some(tx) = self.inner.exclusive.lock().await.handles_rx.get(&handle_id) { + tx.send(rsp).unwrap(); } } } @@ -71,15 +63,33 @@ impl JanusInterface for MockInterface { where Self: Sized, { + let exclusive = Mutex::new(Exclusive::default()); + let inner = InnerMockInterface { exclusive }; Ok(Self { - server: Some(MockServer { - tx: mpsc::unbounded_channel().0, - }), + inner: Arc::new(inner), }) } async fn create(&self, _timeout: Duration) -> JaTransportResult { - todo!("Create is not implemented"); + let Some(rsp) = self.inner.exclusive.lock().await.create_rsp.clone() else { + panic!("Create response is not set"); + }; + let session_id = match rsp.janus { + ResponseType::Success(JaSuccessProtocol::Data { data }) => data.id, + ResponseType::Error { error } => { + let what = JaTransportError::JanusError { + code: error.code, + reason: error.reason, + }; + tracing::error!("{what}"); + return Err(what); + } + _ => { + tracing::error!("Unexpected response"); + return Err(JaTransportError::UnexpectedResponse); + } + }; + Ok(session_id) } async fn server_info(&self, _timeout: Duration) -> JaTransportResult { @@ -92,7 +102,32 @@ impl JanusInterface for MockInterface { _plugin_id: String, _timeout: Duration, ) -> JaTransportResult<(u64, mpsc::UnboundedReceiver)> { - todo!("Attach is not implemented"); + let Some(rsp) = self.inner.exclusive.lock().await.attach_rsp.clone() else { + panic!("Attach response is not set"); + }; + let handle_id = match rsp.janus { + ResponseType::Success(JaSuccessProtocol::Data { data }) => data.id, + ResponseType::Error { error } => { + let what = JaTransportError::JanusError { + code: error.code, + reason: error.reason, + }; + tracing::error!("{what}"); + return Err(what); + } + _ => { + tracing::error!("Unexpected response"); + return Err(JaTransportError::UnexpectedResponse); + } + }; + let (tx, rx) = mpsc::unbounded_channel(); + self.inner + .exclusive + .lock() + .await + .handles_rx + .insert(handle_id, tx); + Ok((handle_id, rx)) } async fn keep_alive(&self, _session_id: u64, _timeout: Duration) -> JaTransportResult<()> { diff --git a/jarust/tests/mocks/mock_session.rs b/jarust/tests/mocks/mock_session.rs deleted file mode 100644 index 033c680..0000000 --- a/jarust/tests/mocks/mock_session.rs +++ /dev/null @@ -1,44 +0,0 @@ -use super::mock_interface::MockServer; -use jarust::jaconnection::CreateConnectionParams; -use jarust::jaconnection::JaConnection; -use jarust::prelude::*; -use jarust_transport::japrotocol::JaData; -use jarust_transport::japrotocol::JaSuccessProtocol; -use jarust_transport::japrotocol::ResponseType; -use std::time::Duration; - -pub struct MockSessionConfig { - pub session_id: u64, - pub ka_interval: u32, - pub timeout: Duration, -} - -#[allow(dead_code)] -pub async fn mock_session( - mut connection: JaConnection, - server: &MockServer, - config: MockSessionConfig, - expected_transaction: &str, -) -> JaResult { - let msg = serde_json::to_string(&JaResponse { - janus: ResponseType::Success(JaSuccessProtocol::Data { - data: JaData { - id: config.session_id, - }, - }), - transaction: Some(expected_transaction.to_string()), - session_id: None, - sender: None, - establishment_protocol: None, - })?; - - server.mock_send_to_client(&msg).await; - let session = connection - .create(CreateConnectionParams { - ka_interval: config.ka_interval, - timeout: config.timeout, - }) - .await?; - - Ok(session) -} diff --git a/jarust/tests/mocks/mod.rs b/jarust/tests/mocks/mod.rs index 2ea346f..a998035 100644 --- a/jarust/tests/mocks/mod.rs +++ b/jarust/tests/mocks/mod.rs @@ -1,5 +1,2 @@ -pub mod mock_connection; pub mod mock_generate_transaction; -pub mod mock_handle; pub mod mock_interface; -pub mod mock_session; diff --git a/jarust/tests/session.rs b/jarust/tests/session.rs index f6491f6..55a074d 100644 --- a/jarust/tests/session.rs +++ b/jarust/tests/session.rs @@ -3,61 +3,72 @@ mod mocks; #[cfg(test)] mod tests { - use crate::fixtures::FIXTURE_KA_INTERVAL; - use crate::fixtures::FIXTURE_SESSION_ID; - use crate::fixtures::FIXTURE_TIMEOUT; - use crate::mocks::mock_connection::mock_connection; use crate::mocks::mock_generate_transaction::MockGenerateTransaction; use crate::mocks::mock_interface::MockInterface; - use crate::mocks::mock_session::mock_session; - use crate::mocks::mock_session::MockSessionConfig; use jarust::error::JaError; - use jarust::japlugin::Attach; + use jarust::jaconnection::CreateConnectionParams; use jarust::japlugin::AttachHandleParams; + use jarust::prelude::Attach; + use jarust::prelude::JaResponse; use jarust_transport::error::JaTransportError; + use jarust_transport::interface::janus_interface::ConnectionParams; + use jarust_transport::interface::janus_interface::JanusInterface; use jarust_transport::japrotocol::ErrorResponse; use jarust_transport::japrotocol::JaData; - use jarust_transport::japrotocol::JaResponse; use jarust_transport::japrotocol::JaSuccessProtocol; use jarust_transport::japrotocol::ResponseType; + use std::time::Duration; #[tokio::test] async fn it_successfully_attach_to_handle() { - let (interface, server) = MockInterface::interface_server_pair().await.unwrap(); - let mut generator = MockGenerateTransaction::new(); - generator.next_transaction("mock-connection-transaction"); - let connection = mock_connection(interface).await.unwrap(); - let session = mock_session( - connection, - &server, - MockSessionConfig { - session_id: FIXTURE_SESSION_ID, - ka_interval: FIXTURE_KA_INTERVAL, - timeout: FIXTURE_TIMEOUT, - }, - "mock-transaction", - ) - .await - .unwrap(); + let conn_params = ConnectionParams { + url: "mock://some.janus.com".to_string(), + capacity: 10, + apisecret: None, + namespace: "mock".to_string(), + }; + let transaction_generator = MockGenerateTransaction::new(); + let interface = MockInterface::make_interface(conn_params, transaction_generator) + .await + .unwrap(); + let mut connection = jarust::custom_connect(interface.clone()).await.unwrap(); + + let session_id = 73; + + let response = JaResponse { + janus: ResponseType::Success(JaSuccessProtocol::Data { + data: JaData { id: session_id }, + }), + transaction: Some("abc123".to_string()), + session_id: None, + sender: None, + establishment_protocol: None, + }; + interface.mock_create_rsp(response).await; + + let session = connection + .create(CreateConnectionParams { + ka_interval: 10, + timeout: Duration::from_secs(10), + }) + .await + .unwrap(); - let attachment_msg = serde_json::to_string(&JaResponse { + let response = JaResponse { janus: ResponseType::Success(JaSuccessProtocol::Data { data: JaData { id: 3 }, }), transaction: Some("mock-attach-plugin-transaction".to_string()), - session_id: Some(FIXTURE_SESSION_ID), + session_id: Some(session_id), sender: None, establishment_protocol: None, - }) - .unwrap(); - server.mock_send_to_client(&attachment_msg).await; + }; + interface.mock_attach_rsp(response).await; - generator.next_transaction("mock-attach-plugin-transaction"); - // no need for assertion, if unwrap fails the test will fail let _ = session .attach(AttachHandleParams { plugin_id: "mock.plugin.test".to_string(), - timeout: FIXTURE_TIMEOUT, + timeout: Duration::from_secs(5), }) .await .unwrap(); @@ -65,24 +76,40 @@ mod tests { #[tokio::test] async fn it_fails_to_attach_session() { - let (interface, server) = MockInterface::interface_server_pair().await.unwrap(); - let mut generator = MockGenerateTransaction::new(); - generator.next_transaction("mock-connection-transaction"); - let connection = mock_connection(interface).await.unwrap(); - let session = mock_session( - connection, - &server, - MockSessionConfig { - session_id: FIXTURE_SESSION_ID, - ka_interval: FIXTURE_KA_INTERVAL, - timeout: FIXTURE_TIMEOUT, - }, - "mock-transaction", - ) - .await - .unwrap(); + let conn_params = ConnectionParams { + url: "mock://some.janus.com".to_string(), + capacity: 10, + apisecret: None, + namespace: "mock".to_string(), + }; + let transaction_generator = MockGenerateTransaction::new(); + let interface = MockInterface::make_interface(conn_params, transaction_generator) + .await + .unwrap(); + let mut connection = jarust::custom_connect(interface.clone()).await.unwrap(); + + let session_id = 73; + + let response = JaResponse { + janus: ResponseType::Success(JaSuccessProtocol::Data { + data: JaData { id: session_id }, + }), + transaction: Some("abc123".to_string()), + session_id: None, + sender: None, + establishment_protocol: None, + }; + interface.mock_create_rsp(response).await; + + let session = connection + .create(CreateConnectionParams { + ka_interval: 10, + timeout: Duration::from_secs(10), + }) + .await + .unwrap(); - let error = serde_json::to_string(&JaResponse { + let response = JaResponse { janus: ResponseType::Error { error: ErrorResponse { code: 0, @@ -90,18 +117,16 @@ mod tests { }, }, transaction: Some("mock-attach-plugin-transaction".to_string()), - session_id: Some(FIXTURE_SESSION_ID), + session_id: Some(session_id), sender: None, establishment_protocol: None, - }) - .unwrap(); + }; + interface.mock_attach_rsp(response).await; - server.mock_send_to_client(&error).await; - generator.next_transaction("mock-attach-plugin-transaction"); let result = session .attach(AttachHandleParams { plugin_id: "mock.plugin.test".to_string(), - timeout: FIXTURE_TIMEOUT, + timeout: Duration::from_secs(5), }) .await; assert!(matches!(