From 7df3cc59a10287db978b15ae1bb6092d39a13e33 Mon Sep 17 00:00:00 2001 From: Nikolay Kim Date: Sun, 29 Mar 2020 13:59:17 +0600 Subject: [PATCH] merge actix-rt --- Cargo.toml | 12 +- actix-net/actix-macros/LICENSE-APACHE | 1 - actix-net/actix-macros/LICENSE-MIT | 1 - actix-net/actix-rt/LICENSE-APACHE | 1 - actix-net/actix-rt/LICENSE-MIT | 1 - ntex-codec/LICENSE | 1 + ntex-codec/LICENSE-APACHE | 1 - ntex-codec/LICENSE-MIT | 1 - .../actix-macros => ntex-macros}/Cargo.toml | 14 +- ntex-macros/LICENSE | 1 + .../actix-macros => ntex-macros}/src/lib.rs | 10 +- ntex-router/LICENSE | 1 + {actix-net/actix-rt => ntex-rt}/CHANGES.md | 4 + {actix-net/actix-rt => ntex-rt}/Cargo.toml | 15 +- ntex-rt/LICENSE | 1 + .../actix-rt => ntex-rt}/src/arbiter.rs | 79 +++---- .../actix-rt => ntex-rt}/src/builder.rs | 82 +++---- {actix-net/actix-rt => ntex-rt}/src/lib.rs | 12 +- .../actix-rt => ntex-rt}/src/runtime.rs | 6 +- {actix-net/actix-rt => ntex-rt}/src/system.rs | 10 +- ntex-service/Cargo.toml | 2 +- ntex-service/LICENSE | 1 + ntex-service/src/and_then.rs | 6 +- ntex-service/src/and_then_apply_fn.rs | 4 +- ntex-service/src/apply.rs | 4 +- ntex-service/src/fn_service.rs | 14 +- ntex-service/src/map.rs | 6 +- ntex-service/src/map_err.rs | 6 +- ntex-service/src/then.rs | 6 +- ntex-web-macros/LICENSE | 1 + ntex/Cargo.toml | 15 +- ntex/LICENSE | 26 +-- ntex/src/channel/condition.rs | 2 +- ntex/src/channel/mpsc.rs | 2 +- ntex/src/channel/oneshot.rs | 4 +- ntex/src/http/body.rs | 26 +-- ntex/src/http/client/builder.rs | 4 +- ntex/src/http/client/pool.rs | 14 +- ntex/src/http/client/request.rs | 14 +- ntex/src/http/client/response.rs | 4 +- ntex/src/http/client/sender.rs | 2 +- ntex/src/http/client/ws.rs | 10 +- ntex/src/http/config.rs | 4 +- ntex/src/http/h1/dispatcher.rs | 2 +- ntex/src/http/h1/payload.rs | 2 +- ntex/src/http/h2/dispatcher.rs | 2 +- ntex/src/http/test.rs | 15 +- ntex/src/lib.rs | 2 +- ntex/src/rt.rs | 2 +- ntex/src/server/accept.rs | 5 +- ntex/src/server/builder.rs | 11 +- ntex/src/server/config.rs | 2 +- ntex/src/server/service.rs | 2 +- ntex/src/server/signals.rs | 12 +- ntex/src/server/socket.rs | 4 +- ntex/src/server/test.rs | 34 +-- ntex/src/server/worker.rs | 8 +- ntex/src/util/inflight.rs | 4 +- ntex/src/util/keepalive.rs | 5 +- ntex/src/util/order.rs | 10 +- ntex/src/util/stream.rs | 2 +- ntex/src/util/time.rs | 14 +- ntex/src/util/timeout.rs | 10 +- ntex/src/web/app.rs | 18 +- ntex/src/web/app_service.rs | 2 +- ntex/src/web/config.rs | 8 +- ntex/src/web/data.rs | 10 +- ntex/src/web/extract.rs | 4 +- ntex/src/web/middleware/cors.rs | 22 +- ntex/src/web/middleware/defaultheaders.rs | 4 +- ntex/src/web/middleware/logger.rs | 8 +- ntex/src/web/request.rs | 4 +- ntex/src/web/resource.rs | 16 +- ntex/src/web/responder.rs | 10 +- ntex/src/web/route.rs | 4 +- ntex/src/web/scope.rs | 48 ++--- ntex/src/web/server.rs | 4 +- ntex/src/web/service.rs | 2 +- ntex/src/web/test.rs | 202 +++++++++--------- ntex/src/web/types/form.rs | 8 +- ntex/src/web/types/json.rs | 14 +- ntex/src/web/types/path.rs | 8 +- ntex/src/web/types/payload.rs | 8 +- ntex/src/web/types/query.rs | 4 +- ntex/tests/server.rs | 106 ++++----- ntex/tests/web_httpserver.rs | 76 +++---- 86 files changed, 582 insertions(+), 587 deletions(-) delete mode 120000 actix-net/actix-macros/LICENSE-APACHE delete mode 120000 actix-net/actix-macros/LICENSE-MIT delete mode 120000 actix-net/actix-rt/LICENSE-APACHE delete mode 120000 actix-net/actix-rt/LICENSE-MIT create mode 120000 ntex-codec/LICENSE delete mode 120000 ntex-codec/LICENSE-APACHE delete mode 120000 ntex-codec/LICENSE-MIT rename {actix-net/actix-macros => ntex-macros}/Cargo.toml (51%) create mode 120000 ntex-macros/LICENSE rename {actix-net/actix-macros => ntex-macros}/src/lib.rs (91%) create mode 120000 ntex-router/LICENSE rename {actix-net/actix-rt => ntex-rt}/CHANGES.md (96%) rename {actix-net/actix-rt => ntex-rt}/Cargo.toml (66%) create mode 120000 ntex-rt/LICENSE rename {actix-net/actix-rt => ntex-rt}/src/arbiter.rs (83%) rename {actix-net/actix-rt => ntex-rt}/src/builder.rs (74%) rename {actix-net/actix-rt => ntex-rt}/src/lib.rs (91%) rename {actix-net/actix-rt => ntex-rt}/src/runtime.rs (96%) rename {actix-net/actix-rt => ntex-rt}/src/system.rs (94%) create mode 120000 ntex-service/LICENSE create mode 120000 ntex-web-macros/LICENSE mode change 100644 => 120000 ntex/LICENSE diff --git a/Cargo.toml b/Cargo.toml index a64ce395..a5070b4f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -2,9 +2,11 @@ members = [ "ntex", "ntex-codec", + "ntex-macros", "ntex-router", + "ntex-rt", "ntex-service", - "ntex-web-macros", + # "ntex-web-macros", "actix-net/actix-service", "actix-net/router", @@ -13,12 +15,10 @@ members = [ [patch.crates-io] ntex = { path = "ntex" } ntex-codec = { path = "ntex-codec" } +ntex-macros = { path = "ntex-macros" } ntex-router = { path = "ntex-router" } +ntex-rt = { path = "ntex-rt" } ntex-service = { path = "ntex-service" } +ntex-web-macros = { path = "ntex-web-macros" } -actix-service = { path = "actix-net/actix-service" } -actix-router = { path = "actix-net/router" } - -actix-rt = { path = "actix-net/actix-rt" } -actix-macros = { path = "actix-net/actix-macros" } bytestring = { path = "actix-net/string" } diff --git a/actix-net/actix-macros/LICENSE-APACHE b/actix-net/actix-macros/LICENSE-APACHE deleted file mode 120000 index 965b606f..00000000 --- a/actix-net/actix-macros/LICENSE-APACHE +++ /dev/null @@ -1 +0,0 @@ -../LICENSE-APACHE \ No newline at end of file diff --git a/actix-net/actix-macros/LICENSE-MIT b/actix-net/actix-macros/LICENSE-MIT deleted file mode 120000 index 76219eb7..00000000 --- a/actix-net/actix-macros/LICENSE-MIT +++ /dev/null @@ -1 +0,0 @@ -../LICENSE-MIT \ No newline at end of file diff --git a/actix-net/actix-rt/LICENSE-APACHE b/actix-net/actix-rt/LICENSE-APACHE deleted file mode 120000 index 965b606f..00000000 --- a/actix-net/actix-rt/LICENSE-APACHE +++ /dev/null @@ -1 +0,0 @@ -../LICENSE-APACHE \ No newline at end of file diff --git a/actix-net/actix-rt/LICENSE-MIT b/actix-net/actix-rt/LICENSE-MIT deleted file mode 120000 index 76219eb7..00000000 --- a/actix-net/actix-rt/LICENSE-MIT +++ /dev/null @@ -1 +0,0 @@ -../LICENSE-MIT \ No newline at end of file diff --git a/ntex-codec/LICENSE b/ntex-codec/LICENSE new file mode 120000 index 00000000..ea5b6064 --- /dev/null +++ b/ntex-codec/LICENSE @@ -0,0 +1 @@ +../LICENSE \ No newline at end of file diff --git a/ntex-codec/LICENSE-APACHE b/ntex-codec/LICENSE-APACHE deleted file mode 120000 index 965b606f..00000000 --- a/ntex-codec/LICENSE-APACHE +++ /dev/null @@ -1 +0,0 @@ -../LICENSE-APACHE \ No newline at end of file diff --git a/ntex-codec/LICENSE-MIT b/ntex-codec/LICENSE-MIT deleted file mode 120000 index 76219eb7..00000000 --- a/ntex-codec/LICENSE-MIT +++ /dev/null @@ -1 +0,0 @@ -../LICENSE-MIT \ No newline at end of file diff --git a/actix-net/actix-macros/Cargo.toml b/ntex-macros/Cargo.toml similarity index 51% rename from actix-net/actix-macros/Cargo.toml rename to ntex-macros/Cargo.toml index 48915510..0bd0b069 100644 --- a/actix-net/actix-macros/Cargo.toml +++ b/ntex-macros/Cargo.toml @@ -1,12 +1,12 @@ [package] -name = "actix-macros" -version = "0.1.1" +name = "ntex-macros" +version = "0.1.0" authors = ["Nikolay Kim "] -description = "Actix runtime macros" -repository = "https://github.com/actix/actix-net" -documentation = "https://docs.rs/actix-macros/" +description = "Ntex runtime macros" +repository = "https://github.com/ntex-rs/ntex" +documentation = "https://docs.rs/ntex-macros/" categories = ["network-programming", "asynchronous"] -license = "MIT/Apache-2.0" +license = "MIT" edition = "2018" [lib] @@ -17,4 +17,4 @@ quote = "^1" syn = { version = "^1", features = ["full"] } [dev-dependencies] -actix-rt = { version = "1.0.0" } +ntex = { version = "0.1.1" } diff --git a/ntex-macros/LICENSE b/ntex-macros/LICENSE new file mode 120000 index 00000000..ea5b6064 --- /dev/null +++ b/ntex-macros/LICENSE @@ -0,0 +1 @@ +../LICENSE \ No newline at end of file diff --git a/actix-net/actix-macros/src/lib.rs b/ntex-macros/src/lib.rs similarity index 91% rename from actix-net/actix-macros/src/lib.rs rename to ntex-macros/src/lib.rs index ec270f28..45b76045 100644 --- a/actix-net/actix-macros/src/lib.rs +++ b/ntex-macros/src/lib.rs @@ -9,7 +9,7 @@ use quote::quote; /// ## Usage /// /// ```rust -/// #[actix_rt::main] +/// #[ntex::main] /// async fn main() { /// println!("Hello world"); /// } @@ -35,7 +35,7 @@ pub fn main(_: TokenStream, item: TokenStream) -> TokenStream { (quote! { #(#attrs)* #vis #sig { - actix_rt::System::new(stringify!(#name)) + ntex_rt::System::new(stringify!(#name)) .block_on(async move { #body }) } }) @@ -47,7 +47,7 @@ pub fn main(_: TokenStream, item: TokenStream) -> TokenStream { /// ## Usage /// /// ```no_run -/// #[actix_rt::test] +/// #[ntex::test] /// async fn my_test() { /// assert!(true); /// } @@ -81,7 +81,7 @@ pub fn test(_: TokenStream, item: TokenStream) -> TokenStream { quote! { #(#attrs)* fn #name() #ret { - actix_rt::System::new("test") + ntex_rt::System::new("test") .block_on(async { #body }) } } @@ -90,7 +90,7 @@ pub fn test(_: TokenStream, item: TokenStream) -> TokenStream { #[test] #(#attrs)* fn #name() #ret { - actix_rt::System::new("test") + ntex_rt::System::new("test") .block_on(async { #body }) } } diff --git a/ntex-router/LICENSE b/ntex-router/LICENSE new file mode 120000 index 00000000..ea5b6064 --- /dev/null +++ b/ntex-router/LICENSE @@ -0,0 +1 @@ +../LICENSE \ No newline at end of file diff --git a/actix-net/actix-rt/CHANGES.md b/ntex-rt/CHANGES.md similarity index 96% rename from actix-net/actix-rt/CHANGES.md rename to ntex-rt/CHANGES.md index 7c7ad63d..08e60c5f 100644 --- a/actix-net/actix-rt/CHANGES.md +++ b/ntex-rt/CHANGES.md @@ -2,6 +2,10 @@ ## [1.0.0] - 2019-12-11 +* Rename crate + +## [1.0.0] - 2019-12-11 + * Update dependencies ## [1.0.0-alpha.3] - 2019-12-07 diff --git a/actix-net/actix-rt/Cargo.toml b/ntex-rt/Cargo.toml similarity index 66% rename from actix-net/actix-rt/Cargo.toml rename to ntex-rt/Cargo.toml index 3ab88ba0..d04fe7dd 100644 --- a/actix-net/actix-rt/Cargo.toml +++ b/ntex-rt/Cargo.toml @@ -1,23 +1,22 @@ [package] -name = "actix-rt" +name = "ntex-rt" version = "1.0.0" authors = ["Nikolay Kim "] description = "Actix runtime" keywords = ["network", "framework", "async", "futures"] -homepage = "https://actix.rs" -repository = "https://github.com/actix/actix-net.git" -documentation = "https://docs.rs/actix-rt/" +homepage = "https://ntex.rs" +repository = "https://github.com/ntex-rs/ntex.git" +documentation = "https://docs.rs/ntex-rt/" categories = ["network-programming", "asynchronous"] -license = "MIT/Apache-2.0" +license = "MIT" edition = "2018" [lib] -name = "actix_rt" +name = "ntex_rt" path = "src/lib.rs" [dependencies] -actix-macros = "0.1.0" +ntex-macros = "0.1.0" actix-threadpool = "0.3" futures = "0.3.1" -copyless = "0.1.4" tokio = { version = "0.2.6", default-features=false, features = ["rt-core", "rt-util", "io-driver", "tcp", "uds", "udp", "time", "signal", "stream"] } diff --git a/ntex-rt/LICENSE b/ntex-rt/LICENSE new file mode 120000 index 00000000..ea5b6064 --- /dev/null +++ b/ntex-rt/LICENSE @@ -0,0 +1 @@ +../LICENSE \ No newline at end of file diff --git a/actix-net/actix-rt/src/arbiter.rs b/ntex-rt/src/arbiter.rs similarity index 83% rename from actix-net/actix-rt/src/arbiter.rs rename to ntex-rt/src/arbiter.rs index 16534476..c4b403dd 100644 --- a/actix-net/actix-rt/src/arbiter.rs +++ b/ntex-rt/src/arbiter.rs @@ -1,5 +1,5 @@ use std::any::{Any, TypeId}; -use std::cell::{Cell, RefCell}; +use std::cell::RefCell; use std::collections::HashMap; use std::pin::Pin; use std::sync::atomic::{AtomicUsize, Ordering}; @@ -9,22 +9,20 @@ use std::{fmt, thread}; use futures::channel::mpsc::{unbounded, UnboundedReceiver, UnboundedSender}; use futures::channel::oneshot::{channel, Canceled, Sender}; use futures::{future, Future, FutureExt, Stream}; +use tokio::task::LocalSet; -use crate::runtime::Runtime; -use crate::system::System; - -use copyless::BoxHelper; +use super::runtime::Runtime; +use super::system::System; thread_local!( static ADDR: RefCell> = RefCell::new(None); - static RUNNING: Cell = Cell::new(false); - static Q: RefCell>>>> = RefCell::new(Vec::new()); - static STORAGE: RefCell>> = RefCell::new(HashMap::new()); + static STORAGE: RefCell>> = + RefCell::new(HashMap::new()); ); -pub(crate) static COUNT: AtomicUsize = AtomicUsize::new(0); +pub(super) static COUNT: AtomicUsize = AtomicUsize::new(0); -pub(crate) enum ArbiterCommand { +pub(super) enum ArbiterCommand { Stop, Execute(Box + Unpin + Send>), ExecuteFn(Box), @@ -62,14 +60,14 @@ impl Default for Arbiter { } impl Arbiter { - pub(crate) fn new_system() -> Self { + pub(super) fn new_system(local: &LocalSet) -> Self { let (tx, rx) = unbounded(); let arb = Arbiter::with_sender(tx); ADDR.with(|cell| *cell.borrow_mut() = Some(arb.clone())); - RUNNING.with(|cell| cell.set(false)); STORAGE.with(|cell| cell.borrow_mut().clear()); - Arbiter::spawn(ArbiterController { stop: None, rx }); + + local.spawn_local(ArbiterController { stop: None, rx }); arb } @@ -104,7 +102,6 @@ impl Arbiter { let arb = Arbiter::with_sender(arb_tx); let (stop, stop_rx) = channel(); - RUNNING.with(|cell| cell.set(true)); STORAGE.with(|cell| cell.borrow_mut().clear()); System::set_current(sys); @@ -142,44 +139,17 @@ impl Arbiter { } } - pub(crate) fn run_system(rt: Option<&Runtime>) { - RUNNING.with(|cell| cell.set(true)); - Q.with(|cell| { - let mut v = cell.borrow_mut(); - for fut in v.drain(..) { - if let Some(rt) = rt { - rt.spawn(fut); - } else { - tokio::task::spawn_local(fut); - } - } - }); - } - - pub(crate) fn stop_system() { - RUNNING.with(|cell| cell.set(false)); - } - /// Spawn a future on the current thread. This does not create a new Arbiter /// or Arbiter address, it is simply a helper for spawning futures on the current /// thread. + /// + /// Panics if arbiter is not started. + #[inline] pub fn spawn(future: F) where F: Future + 'static, { - RUNNING.with(move |cell| { - if cell.get() { - // Spawn the future on running executor - tokio::task::spawn_local(future); - } else { - // Box the future and push it to the queue, this results in double boxing - // because the executor boxes the future again, but works for now - Q.with(move |cell| { - cell.borrow_mut() - .push(unsafe { Pin::new_unchecked(Box::alloc().init(future)) }) - }); - } - }); + tokio::task::spawn_local(future); } /// Executes a future on the current thread. This does not create a new Arbiter @@ -237,7 +207,9 @@ impl Arbiter { /// Set item to arbiter storage pub fn set_item(item: T) { - STORAGE.with(move |cell| cell.borrow_mut().insert(TypeId::of::(), Box::new(item))); + STORAGE.with(move |cell| { + cell.borrow_mut().insert(TypeId::of::(), Box::new(item)) + }); } /// Check if arbiter storage contains item @@ -273,7 +245,9 @@ impl Arbiter { let mut st = cell.borrow_mut(); let item = st .get_mut(&TypeId::of::()) - .and_then(|boxed| (&mut **boxed as &mut (dyn Any + 'static)).downcast_mut()) + .and_then(|boxed| { + (&mut **boxed as &mut (dyn Any + 'static)).downcast_mut() + }) .unwrap(); f(item) }) @@ -342,21 +316,24 @@ impl Future for ArbiterController { } #[derive(Debug)] -pub(crate) enum SystemCommand { +pub(super) enum SystemCommand { Exit(i32), RegisterArbiter(usize, Arbiter), UnregisterArbiter(usize), } #[derive(Debug)] -pub(crate) struct SystemArbiter { +pub(super) struct SystemArbiter { stop: Option>, commands: UnboundedReceiver, arbiters: HashMap, } impl SystemArbiter { - pub(crate) fn new(stop: Sender, commands: UnboundedReceiver) -> Self { + pub(super) fn new( + stop: Sender, + commands: UnboundedReceiver, + ) -> Self { SystemArbiter { commands, stop: Some(stop), @@ -396,7 +373,7 @@ impl Future for SystemArbiter { } } -pub trait FnExec: Send + 'static { +pub(super) trait FnExec: Send + 'static { fn call_box(self: Box); } diff --git a/actix-net/actix-rt/src/builder.rs b/ntex-rt/src/builder.rs similarity index 74% rename from actix-net/actix-rt/src/builder.rs rename to ntex-rt/src/builder.rs index 2ca77b3c..b1d9ce3f 100644 --- a/actix-net/actix-rt/src/builder.rs +++ b/ntex-rt/src/builder.rs @@ -6,9 +6,9 @@ use futures::channel::oneshot::{channel, Receiver}; use futures::future::{lazy, Future, FutureExt}; use tokio::task::LocalSet; -use crate::arbiter::{Arbiter, SystemArbiter}; -use crate::runtime::Runtime; -use crate::system::System; +use super::arbiter::{Arbiter, SystemArbiter}; +use super::runtime::Runtime; +use super::system::System; /// Builder struct for a actix runtime. /// @@ -24,7 +24,7 @@ pub struct Builder { } impl Builder { - pub(crate) fn new() -> Self { + pub(super) fn new() -> Self { Builder { name: Cow::Borrowed("actix"), stop_on_panic: false, @@ -56,7 +56,7 @@ impl Builder { /// Create new System that can run asynchronously. /// /// This method panics if it cannot start the system arbiter - pub(crate) fn build_async(self, local: &LocalSet) -> AsyncSystemRunner { + pub(super) fn build_async(self, local: &LocalSet) -> AsyncSystemRunner { self.create_async_runtime(local) } @@ -74,7 +74,11 @@ impl Builder { let (stop_tx, stop) = channel(); let (sys_sender, sys_receiver) = unbounded(); - let system = System::construct(sys_sender, Arbiter::new_system(), self.stop_on_panic); + let system = System::construct( + sys_sender, + Arbiter::new_system(local), + self.stop_on_panic, + ); // system arbiter let arb = SystemArbiter::new(stop_tx, sys_receiver); @@ -92,12 +96,15 @@ impl Builder { let (stop_tx, stop) = channel(); let (sys_sender, sys_receiver) = unbounded(); - let system = System::construct(sys_sender, Arbiter::new_system(), self.stop_on_panic); + let mut rt = Runtime::new().unwrap(); // system arbiter + let system = System::construct( + sys_sender, + Arbiter::new_system(rt.local()), + self.stop_on_panic, + ); let arb = SystemArbiter::new(stop_tx, sys_receiver); - - let mut rt = Runtime::new().unwrap(); rt.spawn(arb); // init system arbiter and run configuration method @@ -108,7 +115,7 @@ impl Builder { } #[derive(Debug)] -pub(crate) struct AsyncSystemRunner { +pub(super) struct AsyncSystemRunner { stop: Receiver, system: System, } @@ -116,29 +123,27 @@ pub(crate) struct AsyncSystemRunner { impl AsyncSystemRunner { /// This function will start event loop and returns a future that /// resolves once the `System::stop()` function is called. - pub(crate) fn run_nonblocking(self) -> impl Future> + Send { + pub(super) fn run_nonblocking( + self, + ) -> impl Future> + Send { let AsyncSystemRunner { stop, .. } = self; // run loop - lazy(|_| { - Arbiter::run_system(None); - async { - let res = match stop.await { - Ok(code) => { - if code != 0 { - Err(io::Error::new( - io::ErrorKind::Other, - format!("Non-zero exit code: {}", code), - )) - } else { - Ok(()) - } + lazy(|_| async { + let res = match stop.await { + Ok(code) => { + if code != 0 { + Err(io::Error::new( + io::ErrorKind::Other, + format!("Non-zero exit code: {}", code), + )) + } else { + Ok(()) } - Err(e) => Err(io::Error::new(io::ErrorKind::Other, e)), - }; - Arbiter::stop_system(); - return res; - } + } + Err(e) => Err(io::Error::new(io::ErrorKind::Other, e)), + }; + return res; }) .flatten() } @@ -160,7 +165,6 @@ impl SystemRunner { let SystemRunner { mut rt, stop, .. } = self; // run loop - Arbiter::run_system(Some(&rt)); let result = match rt.block_on(stop) { Ok(code) => { if code != 0 { @@ -174,18 +178,24 @@ impl SystemRunner { } Err(e) => Err(io::Error::new(io::ErrorKind::Other, e)), }; - Arbiter::stop_system(); result } /// Execute a future and wait for result. + #[inline] pub fn block_on(&mut self, fut: F) -> O where - F: Future + 'static, + F: Future, { - Arbiter::run_system(Some(&self.rt)); - let res = self.rt.block_on(fut); - Arbiter::stop_system(); - res + self.rt.block_on(fut) + } + + /// Execute a function with enabled executor. + #[inline] + pub fn exec(&mut self, f: F) -> R + where + F: FnOnce() -> R, + { + self.rt.block_on(lazy(|_| f())) } } diff --git a/actix-net/actix-rt/src/lib.rs b/ntex-rt/src/lib.rs similarity index 91% rename from actix-net/actix-rt/src/lib.rs rename to ntex-rt/src/lib.rs index 3ef7460e..21e0414b 100644 --- a/actix-net/actix-rt/src/lib.rs +++ b/ntex-rt/src/lib.rs @@ -1,10 +1,4 @@ //! A runtime implementation that runs everything on the current thread. -#![deny(rust_2018_idioms, warnings)] -#![allow(clippy::type_complexity)] - -#[cfg(not(test))] // Work around for rust-lang/rust#62127 -pub use actix_macros::{main, test}; - mod arbiter; mod builder; mod runtime; @@ -15,6 +9,9 @@ pub use self::builder::{Builder, SystemRunner}; pub use self::runtime::Runtime; pub use self::system::System; +#[cfg(not(test))] // Work around for rust-lang/rust#62127 +pub use ntex_macros::{main, test}; + #[doc(hidden)] pub use actix_threadpool as blocking; @@ -23,6 +20,7 @@ pub use actix_threadpool as blocking; /// # Panics /// /// This function panics if actix system is not running. +#[inline] pub fn spawn(f: F) where F: futures::Future + 'static, @@ -49,7 +47,7 @@ pub mod net { pub use tokio::net::{TcpListener, TcpStream}; #[cfg(unix)] - mod unix { + pub mod unix { pub use tokio::net::{UnixDatagram, UnixListener, UnixStream}; } diff --git a/actix-net/actix-rt/src/runtime.rs b/ntex-rt/src/runtime.rs similarity index 96% rename from actix-net/actix-rt/src/runtime.rs rename to ntex-rt/src/runtime.rs index a03361d6..f3458866 100644 --- a/actix-net/actix-rt/src/runtime.rs +++ b/ntex-rt/src/runtime.rs @@ -30,6 +30,10 @@ impl Runtime { }) } + pub(super) fn local(&self) -> &LocalSet { + &self.local + } + /// Spawn a future onto the single-threaded runtime. /// /// See [module level][mod] documentation for more details. @@ -84,7 +88,7 @@ impl Runtime { /// complete execution by calling `block_on` or `run`. pub fn block_on(&mut self, f: F) -> F::Output where - F: Future + 'static, + F: Future, { let res = self.local.block_on(&mut self.rt, f); res diff --git a/actix-net/actix-rt/src/system.rs b/ntex-rt/src/system.rs similarity index 94% rename from actix-net/actix-rt/src/system.rs rename to ntex-rt/src/system.rs index 383471cd..f1a9b815 100644 --- a/actix-net/actix-rt/src/system.rs +++ b/ntex-rt/src/system.rs @@ -6,8 +6,8 @@ use std::sync::atomic::{AtomicUsize, Ordering}; use futures::channel::mpsc::UnboundedSender; use tokio::task::LocalSet; -use crate::arbiter::{Arbiter, SystemCommand}; -use crate::builder::{Builder, SystemRunner}; +use super::arbiter::{Arbiter, SystemCommand}; +use super::builder::{Builder, SystemRunner}; static SYSTEM_COUNT: AtomicUsize = AtomicUsize::new(0); @@ -26,7 +26,7 @@ thread_local!( impl System { /// Constructs new system and sets it as current - pub(crate) fn construct( + pub(super) fn construct( sys: UnboundedSender, arbiter: Arbiter, stop_on_panic: bool, @@ -80,7 +80,7 @@ impl System { } /// Set current running system. - pub(crate) fn is_set() -> bool { + pub(super) fn is_set() -> bool { CURRENT.with(|cell| cell.borrow().is_some()) } @@ -118,7 +118,7 @@ impl System { let _ = self.sys.unbounded_send(SystemCommand::Exit(code)); } - pub(crate) fn sys(&self) -> &UnboundedSender { + pub(super) fn sys(&self) -> &UnboundedSender { &self.sys } diff --git a/ntex-service/Cargo.toml b/ntex-service/Cargo.toml index b04b46bb..07f6b728 100644 --- a/ntex-service/Cargo.toml +++ b/ntex-service/Cargo.toml @@ -20,4 +20,4 @@ futures-util = "0.3.1" pin-project = "0.4.6" [dev-dependencies] -actix-rt = "1.0.0" \ No newline at end of file +ntex-rt = "1.0" \ No newline at end of file diff --git a/ntex-service/LICENSE b/ntex-service/LICENSE new file mode 120000 index 00000000..ea5b6064 --- /dev/null +++ b/ntex-service/LICENSE @@ -0,0 +1 @@ +../LICENSE \ No newline at end of file diff --git a/ntex-service/src/and_then.rs b/ntex-service/src/and_then.rs index 05b0f19c..18f3557e 100644 --- a/ntex-service/src/and_then.rs +++ b/ntex-service/src/and_then.rs @@ -313,7 +313,7 @@ mod tests { } } - #[actix_rt::test] + #[ntex_rt::test] async fn test_poll_ready() { let cnt = Rc::new(Cell::new(0)); let mut srv = pipeline(Srv1(cnt.clone())).and_then(Srv2(cnt.clone())); @@ -322,7 +322,7 @@ mod tests { assert_eq!(cnt.get(), 2); } - #[actix_rt::test] + #[ntex_rt::test] async fn test_call() { let cnt = Rc::new(Cell::new(0)); let mut srv = pipeline(Srv1(cnt.clone())).and_then(Srv2(cnt)); @@ -331,7 +331,7 @@ mod tests { assert_eq!(res.unwrap(), (("srv1", "srv2"))); } - #[actix_rt::test] + #[ntex_rt::test] async fn test_new_service() { let cnt = Rc::new(Cell::new(0)); let cnt2 = cnt.clone(); diff --git a/ntex-service/src/and_then_apply_fn.rs b/ntex-service/src/and_then_apply_fn.rs index b1328e8c..2c6e41e5 100644 --- a/ntex-service/src/and_then_apply_fn.rs +++ b/ntex-service/src/and_then_apply_fn.rs @@ -311,7 +311,7 @@ mod tests { } } - #[actix_rt::test] + #[ntex_rt::test] async fn test_service() { let mut srv = pipeline(|r: &'static str| ok(r)) .and_then_apply_fn(Srv, |req: &'static str, s| { @@ -325,7 +325,7 @@ mod tests { assert_eq!(res.unwrap(), ("srv", ())); } - #[actix_rt::test] + #[ntex_rt::test] async fn test_service_factory() { let new_srv = pipeline_factory(|| ok::<_, ()>(fn_service(|r: &'static str| ok(r)))) diff --git a/ntex-service/src/apply.rs b/ntex-service/src/apply.rs index c3c797dc..eab2de2e 100644 --- a/ntex-service/src/apply.rs +++ b/ntex-service/src/apply.rs @@ -238,7 +238,7 @@ mod tests { } } - #[actix_rt::test] + #[ntex_rt::test] async fn test_call() { let mut srv = pipeline(apply_fn(Srv, |req: &'static str, srv| { let fut = srv.call(()); @@ -255,7 +255,7 @@ mod tests { assert_eq!(res.unwrap(), (("srv", ()))); } - #[actix_rt::test] + #[ntex_rt::test] async fn test_new_service() { let new_srv = pipeline_factory(apply_fn_factory( || ok::<_, ()>(Srv), diff --git a/ntex-service/src/fn_service.rs b/ntex-service/src/fn_service.rs index bedc26fd..5619a234 100644 --- a/ntex-service/src/fn_service.rs +++ b/ntex-service/src/fn_service.rs @@ -23,7 +23,7 @@ where /// /// ```rust /// use std::io; -/// use actix_service::{fn_factory, fn_service, Service, ServiceFactory}; +/// use ntex_service::{fn_factory, fn_service, Service, ServiceFactory}; /// use futures_util::future::ok; /// /// /// Service that divides two usize values. @@ -35,7 +35,7 @@ where /// } /// } /// -/// #[actix_rt::main] +/// #[ntex::main] /// async fn main() -> io::Result<()> { /// // Create service factory that produces `div` services /// let factory = fn_factory(|| { @@ -73,10 +73,10 @@ where /// /// ```rust /// use std::io; -/// use actix_service::{fn_factory_with_config, fn_service, Service, ServiceFactory}; +/// use ntex_service::{fn_factory_with_config, fn_service, Service, ServiceFactory}; /// use futures_util::future::ok; /// -/// #[actix_rt::main] +/// #[ntex::main] /// async fn main() -> io::Result<()> { /// // Create service factory. factory uses config argument for /// // services it generates. @@ -370,7 +370,7 @@ mod tests { use super::*; use crate::{Service, ServiceFactory}; - #[actix_rt::test] + #[ntex_rt::test] async fn test_fn_service() { let new_srv = fn_service(|()| ok::<_, ()>("srv")); @@ -381,7 +381,7 @@ mod tests { assert_eq!(res.unwrap(), "srv"); } - #[actix_rt::test] + #[ntex_rt::test] async fn test_fn_service_service() { let mut srv = fn_service(|()| ok::<_, ()>("srv")); @@ -391,7 +391,7 @@ mod tests { assert_eq!(res.unwrap(), "srv"); } - #[actix_rt::test] + #[ntex_rt::test] async fn test_fn_service_with_config() { let new_srv = fn_factory_with_config(|cfg: usize| { ok::<_, ()>(fn_service(move |()| ok::<_, ()>(("srv", cfg)))) diff --git a/ntex-service/src/map.rs b/ntex-service/src/map.rs index 78e90937..610c2219 100644 --- a/ntex-service/src/map.rs +++ b/ntex-service/src/map.rs @@ -226,14 +226,14 @@ mod tests { } } - #[actix_rt::test] + #[ntex_rt::test] async fn test_poll_ready() { let mut srv = Srv.map(|_| "ok"); let res = lazy(|cx| srv.poll_ready(cx)).await; assert_eq!(res, Poll::Ready(Ok(()))); } - #[actix_rt::test] + #[ntex_rt::test] async fn test_call() { let mut srv = Srv.map(|_| "ok"); let res = srv.call(()).await; @@ -241,7 +241,7 @@ mod tests { assert_eq!(res.unwrap(), "ok"); } - #[actix_rt::test] + #[ntex_rt::test] async fn test_new_service() { let new_srv = (|| ok::<_, ()>(Srv)).into_factory().map(|_| "ok"); let mut srv = new_srv.new_service(&()).await.unwrap(); diff --git a/ntex-service/src/map_err.rs b/ntex-service/src/map_err.rs index 5b48b290..e3d79666 100644 --- a/ntex-service/src/map_err.rs +++ b/ntex-service/src/map_err.rs @@ -228,14 +228,14 @@ mod tests { } } - #[actix_rt::test] + #[ntex_rt::test] async fn test_poll_ready() { let mut srv = Srv.map_err(|_| "error"); let res = lazy(|cx| srv.poll_ready(cx)).await; assert_eq!(res, Poll::Ready(Err("error"))); } - #[actix_rt::test] + #[ntex_rt::test] async fn test_call() { let mut srv = Srv.map_err(|_| "error"); let res = srv.call(()).await; @@ -243,7 +243,7 @@ mod tests { assert_eq!(res.err().unwrap(), "error"); } - #[actix_rt::test] + #[ntex_rt::test] async fn test_new_service() { let new_srv = (|| ok::<_, ()>(Srv)).into_factory().map_err(|_| "error"); let mut srv = new_srv.new_service(&()).await.unwrap(); diff --git a/ntex-service/src/then.rs b/ntex-service/src/then.rs index 68612548..83379a63 100644 --- a/ntex-service/src/then.rs +++ b/ntex-service/src/then.rs @@ -306,7 +306,7 @@ mod tests { } } - #[actix_rt::test] + #[ntex_rt::test] async fn test_poll_ready() { let cnt = Rc::new(Cell::new(0)); let mut srv = pipeline(Srv1(cnt.clone())).then(Srv2(cnt.clone())); @@ -315,7 +315,7 @@ mod tests { assert_eq!(cnt.get(), 2); } - #[actix_rt::test] + #[ntex_rt::test] async fn test_call() { let cnt = Rc::new(Cell::new(0)); let mut srv = pipeline(Srv1(cnt.clone())).then(Srv2(cnt)); @@ -329,7 +329,7 @@ mod tests { assert_eq!(res.unwrap(), (("srv2", "err"))); } - #[actix_rt::test] + #[ntex_rt::test] async fn test_factory() { let cnt = Rc::new(Cell::new(0)); let cnt2 = cnt.clone(); diff --git a/ntex-web-macros/LICENSE b/ntex-web-macros/LICENSE new file mode 120000 index 00000000..ea5b6064 --- /dev/null +++ b/ntex-web-macros/LICENSE @@ -0,0 +1 @@ +../LICENSE \ No newline at end of file diff --git a/ntex/Cargo.toml b/ntex/Cargo.toml index b2c0b3cf..ea795feb 100644 --- a/ntex/Cargo.toml +++ b/ntex/Cargo.toml @@ -36,15 +36,14 @@ compress = ["flate2", "brotli2"] cookie = ["coo-kie", "coo-kie/percent-encode"] [dependencies] -ntex-codec = { path = "../ntex-codec" } -ntex-router = { path = "../ntex-router" } -ntex-service = { path = "../ntex-service" } -ntex-web-macros = { path = "../ntex-web-macros" } +ntex-codec = "0.1" +ntex-macros = "0.1" +ntex-rt = "1.0" +ntex-router = "0.3" +ntex-service = "1.0" +ntex-web-macros = "0.1" -actix-macros = "0.1.0" -actix-rt = "1.0.0" actix-threadpool = "0.3.1" - base64 = "0.11" bitflags = "1.2" bytes = "0.5.3" @@ -96,7 +95,7 @@ mio-uds = { version = "0.6.7" } brotli2 = { version="0.3.2", optional = true } flate2 = { version = "1.0.13", optional = true } -tokio = "0.2.4" +tokio = { version = "0.2.6", default-features=false, features = ["rt-core", "rt-util", "io-driver", "tcp", "uds", "udp", "time", "signal", "stream"] } [dev-dependencies] futures = "0.3.1" diff --git a/ntex/LICENSE b/ntex/LICENSE deleted file mode 100644 index 0f80296a..00000000 --- a/ntex/LICENSE +++ /dev/null @@ -1,25 +0,0 @@ -Copyright (c) 2017 Nikolay Kim - -Permission is hereby granted, free of charge, to any -person obtaining a copy of this software and associated -documentation files (the "Software"), to deal in the -Software without restriction, including without -limitation the rights to use, copy, modify, merge, -publish, distribute, sublicense, and/or sell copies of -the Software, and to permit persons to whom the Software -is furnished to do so, subject to the following -conditions: - -The above copyright notice and this permission notice -shall be included in all copies or substantial portions -of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF -ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED -TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A -PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT -SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR -IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -DEALINGS IN THE SOFTWARE. diff --git a/ntex/LICENSE b/ntex/LICENSE new file mode 120000 index 00000000..ea5b6064 --- /dev/null +++ b/ntex/LICENSE @@ -0,0 +1 @@ +../LICENSE \ No newline at end of file diff --git a/ntex/src/channel/condition.rs b/ntex/src/channel/condition.rs index 8ee7d6d5..1c144379 100644 --- a/ntex/src/channel/condition.rs +++ b/ntex/src/channel/condition.rs @@ -98,7 +98,7 @@ mod tests { use super::*; use futures::future::lazy; - #[crate::test] + #[ntex_rt::test] async fn test_condition() { let mut cond = Condition::new(); let mut waiter = cond.wait(); diff --git a/ntex/src/channel/mpsc.rs b/ntex/src/channel/mpsc.rs index e044df1d..3b01d2fe 100644 --- a/ntex/src/channel/mpsc.rs +++ b/ntex/src/channel/mpsc.rs @@ -195,7 +195,7 @@ mod tests { use futures::future::lazy; use futures::{Stream, StreamExt}; - #[crate::test] + #[ntex_rt::test] async fn test_mpsc() { let (tx, mut rx) = channel(); tx.send("test").unwrap(); diff --git a/ntex/src/channel/oneshot.rs b/ntex/src/channel/oneshot.rs index e5612903..ed280b86 100644 --- a/ntex/src/channel/oneshot.rs +++ b/ntex/src/channel/oneshot.rs @@ -255,7 +255,7 @@ mod tests { use super::*; use futures::future::lazy; - #[crate::test] + #[ntex_rt::test] async fn test_oneshot() { let (tx, rx) = channel(); tx.send("test").unwrap(); @@ -282,7 +282,7 @@ mod tests { assert!(rx.await.is_err()); } - #[crate::test] + #[ntex_rt::test] async fn test_pool() { let (tx, rx) = pool().channel(); tx.send("test").unwrap(); diff --git a/ntex/src/http/body.rs b/ntex/src/http/body.rs index d33dc479..1fa61776 100644 --- a/ntex/src/http/body.rs +++ b/ntex/src/http/body.rs @@ -525,7 +525,7 @@ mod tests { } } - #[crate::test] + #[ntex_rt::test] async fn test_static_str() { assert_eq!(Body::from("").size(), BodySize::Sized(0)); assert_eq!(Body::from("test").size(), BodySize::Sized(4)); @@ -538,7 +538,7 @@ mod tests { ); } - #[crate::test] + #[ntex_rt::test] async fn test_static_bytes() { assert_eq!(Body::from(b"test".as_ref()).size(), BodySize::Sized(4)); assert_eq!(Body::from(b"test".as_ref()).get_ref(), b"test"); @@ -558,7 +558,7 @@ mod tests { ); } - #[crate::test] + #[ntex_rt::test] async fn test_vec() { assert_eq!(Body::from(Vec::from("test")).size(), BodySize::Sized(4)); assert_eq!(Body::from(Vec::from("test")).get_ref(), b"test"); @@ -573,7 +573,7 @@ mod tests { ); } - #[crate::test] + #[ntex_rt::test] async fn test_bytes() { let mut b = Bytes::from("test"); assert_eq!(Body::from(b.clone()).size(), BodySize::Sized(4)); @@ -586,7 +586,7 @@ mod tests { ); } - #[crate::test] + #[ntex_rt::test] async fn test_bytes_mut() { let mut b = BytesMut::from("test"); assert_eq!(Body::from(b.clone()).size(), BodySize::Sized(4)); @@ -599,7 +599,7 @@ mod tests { ); } - #[crate::test] + #[ntex_rt::test] async fn test_string() { let mut b = "test".to_owned(); assert_eq!(Body::from(b.clone()).size(), BodySize::Sized(4)); @@ -614,20 +614,20 @@ mod tests { ); } - #[crate::test] + #[ntex_rt::test] async fn test_unit() { assert_eq!(().size(), BodySize::Empty); assert!(poll_fn(|cx| ().poll_next_chunk(cx)).await.is_none()); } - #[crate::test] + #[ntex_rt::test] async fn test_box() { let mut val = Box::new(()); assert_eq!(val.size(), BodySize::Empty); assert!(poll_fn(|cx| val.poll_next_chunk(cx)).await.is_none()); } - #[crate::test] + #[ntex_rt::test] async fn test_body_eq() { assert!(Body::None == Body::None); assert!(Body::None != Body::Empty); @@ -640,14 +640,14 @@ mod tests { assert!(Body::Bytes(Bytes::from_static(b"1")) != Body::None); } - #[crate::test] + #[ntex_rt::test] async fn test_body_debug() { assert!(format!("{:?}", Body::None).contains("Body::None")); assert!(format!("{:?}", Body::Empty).contains("Body::Empty")); assert!(format!("{:?}", Body::Bytes(Bytes::from_static(b"1"))).contains("1")); } - #[crate::test] + #[ntex_rt::test] async fn test_serde_json() { use serde_json::json; assert_eq!( @@ -663,7 +663,7 @@ mod tests { mod body_stream { use super::*; - #[crate::test] + #[ntex_rt::test] async fn skips_empty_chunks() { let mut body = BodyStream::new(stream::iter( ["1", "", "2"] @@ -684,7 +684,7 @@ mod tests { mod sized_stream { use super::*; - #[crate::test] + #[ntex_rt::test] async fn skips_empty_chunks() { let mut body = SizedStream::new( 2, diff --git a/ntex/src/http/client/builder.rs b/ntex/src/http/client/builder.rs index 9479866c..59a999b5 100644 --- a/ntex/src/http/client/builder.rs +++ b/ntex/src/http/client/builder.rs @@ -149,7 +149,7 @@ impl ClientBuilder { mod tests { use super::*; - #[crate::test] + #[ntex_rt::test] async fn client_basic_auth() { let client = ClientBuilder::new().basic_auth("username", Some("password")); assert_eq!( @@ -176,7 +176,7 @@ mod tests { ); } - #[crate::test] + #[ntex_rt::test] async fn client_bearer_auth() { let client = ClientBuilder::new().bearer_auth("someS3cr3tAutht0k3n"); assert_eq!( diff --git a/ntex/src/http/client/pool.rs b/ntex/src/http/client/pool.rs index 434ac55d..4fcaee90 100644 --- a/ntex/src/http/client/pool.rs +++ b/ntex/src/http/client/pool.rs @@ -94,7 +94,7 @@ where fn call(&mut self, req: Connect) -> Self::Future { // start support future - actix_rt::spawn(ConnectorPoolSupport { + crate::rt::spawn(ConnectorPoolSupport { connector: self.0.clone(), inner: self.1.clone(), }); @@ -133,7 +133,7 @@ where )) } else { let (snd, connection) = handshake(io).await?; - actix_rt::spawn(connection.map(|_| ())); + crate::rt::spawn(connection.map(|_| ())); Ok(IoConnection::new( ConnectionType::H2(snd), Instant::now(), @@ -322,7 +322,7 @@ where { if let Some(timeout) = self.disconnect_timeout { if let ConnectionType::H1(io) = conn.io { - actix_rt::spawn(CloseConnection::new(io, timeout)) + crate::rt::spawn(CloseConnection::new(io, timeout)) } } } else { @@ -334,7 +334,7 @@ where Poll::Ready(Ok(n)) if n > 0 => { if let Some(timeout) = self.disconnect_timeout { if let ConnectionType::H1(io) = io { - actix_rt::spawn(CloseConnection::new( + crate::rt::spawn(CloseConnection::new( io, timeout, )) } @@ -368,7 +368,7 @@ where self.acquired -= 1; if let Some(timeout) = self.disconnect_timeout { if let ConnectionType::H1(io) = io { - actix_rt::spawn(CloseConnection::new(io, timeout)) + crate::rt::spawn(CloseConnection::new(io, timeout)) } } self.check_availibility(); @@ -510,7 +510,7 @@ where inner: Rc>>, fut: F, ) { - actix_rt::spawn(OpenWaitingConnection { + crate::rt::spawn(OpenWaitingConnection { key, fut, h2: None, @@ -546,7 +546,7 @@ where if let Some(ref mut h2) = this.h2 { return match Pin::new(h2).poll(cx) { Poll::Ready(Ok((snd, connection))) => { - actix_rt::spawn(connection.map(|_| ())); + crate::rt::spawn(connection.map(|_| ())); let rx = this.rx.take().unwrap(); let _ = rx.send(Ok(IoConnection::new( ConnectionType::H2(snd), diff --git a/ntex/src/http/client/request.rs b/ntex/src/http/client/request.rs index 3826a1c5..68f78041 100644 --- a/ntex/src/http/client/request.rs +++ b/ntex/src/http/client/request.rs @@ -577,7 +577,7 @@ mod tests { use super::*; use crate::http::client::Client; - #[crate::test] + #[ntex_rt::test] async fn test_debug() { let request = Client::new().get("/").header("x-test", "111"); let repr = format!("{:?}", request); @@ -585,7 +585,7 @@ mod tests { assert!(repr.contains("x-test")); } - #[crate::test] + #[ntex_rt::test] async fn test_basics() { let mut req = Client::new() .put("/") @@ -612,7 +612,7 @@ mod tests { let _ = req.send_body(""); } - #[crate::test] + #[ntex_rt::test] async fn test_client_header() { let req = Client::build() .header(header::CONTENT_TYPE, "111") @@ -630,7 +630,7 @@ mod tests { ); } - #[crate::test] + #[ntex_rt::test] async fn test_client_header_override() { let req = Client::build() .header(header::CONTENT_TYPE, "111") @@ -649,7 +649,7 @@ mod tests { ); } - #[crate::test] + #[ntex_rt::test] async fn client_basic_auth() { let req = Client::new() .get("/") @@ -676,7 +676,7 @@ mod tests { ); } - #[crate::test] + #[ntex_rt::test] async fn client_bearer_auth() { let req = Client::new().get("/").bearer_auth("someS3cr3tAutht0k3n"); assert_eq!( @@ -690,7 +690,7 @@ mod tests { ); } - #[crate::test] + #[ntex_rt::test] async fn client_query() { let req = Client::new() .get("/") diff --git a/ntex/src/http/client/response.rs b/ntex/src/http/client/response.rs index 7f1f0638..b5415908 100644 --- a/ntex/src/http/client/response.rs +++ b/ntex/src/http/client/response.rs @@ -381,7 +381,7 @@ mod tests { use crate::http::client::test::TestResponse; use crate::http::header; - #[crate::test] + #[ntex_rt::test] async fn test_body() { let mut req = TestResponse::with_header(header::CONTENT_LENGTH, "xxxx").finish(); match req.body().await.err().unwrap() { @@ -429,7 +429,7 @@ mod tests { } } - #[crate::test] + #[ntex_rt::test] async fn test_json_body() { let mut req = TestResponse::default().finish(); let json = JsonBody::<_, MyObject>::new(&mut req).await; diff --git a/ntex/src/http/client/sender.rs b/ntex/src/http/client/sender.rs index 2ff79429..07f35deb 100644 --- a/ntex/src/http/client/sender.rs +++ b/ntex/src/http/client/sender.rs @@ -5,7 +5,6 @@ use std::rc::Rc; use std::task::{Context, Poll}; use std::time::Duration; -use actix_rt::time::{delay_for, Delay}; use bytes::Bytes; use derive_more::From; use futures::{Future, Stream}; @@ -16,6 +15,7 @@ use crate::http::body::{Body, BodyStream}; use crate::http::error::HttpError; use crate::http::header::{self, HeaderMap, HeaderName, IntoHeaderValue}; use crate::http::RequestHead; +use crate::rt::time::{delay_for, Delay}; #[cfg(feature = "compress")] use crate::http::encoding::Decoder; diff --git a/ntex/src/http/client/ws.rs b/ntex/src/http/client/ws.rs index a16d1801..3c4b546b 100644 --- a/ntex/src/http/client/ws.rs +++ b/ntex/src/http/client/ws.rs @@ -410,7 +410,7 @@ mod tests { use super::*; use crate::http::client::Client; - #[crate::test] + #[ntex_rt::test] async fn test_debug() { let request = Client::new().ws("/").header("x-test", "111"); let repr = format!("{:?}", request); @@ -418,7 +418,7 @@ mod tests { assert!(repr.contains("x-test")); } - #[crate::test] + #[ntex_rt::test] async fn test_header_override() { let req = Client::build() .header(header::CONTENT_TYPE, "111") @@ -437,7 +437,7 @@ mod tests { ); } - #[crate::test] + #[ntex_rt::test] async fn basic_auth() { let req = Client::new() .ws("/") @@ -464,7 +464,7 @@ mod tests { ); } - #[crate::test] + #[ntex_rt::test] async fn bearer_auth() { let req = Client::new().ws("/").bearer_auth("someS3cr3tAutht0k3n"); assert_eq!( @@ -480,7 +480,7 @@ mod tests { } #[cfg(feature = "cookie")] - #[crate::test] + #[ntex_rt::test] async fn basics() { let req = Client::new() .ws("http://localhost/") diff --git a/ntex/src/http/config.rs b/ntex/src/http/config.rs index 94721739..59f91dd3 100644 --- a/ntex/src/http/config.rs +++ b/ntex/src/http/config.rs @@ -266,7 +266,7 @@ impl DateService { // periodic date update let s = self.clone(); - actix_rt::spawn(delay_for(Duration::from_millis(500)).then(move |_| { + crate::rt::spawn(delay_for(Duration::from_millis(500)).then(move |_| { s.0.reset(); future::ready(()) })); @@ -293,7 +293,7 @@ mod tests { assert_eq!(DATE_VALUE_LENGTH, "Sun, 06 Nov 1994 08:49:37 GMT".len()); } - #[crate::test] + #[ntex_rt::test] async fn test_date() { let settings = ServiceConfig::new(KeepAlive::Os, 0, 0, false, None); let mut buf1 = BytesMut::with_capacity(DATE_VALUE_LENGTH + 10); diff --git a/ntex/src/http/h1/dispatcher.rs b/ntex/src/http/h1/dispatcher.rs index ed583b00..ccf0e4e6 100644 --- a/ntex/src/http/h1/dispatcher.rs +++ b/ntex/src/http/h1/dispatcher.rs @@ -913,7 +913,7 @@ mod tests { use crate::http::test::TestBuffer; use crate::IntoService; - #[crate::test] + #[ntex_rt::test] async fn test_req_parse_err() { lazy(|cx| { let buf = TestBuffer::new("GET /test HTTP/1\r\n\r\n"); diff --git a/ntex/src/http/h1/payload.rs b/ntex/src/http/h1/payload.rs index 2b31a2d0..2cf13054 100644 --- a/ntex/src/http/h1/payload.rs +++ b/ntex/src/http/h1/payload.rs @@ -228,7 +228,7 @@ mod tests { use super::*; use futures::future::poll_fn; - #[crate::test] + #[ntex_rt::test] async fn test_unread_data() { let (_, mut payload) = Payload::create(false); diff --git a/ntex/src/http/h2/dispatcher.rs b/ntex/src/http/h2/dispatcher.rs index 1ca30668..a9993682 100644 --- a/ntex/src/http/h2/dispatcher.rs +++ b/ntex/src/http/h2/dispatcher.rs @@ -134,7 +134,7 @@ where on_connect.set(&mut req.extensions_mut()); } - actix_rt::spawn(ServiceResponse::< + crate::rt::spawn(ServiceResponse::< S::Future, S::Response, S::Error, diff --git a/ntex/src/http/test.rs b/ntex/src/http/test.rs index 53ddcc09..76612f32 100644 --- a/ntex/src/http/test.rs +++ b/ntex/src/http/test.rs @@ -307,15 +307,18 @@ pub fn server>(factory: F) -> TestServer { // run server in separate thread thread::spawn(move || { - let sys = System::new("actix-test-server"); + let mut sys = System::new("actix-test-server"); let tcp = net::TcpListener::bind("127.0.0.1:0").unwrap(); let local_addr = tcp.local_addr().unwrap(); - Server::build() - .listen("test", tcp, factory)? - .workers(1) - .disable_signals() - .start(); + sys.exec(|| { + Server::build() + .listen("test", tcp, factory)? + .workers(1) + .disable_signals() + .start(); + Ok::<_, io::Error>(()) + })?; tx.send((System::current(), local_addr)).unwrap(); sys.run() diff --git a/ntex/src/lib.rs b/ntex/src/lib.rs index cf2c0b88..efe96077 100644 --- a/ntex/src/lib.rs +++ b/ntex/src/lib.rs @@ -15,7 +15,7 @@ #[macro_use] extern crate log; -pub use actix_macros::{main, test}; +pub use ntex_macros::{main, test}; pub mod channel; pub mod codec; diff --git a/ntex/src/rt.rs b/ntex/src/rt.rs index d7e79052..0dc66e00 100644 --- a/ntex/src/rt.rs +++ b/ntex/src/rt.rs @@ -1,2 +1,2 @@ //! A runtime implementation that runs everything on the current thread. -pub use actix_rt::*; +pub use ntex_rt::*; diff --git a/ntex/src/server/accept.rs b/ntex/src/server/accept.rs index 4b5e5beb..2ba398f1 100644 --- a/ntex/src/server/accept.rs +++ b/ntex/src/server/accept.rs @@ -2,11 +2,12 @@ use std::sync::mpsc as sync_mpsc; use std::time::Duration; use std::{io, thread}; -use actix_rt::time::{delay_until, Instant}; -use actix_rt::System; use log::{error, info}; use slab::Slab; +use crate::rt::time::{delay_until, Instant}; +use crate::rt::System; + use super::server::Server; use super::socket::{SocketAddr, SocketListener, StdListener}; use super::worker::{Conn, WorkerClient}; diff --git a/ntex/src/server/builder.rs b/ntex/src/server/builder.rs index b6e2021c..67a3b14d 100644 --- a/ntex/src/server/builder.rs +++ b/ntex/src/server/builder.rs @@ -3,9 +3,6 @@ use std::task::{Context, Poll}; use std::time::Duration; use std::{io, mem, net}; -use actix_rt::net::TcpStream; -use actix_rt::time::{delay_until, Instant}; -use actix_rt::{spawn, System}; use futures::channel::mpsc::{unbounded, UnboundedReceiver}; use futures::channel::oneshot; use futures::future::ready; @@ -15,6 +12,10 @@ use log::{error, info}; use net2::TcpBuilder; use num_cpus; +use crate::rt::net::TcpStream; +use crate::rt::time::{delay_until, Instant}; +use crate::rt::{spawn, System}; + use super::accept::{AcceptLoop, AcceptNotify, Command}; use super::config::{ConfiguredService, ServiceConfig}; use super::server::{Server, ServerCommand}; @@ -187,7 +188,7 @@ impl ServerBuilder { /// Add new unix domain service to the server. pub fn bind_uds(self, name: N, addr: U, factory: F) -> io::Result where - F: ServiceFactory, + F: ServiceFactory, N: AsRef, U: AsRef, { @@ -217,7 +218,7 @@ impl ServerBuilder { factory: F, ) -> io::Result where - F: ServiceFactory, + F: ServiceFactory, { use std::net::{IpAddr, Ipv4Addr, SocketAddr}; let token = self.token.next(); diff --git a/ntex/src/server/config.rs b/ntex/src/server/config.rs index f3975427..ebd29ec5 100644 --- a/ntex/src/server/config.rs +++ b/ntex/src/server/config.rs @@ -1,10 +1,10 @@ use std::collections::HashMap; use std::{fmt, io, net}; -use actix_rt::net::TcpStream; use futures::future::{ok, Future, FutureExt, LocalBoxFuture}; use log::error; +use crate::rt::net::TcpStream; use crate::service; use crate::util::counter::CounterGuard; diff --git a/ntex/src/server/service.rs b/ntex/src/server/service.rs index 00fb64c2..ff562f19 100644 --- a/ntex/src/server/service.rs +++ b/ntex/src/server/service.rs @@ -3,11 +3,11 @@ use std::net::SocketAddr; use std::task::{Context, Poll}; use std::time::Duration; -use actix_rt::spawn; use futures::future::{err, ok, LocalBoxFuture, Ready}; use futures::{FutureExt, TryFutureExt}; use log::error; +use crate::rt::spawn; use crate::service::{Service, ServiceFactory as ActixServiceFactory}; use crate::util::counter::CounterGuard; diff --git a/ntex/src/server/signals.rs b/ntex/src/server/signals.rs index db226585..4399602e 100644 --- a/ntex/src/server/signals.rs +++ b/ntex/src/server/signals.rs @@ -26,22 +26,22 @@ pub(crate) struct Signals { #[cfg(not(unix))] stream: Pin>>>, #[cfg(unix)] - streams: Vec<(Signal, actix_rt::signal::unix::Signal)>, + streams: Vec<(Signal, crate::rt::signal::unix::Signal)>, } impl Signals { pub(crate) fn start(srv: Server) -> io::Result<()> { - actix_rt::spawn(lazy(|_| { + crate::rt::spawn(lazy(|_| { #[cfg(not(unix))] { - actix_rt::spawn(Signals { + crate::rt::spawn(Signals { srv, - stream: Box::pin(actix_rt::signal::ctrl_c()), + stream: Box::pin(crate::rt::signal::ctrl_c()), }); } #[cfg(unix)] { - use actix_rt::signal::unix; + use crate::rt::signal::unix; let mut streams = Vec::new(); @@ -63,7 +63,7 @@ impl Signals { } } - actix_rt::spawn(Signals { srv, streams }) + crate::rt::spawn(Signals { srv, streams }) } })); diff --git a/ntex/src/server/socket.rs b/ntex/src/server/socket.rs index 667d1187..033c5abc 100644 --- a/ntex/src/server/socket.rs +++ b/ntex/src/server/socket.rs @@ -162,11 +162,11 @@ impl FromStream for TcpStream { } #[cfg(all(unix))] -impl FromStream for actix_rt::net::UnixStream { +impl FromStream for crate::rt::net::UnixStream { fn from_stdstream(sock: StdStream) -> io::Result { match sock { StdStream::Tcp(_) => panic!("Should not happen, bug in server impl"), - StdStream::Uds(stream) => actix_rt::net::UnixStream::from_std(stream), + StdStream::Uds(stream) => crate::rt::net::UnixStream::from_std(stream), } } } diff --git a/ntex/src/server/test.rs b/ntex/src/server/test.rs index b5291d61..2fe87c50 100644 --- a/ntex/src/server/test.rs +++ b/ntex/src/server/test.rs @@ -1,11 +1,11 @@ //! Test server use std::sync::mpsc; -use std::{net, thread}; +use std::{io, net, thread}; -use actix_rt::{net::TcpStream, System}; use net2::TcpBuilder; -use super::{Server, ServerBuilder, ServiceFactory}; +use crate::rt::{net::TcpStream, System}; +use crate::server::{Server, ServerBuilder, ServiceFactory}; /// Start test server /// @@ -43,15 +43,18 @@ pub fn test_server>(factory: F) -> TestServer { // run server in separate thread thread::spawn(move || { - let sys = System::new("ntex-test-server"); + let mut sys = System::new("ntex-test-server"); let tcp = net::TcpListener::bind("127.0.0.1:0").unwrap(); let local_addr = tcp.local_addr().unwrap(); - Server::build() - .listen("test", tcp, factory)? - .workers(1) - .disable_signals() - .start(); + sys.exec(|| { + Server::build() + .listen("test", tcp, factory)? + .workers(1) + .disable_signals() + .start(); + Ok::<_, io::Error>(()) + })?; tx.send((System::current(), local_addr)).unwrap(); sys.run() @@ -71,11 +74,14 @@ where // run server in separate thread thread::spawn(move || { - let sys = System::new("actix-test-server"); - factory(Server::build()) - .workers(1) - .disable_signals() - .start(); + let mut sys = System::new("actix-test-server"); + + sys.exec(|| { + factory(Server::build()) + .workers(1) + .disable_signals() + .start(); + }); tx.send(System::current()).unwrap(); sys.run() diff --git a/ntex/src/server/worker.rs b/ntex/src/server/worker.rs index 9abe235b..0c98ea8a 100644 --- a/ntex/src/server/worker.rs +++ b/ntex/src/server/worker.rs @@ -4,14 +4,14 @@ use std::sync::Arc; use std::task::{Context, Poll}; use std::time; -use actix_rt::time::{delay_until, Delay, Instant}; -use actix_rt::{spawn, Arbiter}; use futures::channel::mpsc::{unbounded, UnboundedReceiver, UnboundedSender}; use futures::channel::oneshot; use futures::future::{join_all, LocalBoxFuture, MapOk}; use futures::{Future, FutureExt, Stream, TryFutureExt}; use log::{error, info, trace}; +use crate::rt::time::{delay_until, Delay, Instant}; +use crate::rt::{spawn, Arbiter}; use crate::util::counter::Counter; use super::accept::AcceptNotify; @@ -229,7 +229,7 @@ impl Worker { self.services.iter_mut().for_each(|srv| { if srv.status == WorkerServiceStatus::Available { srv.status = WorkerServiceStatus::Stopped; - actix_rt::spawn( + crate::rt::spawn( srv.service .call((None, ServerMessage::ForceShutdown)) .map(|_| ()), @@ -241,7 +241,7 @@ impl Worker { self.services.iter_mut().for_each(move |srv| { if srv.status == WorkerServiceStatus::Available { srv.status = WorkerServiceStatus::Stopping; - actix_rt::spawn( + crate::rt::spawn( srv.service .call((None, ServerMessage::Shutdown(timeout))) .map(|_| ()), diff --git a/ntex/src/util/inflight.rs b/ntex/src/util/inflight.rs index d595e93e..0701c96b 100644 --- a/ntex/src/util/inflight.rs +++ b/ntex/src/util/inflight.rs @@ -140,7 +140,7 @@ mod tests { } } - #[crate::test] + #[ntex_rt::test] async fn test_transform() { let wait_time = Duration::from_millis(50); @@ -154,7 +154,7 @@ mod tests { assert_eq!(lazy(|cx| srv.poll_ready(cx)).await, Poll::Ready(Ok(()))); } - #[crate::test] + #[ntex_rt::test] async fn test_newtransform() { let wait_time = Duration::from_millis(50); diff --git a/ntex/src/util/keepalive.rs b/ntex/src/util/keepalive.rs index 2f5fe06e..926a1186 100644 --- a/ntex/src/util/keepalive.rs +++ b/ntex/src/util/keepalive.rs @@ -5,12 +5,13 @@ use std::pin::Pin; use std::task::{Context, Poll}; use std::time::Duration; -use actix_rt::time::{delay_until, Delay, Instant}; use futures::future::{ok, Ready}; -use super::time::{LowResTime, LowResTimeService}; +use crate::rt::time::{delay_until, Delay, Instant}; use crate::{Service, ServiceFactory}; +use super::time::{LowResTime, LowResTimeService}; + pub struct KeepAlive { f: F, ka: Duration, diff --git a/ntex/src/util/order.rs b/ntex/src/util/order.rs index 0b173d3a..a5d2c788 100644 --- a/ntex/src/util/order.rs +++ b/ntex/src/util/order.rs @@ -180,7 +180,7 @@ where let waker = self.waker.clone(); let fut = self.service.call(request); - actix_rt::spawn(async move { + crate::rt::spawn(async move { let res = fut.await; waker.wake(); let _ = tx1.send(res); @@ -236,7 +236,7 @@ mod tests { } } - #[crate::test] + #[ntex_rt::test] async fn test_inorder() { let (tx1, rx1) = oneshot::channel(); let (tx2, rx2) = oneshot::channel(); @@ -248,7 +248,7 @@ mod tests { let rx2 = rx2; let rx3 = rx3; let tx_stop = tx_stop; - let _ = actix_rt::System::new("test").block_on(async { + let _ = crate::rt::System::new("test").block_on(async { let mut srv = InOrderService::new(Srv); let _ = lazy(|cx| srv.poll_ready(cx)).await; @@ -256,7 +256,7 @@ mod tests { let res2 = srv.call(rx2); let res3 = srv.call(rx3); - actix_rt::spawn(async move { + crate::rt::spawn(async move { let _ = poll_fn(|cx| { let _ = srv.poll_ready(cx); Poll::<()>::Pending @@ -269,7 +269,7 @@ mod tests { assert_eq!(res3.await.unwrap(), 3); let _ = tx_stop.send(()); - actix_rt::System::current().stop(); + crate::rt::System::current().stop(); }); }); diff --git a/ntex/src/util/stream.rs b/ntex/src/util/stream.rs index 3c02b98a..8be5e8ca 100644 --- a/ntex/src/util/stream.rs +++ b/ntex/src/util/stream.rs @@ -58,7 +58,7 @@ where Poll::Ready(_) => match this.stream.poll_next(cx) { Poll::Ready(Some(item)) => { let stop = this.err_tx.clone(); - actix_rt::spawn(this.service.call(item).map(move |res| { + crate::rt::spawn(this.service.call(item).map(move |res| { if let Err(e) = res { let _ = stop.send(e); } diff --git a/ntex/src/util/time.rs b/ntex/src/util/time.rs index 9ccf4f9e..1d91fd61 100644 --- a/ntex/src/util/time.rs +++ b/ntex/src/util/time.rs @@ -2,10 +2,10 @@ use std::convert::Infallible; use std::task::{Context, Poll}; use std::time::{self, Duration, Instant}; -use actix_rt::time::delay_for; use futures::future::{ok, ready, FutureExt, Ready}; use super::cell::Cell; +use crate::rt::time::delay_for; use crate::service::{Service, ServiceFactory}; #[derive(Clone, Debug)] @@ -79,7 +79,7 @@ impl LowResTimeService { b.resolution }; - actix_rt::spawn(delay_for(interval).then(move |_| { + crate::rt::spawn(delay_for(interval).then(move |_| { inner.get_mut().current.take(); ready(()) })); @@ -144,7 +144,7 @@ impl SystemTimeService { b.resolution }; - actix_rt::spawn(delay_for(interval).then(move |_| { + crate::rt::spawn(delay_for(interval).then(move |_| { inner.get_mut().current.take(); ready(()) })); @@ -161,7 +161,7 @@ mod tests { /// State Under Test: Two calls of `SystemTimeService::now()` return the same value if they are done within resolution interval of `SystemTimeService`. /// /// Expected Behavior: Two back-to-back calls of `SystemTimeService::now()` return the same value. - #[crate::test] + #[ntex_rt::test] async fn system_time_service_time_does_not_immediately_change() { let resolution = Duration::from_millis(50); @@ -172,7 +172,7 @@ mod tests { /// State Under Test: Two calls of `LowResTimeService::now()` return the same value if they are done within resolution interval of `SystemTimeService`. /// /// Expected Behavior: Two back-to-back calls of `LowResTimeService::now()` return the same value. - #[crate::test] + #[ntex_rt::test] async fn lowres_time_service_time_does_not_immediately_change() { let resolution = Duration::from_millis(50); let time_service = LowResTimeService::with(resolution); @@ -183,7 +183,7 @@ mod tests { /// /// Expected Behavior: Two calls of `LowResTimeService::now()` made in subsequent resolution interval return different values /// and second value is greater than the first one at least by a resolution interval. - #[crate::test] + #[ntex_rt::test] async fn system_time_service_time_updates_after_resolution_interval() { let resolution = Duration::from_millis(100); let wait_time = Duration::from_millis(300); @@ -209,7 +209,7 @@ mod tests { /// /// Expected Behavior: Two calls of `LowResTimeService::now()` made in subsequent resolution interval return different values /// and second value is greater than the first one at least by a resolution interval. - #[crate::test] + #[ntex_rt::test] async fn lowres_time_service_time_updates_after_resolution_interval() { let resolution = Duration::from_millis(100); let wait_time = Duration::from_millis(300); diff --git a/ntex/src/util/timeout.rs b/ntex/src/util/timeout.rs index 07b86d5a..fc4deea7 100644 --- a/ntex/src/util/timeout.rs +++ b/ntex/src/util/timeout.rs @@ -8,9 +8,9 @@ use std::pin::Pin; use std::task::{Context, Poll}; use std::{fmt, time}; -use actix_rt::time::{delay_for, Delay}; use futures::future::{ok, Ready}; +use crate::rt::time::{delay_for, Delay}; use crate::service::{IntoService, Service, Transform}; /// Applies a timeout to requests. @@ -203,13 +203,13 @@ mod tests { } fn call(&mut self, _: ()) -> Self::Future { - actix_rt::time::delay_for(self.0) + crate::rt::time::delay_for(self.0) .then(|_| ok::<_, ()>(())) .boxed_local() } } - #[crate::test] + #[ntex_rt::test] async fn test_success() { let resolution = Duration::from_millis(100); let wait_time = Duration::from_millis(50); @@ -218,7 +218,7 @@ mod tests { assert_eq!(timeout.call(()).await, Ok(())); } - #[crate::test] + #[ntex_rt::test] async fn test_timeout() { let resolution = Duration::from_millis(100); let wait_time = Duration::from_millis(500); @@ -227,7 +227,7 @@ mod tests { assert_eq!(timeout.call(()).await, Err(TimeoutError::Timeout)); } - #[crate::test] + #[ntex_rt::test] async fn test_timeout_newservice() { let resolution = Duration::from_millis(100); let wait_time = Duration::from_millis(500); diff --git a/ntex/src/web/app.rs b/ntex/src/web/app.rs index a62b4b74..d57e7e0e 100644 --- a/ntex/src/web/app.rs +++ b/ntex/src/web/app.rs @@ -527,7 +527,7 @@ mod tests { use crate::web::{self, DefaultError, HttpRequest, HttpResponse}; use crate::Service; - #[crate::test] + #[ntex_rt::test] async fn test_default_resource() { let mut srv = init_service( App::new() @@ -573,7 +573,7 @@ mod tests { assert_eq!(resp.status(), StatusCode::CREATED); } - #[crate::test] + #[ntex_rt::test] async fn test_data_factory() { let mut srv = init_service( App::new().data_factory(|| ok::<_, ()>(10usize)).service( @@ -598,7 +598,7 @@ mod tests { assert_eq!(res.status(), StatusCode::INTERNAL_SERVER_ERROR); } - #[crate::test] + #[ntex_rt::test] async fn test_extension() { let mut srv = init_service(App::new().app_data(10usize).service( web::resource("/").to(|req: HttpRequest| async move { @@ -612,7 +612,7 @@ mod tests { assert_eq!(resp.status(), StatusCode::OK); } - #[crate::test] + #[ntex_rt::test] async fn test_wrap() { let mut srv = init_service( App::new() @@ -632,7 +632,7 @@ mod tests { ); } - #[crate::test] + #[ntex_rt::test] async fn test_router_wrap() { let mut srv = init_service( App::new() @@ -652,7 +652,7 @@ mod tests { ); } - #[crate::test] + #[ntex_rt::test] async fn test_wrap_fn() { let mut srv = init_service( App::new() @@ -679,7 +679,7 @@ mod tests { ); } - #[crate::test] + #[ntex_rt::test] async fn test_router_wrap_fn() { let mut srv = init_service( App::new() @@ -706,7 +706,7 @@ mod tests { ); } - #[crate::test] + #[ntex_rt::test] async fn test_case_insensitive_router() { let mut srv = init_service( App::new() @@ -723,7 +723,7 @@ mod tests { assert_eq!(resp.status(), StatusCode::OK); } - #[crate::test] + #[ntex_rt::test] async fn test_external_resource() { let mut srv = init_service( App::new() diff --git a/ntex/src/web/app_service.rs b/ntex/src/web/app_service.rs index 61e30614..1139efa0 100644 --- a/ntex/src/web/app_service.rs +++ b/ntex/src/web/app_service.rs @@ -492,7 +492,7 @@ mod tests { } } - #[crate::test] + #[ntex_rt::test] async fn test_drop_data() { let data = Arc::new(AtomicBool::new(false)); diff --git a/ntex/src/web/config.rs b/ntex/src/web/config.rs index 48dd78b0..ff40aff0 100644 --- a/ntex/src/web/config.rs +++ b/ntex/src/web/config.rs @@ -249,7 +249,7 @@ mod tests { use crate::web::{self, App, HttpRequest, HttpResponse}; use crate::Service; - #[crate::test] + #[ntex_rt::test] async fn test_data() { let cfg = |cfg: &mut ServiceConfig<_>| { cfg.data(10usize); @@ -264,7 +264,7 @@ mod tests { assert_eq!(resp.status(), StatusCode::OK); } - // #[crate::test] + // #[ntex_rt::test] // async fn test_data_factory() { // let cfg = |cfg: &mut ServiceConfig| { // cfg.data_factory(|| { @@ -296,7 +296,7 @@ mod tests { // assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR); // } - #[crate::test] + #[ntex_rt::test] async fn test_external_resource() { let mut srv = init_service( App::new() @@ -324,7 +324,7 @@ mod tests { assert_eq!(body, Bytes::from_static(b"https://youtube.com/watch/12345")); } - #[crate::test] + #[ntex_rt::test] async fn test_service() { let mut srv = init_service(App::new().configure(|cfg| { cfg.service( diff --git a/ntex/src/web/data.rs b/ntex/src/web/data.rs index 82ce770b..a3b310cf 100644 --- a/ntex/src/web/data.rs +++ b/ntex/src/web/data.rs @@ -140,7 +140,7 @@ mod tests { use crate::web::{self, App, HttpResponse}; use crate::Service; - #[crate::test] + #[ntex_rt::test] async fn test_data_extractor() { let mut srv = init_service(App::new().data("TEST".to_string()).service( web::resource("/").to(|data: web::Data| async move { @@ -163,7 +163,7 @@ mod tests { assert_eq!(res.status(), StatusCode::INTERNAL_SERVER_ERROR); } - #[crate::test] + #[ntex_rt::test] async fn test_app_data_extractor() { let mut srv = init_service(App::new().app_data(Data::new(10usize)).service( web::resource("/").to(|_: web::Data| async { HttpResponse::Ok() }), @@ -183,7 +183,7 @@ mod tests { assert_eq!(res.status(), StatusCode::INTERNAL_SERVER_ERROR); } - #[crate::test] + #[ntex_rt::test] async fn test_route_data_extractor() { let mut srv = init_service(App::new().service(web::resource("/").data(10usize).route( @@ -209,7 +209,7 @@ mod tests { assert_eq!(res.status(), StatusCode::INTERNAL_SERVER_ERROR); } - #[crate::test] + #[ntex_rt::test] async fn test_override_data() { let mut srv = init_service(App::new().data(1usize).service( web::resource("/").data(10usize).route(web::get().to( @@ -227,7 +227,7 @@ mod tests { assert_eq!(resp.status(), StatusCode::OK); } - #[crate::test] + #[ntex_rt::test] async fn test_data_drop() { struct TestData(Arc); diff --git a/ntex/src/web/extract.rs b/ntex/src/web/extract.rs index 028802b7..b60ecb1c 100644 --- a/ntex/src/web/extract.rs +++ b/ntex/src/web/extract.rs @@ -280,7 +280,7 @@ tuple_from_req!(TupleFromRequest10, (0, A), (1, B), (2, C), (3, D), (4, E), (5, // extract // } -// #[crate::test] +// #[ntex_rt::test] // async fn test_option() { // let (req, mut pl) = TestRequest::with_header( // header::CONTENT_TYPE, @@ -326,7 +326,7 @@ tuple_from_req!(TupleFromRequest10, (0, A), (1, B), (2, C), (3, D), (4, E), (5, // assert_eq!(r, None); // } -// #[crate::test] +// #[ntex_rt::test] // async fn test_result() { // let (req, mut pl) = TestRequest::with_header( // header::CONTENT_TYPE, diff --git a/ntex/src/web/middleware/cors.rs b/ntex/src/web/middleware/cors.rs index e05f2923..1db20c7f 100644 --- a/ntex/src/web/middleware/cors.rs +++ b/ntex/src/web/middleware/cors.rs @@ -827,13 +827,13 @@ mod tests { use super::*; - #[crate::test] + #[ntex_rt::test] #[should_panic(expected = "Credentials are allowed, but the Origin is set to")] async fn cors_validates_illegal_allow_credentials() { let _cors = Cors::new().supports_credentials().send_wildcard().finish(); } - #[crate::test] + #[ntex_rt::test] async fn validate_origin_allows_all_origins() { let mut cors = Cors::new() .finish() @@ -847,7 +847,7 @@ mod tests { assert_eq!(resp.status(), StatusCode::OK); } - #[crate::test] + #[ntex_rt::test] async fn default() { let mut cors = Cors::default() .new_transform(test::ok_service()) @@ -860,7 +860,7 @@ mod tests { assert_eq!(resp.status(), StatusCode::OK); } - #[crate::test] + #[ntex_rt::test] async fn test_preflight() { let mut cors = Cors::new() .send_wildcard() @@ -950,7 +950,7 @@ mod tests { assert_eq!(resp.status(), StatusCode::OK); } - // #[crate::test] + // #[ntex_rt::test] // #[should_panic(expected = "MissingOrigin")] // async fn test_validate_missing_origin() { // let cors = Cors::build() @@ -960,7 +960,7 @@ mod tests { // cors.start(&req).unwrap(); // } - #[crate::test] + #[ntex_rt::test] #[should_panic(expected = "OriginNotAllowed")] async fn test_validate_not_allowed_origin() { let cors = Cors::new() @@ -978,7 +978,7 @@ mod tests { cors.inner.validate_allowed_headers(req.head()).unwrap(); } - #[crate::test] + #[ntex_rt::test] async fn test_validate_origin() { let mut cors = Cors::new() .allowed_origin("https://www.example.com") @@ -995,7 +995,7 @@ mod tests { assert_eq!(resp.status(), StatusCode::OK); } - #[crate::test] + #[ntex_rt::test] async fn test_no_origin_response() { let mut cors = Cors::new() .disable_preflight() @@ -1024,7 +1024,7 @@ mod tests { ); } - #[crate::test] + #[ntex_rt::test] async fn test_response() { let exposed_headers = vec![header::AUTHORIZATION, header::ACCEPT]; let mut cors = Cors::new() @@ -1124,7 +1124,7 @@ mod tests { assert_eq!("https://www.example.com", origins_str); } - #[crate::test] + #[ntex_rt::test] async fn test_multiple_origins() { let mut cors = Cors::new() .allowed_origin("https://example.com") @@ -1162,7 +1162,7 @@ mod tests { ); } - #[crate::test] + #[ntex_rt::test] async fn test_multiple_origins_preflight() { let mut cors = Cors::new() .allowed_origin("https://example.com") diff --git a/ntex/src/web/middleware/defaultheaders.rs b/ntex/src/web/middleware/defaultheaders.rs index d5ecf9eb..bc2acd1b 100644 --- a/ntex/src/web/middleware/defaultheaders.rs +++ b/ntex/src/web/middleware/defaultheaders.rs @@ -170,7 +170,7 @@ mod tests { use crate::web::test::{ok_service, TestRequest}; use crate::web::{DefaultError, Error, HttpResponse}; - #[crate::test] + #[ntex_rt::test] async fn test_default_headers() { let mut mw = DefaultHeaders::::new() .header(CONTENT_TYPE, "0001") @@ -198,7 +198,7 @@ mod tests { assert_eq!(resp.headers().get(CONTENT_TYPE).unwrap(), "0002"); } - #[crate::test] + #[ntex_rt::test] async fn test_content_type() { let srv = |req: WebRequest| { ok::<_, Error>(req.into_response(HttpResponse::Ok().finish())) diff --git a/ntex/src/web/middleware/logger.rs b/ntex/src/web/middleware/logger.rs index dfa0fbc6..b29c6697 100644 --- a/ntex/src/web/middleware/logger.rs +++ b/ntex/src/web/middleware/logger.rs @@ -490,7 +490,7 @@ mod tests { use crate::web::test::TestRequest; use crate::web::{DefaultError, Error}; - #[crate::test] + #[ntex_rt::test] async fn test_logger() { let srv = |req: WebRequest| { ok::<_, Error>( @@ -515,7 +515,7 @@ mod tests { let _res = srv.call(req).await; } - #[crate::test] + #[ntex_rt::test] async fn test_url_path() { let mut format = Format::new("%T %U"); let req = TestRequest::with_header( @@ -545,7 +545,7 @@ mod tests { assert!(s.contains("/test/route/yeah")); } - #[crate::test] + #[ntex_rt::test] async fn test_default_format() { let mut format = Format::default(); @@ -578,7 +578,7 @@ mod tests { assert!(s.contains("ACTIX-WEB")); } - #[crate::test] + #[ntex_rt::test] async fn test_request_time_format() { let mut format = Format::new("%t"); let req = TestRequest::default().to_srv_request(); diff --git a/ntex/src/web/request.rs b/ntex/src/web/request.rs index 755c9f07..2740cadf 100644 --- a/ntex/src/web/request.rs +++ b/ntex/src/web/request.rs @@ -460,7 +460,7 @@ mod tests { ); } - #[crate::test] + #[ntex_rt::test] async fn test_data() { let mut srv = init_service(App::new().app_data(10usize).service( web::resource("/").to(|req: HttpRequest| { @@ -493,7 +493,7 @@ mod tests { assert_eq!(resp.status(), StatusCode::BAD_REQUEST); } - #[crate::test] + #[ntex_rt::test] async fn test_extensions_dropped() { struct Tracker { dropped: bool, diff --git a/ntex/src/web/resource.rs b/ntex/src/web/resource.rs index 57dc28b7..c4726bd8 100644 --- a/ntex/src/web/resource.rs +++ b/ntex/src/web/resource.rs @@ -558,18 +558,18 @@ impl ServiceFactory for ResourceEndpoint { mod tests { use std::time::Duration; - use actix_rt::time::delay_for; use futures::future::{ok, ready}; use crate::http::header::{self, HeaderValue}; use crate::http::{Method, StatusCode}; + use crate::rt::time::delay_for; use crate::web::middleware::DefaultHeaders; use crate::web::service::WebRequest; use crate::web::test::{call_service, init_service, TestRequest}; use crate::web::{self, guard, App, DefaultError, Error, HttpResponse}; use crate::Service; - #[crate::test] + #[ntex_rt::test] async fn test_middleware() { let mut srv = init_service( @@ -593,7 +593,7 @@ mod tests { ); } - #[crate::test] + #[ntex_rt::test] async fn test_middleware_fn() { let mut srv = init_service( App::new().service( @@ -623,7 +623,7 @@ mod tests { ); } - #[crate::test] + #[ntex_rt::test] async fn test_to() { let mut srv = init_service(App::new().service(web::resource("/test").to(|| async { @@ -636,7 +636,7 @@ mod tests { assert_eq!(resp.status(), StatusCode::OK); } - #[crate::test] + #[ntex_rt::test] async fn test_pattern() { let mut srv = init_service(App::new().service( web::resource(["/test", "/test2"]).to(|| async { HttpResponse::Ok() }), @@ -650,7 +650,7 @@ mod tests { assert_eq!(resp.status(), StatusCode::OK); } - #[crate::test] + #[ntex_rt::test] async fn test_default_resource() { let mut srv = init_service( App::new() @@ -695,7 +695,7 @@ mod tests { assert_eq!(resp.status(), StatusCode::BAD_REQUEST); } - #[crate::test] + #[ntex_rt::test] async fn test_resource_guards() { let mut srv = init_service( App::new() @@ -736,7 +736,7 @@ mod tests { assert_eq!(resp.status(), StatusCode::NO_CONTENT); } - #[crate::test] + #[ntex_rt::test] async fn test_data() { let mut srv = init_service( App::new() diff --git a/ntex/src/web/responder.rs b/ntex/src/web/responder.rs index afd7f40b..bc99bb13 100644 --- a/ntex/src/web/responder.rs +++ b/ntex/src/web/responder.rs @@ -485,7 +485,7 @@ pub(crate) mod tests { responder } - #[crate::test] + #[ntex_rt::test] async fn test_option_responder() { let mut srv = init_service( web::App::new() @@ -512,7 +512,7 @@ pub(crate) mod tests { } } - #[crate::test] + #[ntex_rt::test] async fn test_responder() { let req = TestRequest::default().to_http_request(); @@ -585,7 +585,7 @@ pub(crate) mod tests { assert_eq!(resp.status(), StatusCode::BAD_REQUEST); } - #[crate::test] + #[ntex_rt::test] async fn test_result_responder() { let req = TestRequest::default().to_http_request(); @@ -612,7 +612,7 @@ pub(crate) mod tests { assert!(res.is_err()); } - #[crate::test] + #[ntex_rt::test] async fn test_custom_responder() { let req = TestRequest::default().to_http_request(); let res = responder("test".to_string()) @@ -637,7 +637,7 @@ pub(crate) mod tests { ); } - #[crate::test] + #[ntex_rt::test] async fn test_tuple_responder_with_status_code() { let req = TestRequest::default().to_http_request(); let res = Responder::::respond_to( diff --git a/ntex/src/web/route.rs b/ntex/src/web/route.rs index c3d90de8..d62520ad 100644 --- a/ntex/src/web/route.rs +++ b/ntex/src/web/route.rs @@ -206,11 +206,11 @@ impl Route { mod tests { use std::time::Duration; - use actix_rt::time::delay_for; use bytes::Bytes; use serde_derive::Serialize; use crate::http::{Method, StatusCode}; + use crate::rt::time::delay_for; use crate::web::test::{call_service, init_service, read_body, TestRequest}; use crate::web::{self, error, App, DefaultError, HttpResponse}; @@ -219,7 +219,7 @@ mod tests { name: String, } - #[crate::test] + #[ntex_rt::test] async fn test_route() { let mut srv = init_service( App::new() diff --git a/ntex/src/web/scope.rs b/ntex/src/web/scope.rs index 679c2163..6e42d682 100644 --- a/ntex/src/web/scope.rs +++ b/ntex/src/web/scope.rs @@ -689,7 +689,7 @@ mod tests { use crate::web::DefaultError; use crate::web::{self, guard, App, HttpRequest, HttpResponse}; - #[crate::test] + #[ntex_rt::test] async fn test_scope() { let mut srv = init_service(App::new().service( @@ -704,7 +704,7 @@ mod tests { assert_eq!(resp.status(), StatusCode::OK); } - #[crate::test] + #[ntex_rt::test] async fn test_scope_root() { let mut srv = init_service( App::new().service( @@ -726,7 +726,7 @@ mod tests { assert_eq!(resp.status(), StatusCode::CREATED); } - #[crate::test] + #[ntex_rt::test] async fn test_scope_root2() { let mut srv = init_service( App::new().service( @@ -745,7 +745,7 @@ mod tests { assert_eq!(resp.status(), StatusCode::OK); } - #[crate::test] + #[ntex_rt::test] async fn test_scope_root3() { let mut srv = init_service( App::new().service( @@ -764,7 +764,7 @@ mod tests { assert_eq!(resp.status(), StatusCode::OK); } - #[crate::test] + #[ntex_rt::test] async fn test_scope_route() { let mut srv = init_service( App::new().service( @@ -792,7 +792,7 @@ mod tests { assert_eq!(resp.status(), StatusCode::NOT_FOUND); } - #[crate::test] + #[ntex_rt::test] async fn test_scope_route_without_leading_slash() { let mut srv = init_service( App::new().service( @@ -822,7 +822,7 @@ mod tests { assert_eq!(resp.status(), StatusCode::METHOD_NOT_ALLOWED); } - #[crate::test] + #[ntex_rt::test] async fn test_scope_guard() { let mut srv = init_service(App::new().service( @@ -845,7 +845,7 @@ mod tests { assert_eq!(resp.status(), StatusCode::OK); } - #[crate::test] + #[ntex_rt::test] async fn test_scope_variable_segment() { let mut srv = init_service(App::new().service(web::scope("/ab-{project}").service( @@ -873,7 +873,7 @@ mod tests { assert_eq!(resp.status(), StatusCode::NOT_FOUND); } - #[crate::test] + #[ntex_rt::test] async fn test_nested_scope() { let mut srv = init_service(App::new().service(web::scope("/app").service( web::scope("/t1").service( @@ -887,7 +887,7 @@ mod tests { assert_eq!(resp.status(), StatusCode::CREATED); } - #[crate::test] + #[ntex_rt::test] async fn test_nested_scope_no_slash() { let mut srv = init_service(App::new().service(web::scope("/app").service( web::scope("t1").service( @@ -901,7 +901,7 @@ mod tests { assert_eq!(resp.status(), StatusCode::CREATED); } - #[crate::test] + #[ntex_rt::test] async fn test_nested_scope_root() { let mut srv = init_service( App::new().service( @@ -925,7 +925,7 @@ mod tests { assert_eq!(resp.status(), StatusCode::CREATED); } - #[crate::test] + #[ntex_rt::test] async fn test_nested_scope_filter() { let mut srv = init_service(App::new().service(web::scope("/app").service( @@ -948,7 +948,7 @@ mod tests { assert_eq!(resp.status(), StatusCode::OK); } - #[crate::test] + #[ntex_rt::test] async fn test_nested_scope_with_variable_segment() { let mut srv = init_service(App::new().service(web::scope("/app").service( web::scope("/{project_id}").service(web::resource("/path1").to( @@ -973,7 +973,7 @@ mod tests { } } - #[crate::test] + #[ntex_rt::test] async fn test_nested2_scope_with_variable_segment() { let mut srv = init_service(App::new().service(web::scope("/app").service( web::scope("/{project}").service(web::scope("/{id}").service( @@ -1005,7 +1005,7 @@ mod tests { assert_eq!(resp.status(), StatusCode::NOT_FOUND); } - #[crate::test] + #[ntex_rt::test] async fn test_default_resource() { let mut srv = init_service( App::new().service( @@ -1027,7 +1027,7 @@ mod tests { assert_eq!(resp.status(), StatusCode::NOT_FOUND); } - #[crate::test] + #[ntex_rt::test] async fn test_default_resource_propagation() { let mut srv = init_service( App::new() @@ -1054,7 +1054,7 @@ mod tests { assert_eq!(resp.status(), StatusCode::METHOD_NOT_ALLOWED); } - #[crate::test] + #[ntex_rt::test] async fn test_middleware() { let mut srv = init_service( App::new().service( @@ -1080,7 +1080,7 @@ mod tests { ); } - #[crate::test] + #[ntex_rt::test] async fn test_middleware_fn() { let mut srv = init_service( App::new().service( @@ -1108,7 +1108,7 @@ mod tests { ); } - #[crate::test] + #[ntex_rt::test] async fn test_override_data() { let mut srv = init_service(App::new().data(1usize).service( web::scope("app").data(10usize).route( @@ -1127,7 +1127,7 @@ mod tests { assert_eq!(resp.status(), StatusCode::OK); } - #[crate::test] + #[ntex_rt::test] async fn test_override_app_data() { let mut srv = init_service(App::new().app_data(web::Data::new(1usize)).service( web::scope("app").app_data(web::Data::new(10usize)).route( @@ -1146,7 +1146,7 @@ mod tests { assert_eq!(resp.status(), StatusCode::OK); } - #[crate::test] + #[ntex_rt::test] async fn test_scope_config() { let mut srv = init_service(App::new().service(web::scope("/app").configure(|s| { @@ -1159,7 +1159,7 @@ mod tests { assert_eq!(resp.status(), StatusCode::OK); } - #[crate::test] + #[ntex_rt::test] async fn test_scope_config_2() { let mut srv = init_service(App::new().service(web::scope("/app").configure(|s| { @@ -1174,7 +1174,7 @@ mod tests { assert_eq!(resp.status(), StatusCode::OK); } - #[crate::test] + #[ntex_rt::test] async fn test_url_for_external() { let mut srv = init_service(App::new().service(web::scope("/app").configure(|s| { @@ -1203,7 +1203,7 @@ mod tests { assert_eq!(body, &b"https://youtube.com/watch/xxxxxx"[..]); } - #[crate::test] + #[ntex_rt::test] async fn test_url_for_nested() { let mut srv = init_service(App::new().service(web::scope("/a").service( web::scope("/b").service(web::resource("/c/{stuff}").name("c").route( diff --git a/ntex/src/web/server.rs b/ntex/src/web/server.rs index 751e8c24..f4297685 100644 --- a/ntex/src/web/server.rs +++ b/ntex/src/web/server.rs @@ -450,7 +450,7 @@ where mut self, lst: std::os::unix::net::UnixListener, ) -> io::Result { - use actix_rt::net::UnixStream; + use crate::rt::net::UnixStream; let cfg = self.config.clone(); let factory = self.factory.clone(); @@ -490,7 +490,7 @@ where where A: AsRef, { - use actix_rt::net::UnixStream; + use crate::rt::net::UnixStream; let cfg = self.config.clone(); let factory = self.factory.clone(); diff --git a/ntex/src/web/service.rs b/ntex/src/web/service.rs index 81b3125c..cdacbdb9 100644 --- a/ntex/src/web/service.rs +++ b/ntex/src/web/service.rs @@ -600,7 +600,7 @@ mod tests { assert!(WebRequest::::from_request(r).is_err()); } - #[crate::test] + #[ntex_rt::test] async fn test_service() { let mut srv = init_service(App::new().service( web::service("/test").name("test").finish( diff --git a/ntex/src/web/test.rs b/ntex/src/web/test.rs index 03e7c77e..1752e6b2 100644 --- a/ntex/src/web/test.rs +++ b/ntex/src/web/test.rs @@ -278,7 +278,7 @@ where /// /// For unit testing, actix provides a request builder type and a simple handler runner. TestRequest implements a builder-like pattern. /// You can generate various types of request via TestRequest's methods: -/// * `TestRequest::to_request` creates `actix_http::Request` instance. +/// * `TestRequest::to_request` creates `ntex::http::Request` instance. /// * `TestRequest::to_srv_request` creates `WebRequest` instance, which is used for testing middlewares and chain adapters. /// * `TestRequest::to_srv_response` creates `WebResponse` instance. /// * `TestRequest::to_http_request` creates `HttpRequest` instance, which is used for testing handlers. @@ -615,98 +615,102 @@ where // run server in separate thread thread::spawn(move || { - let sys = System::new("actix-test-server"); + let mut sys = System::new("actix-test-server"); + + let cfg = cfg.clone(); + let factory = factory.clone(); + let ctimeout = cfg.client_timeout; let tcp = net::TcpListener::bind("127.0.0.1:0").unwrap(); let local_addr = tcp.local_addr().unwrap(); - let factory = factory.clone(); - let cfg = cfg.clone(); - let ctimeout = cfg.client_timeout; - let builder = Server::build().workers(1).disable_signals(); - let srv = match cfg.stream { - StreamType::Tcp => match cfg.tp { - HttpVer::Http1 => builder.listen("test", tcp, move || { - let cfg = - AppConfig::new(false, local_addr, format!("{}", local_addr)); - HttpService::build() - .client_timeout(ctimeout) - .h1(map_config(factory(), move |_| cfg.clone())) - .tcp() - }), - HttpVer::Http2 => builder.listen("test", tcp, move || { - let cfg = - AppConfig::new(false, local_addr, format!("{}", local_addr)); - HttpService::build() - .client_timeout(ctimeout) - .h2(map_config(factory(), move |_| cfg.clone())) - .tcp() - }), - HttpVer::Both => builder.listen("test", tcp, move || { - let cfg = - AppConfig::new(false, local_addr, format!("{}", local_addr)); - HttpService::build() - .client_timeout(ctimeout) - .finish(map_config(factory(), move |_| cfg.clone())) - .tcp() - }), - }, - #[cfg(feature = "openssl")] - StreamType::Openssl(acceptor) => match cfg.tp { - HttpVer::Http1 => builder.listen("test", tcp, move || { - let cfg = - AppConfig::new(true, local_addr, format!("{}", local_addr)); - HttpService::build() - .client_timeout(ctimeout) - .h1(map_config(factory(), move |_| cfg.clone())) - .openssl(acceptor.clone()) - }), - HttpVer::Http2 => builder.listen("test", tcp, move || { - let cfg = - AppConfig::new(true, local_addr, format!("{}", local_addr)); - HttpService::build() - .client_timeout(ctimeout) - .h2(map_config(factory(), move |_| cfg.clone())) - .openssl(acceptor.clone()) - }), - HttpVer::Both => builder.listen("test", tcp, move || { - let cfg = - AppConfig::new(true, local_addr, format!("{}", local_addr)); - HttpService::build() - .client_timeout(ctimeout) - .finish(map_config(factory(), move |_| cfg.clone())) - .openssl(acceptor.clone()) - }), - }, - #[cfg(feature = "rustls")] - StreamType::Rustls(config) => match cfg.tp { - HttpVer::Http1 => builder.listen("test", tcp, move || { - let cfg = - AppConfig::new(true, local_addr, format!("{}", local_addr)); - HttpService::build() - .client_timeout(ctimeout) - .h1(map_config(factory(), move |_| cfg.clone())) - .rustls(config.clone()) - }), - HttpVer::Http2 => builder.listen("test", tcp, move || { - let cfg = - AppConfig::new(true, local_addr, format!("{}", local_addr)); - HttpService::build() - .client_timeout(ctimeout) - .h2(map_config(factory(), move |_| cfg.clone())) - .rustls(config.clone()) - }), - HttpVer::Both => builder.listen("test", tcp, move || { - let cfg = - AppConfig::new(true, local_addr, format!("{}", local_addr)); - HttpService::build() - .client_timeout(ctimeout) - .finish(map_config(factory(), move |_| cfg.clone())) - .rustls(config.clone()) - }), - }, - } - .unwrap() - .start(); + let srv = sys.exec(|| { + let builder = Server::build().workers(1).disable_signals(); + + match cfg.stream { + StreamType::Tcp => match cfg.tp { + HttpVer::Http1 => builder.listen("test", tcp, move || { + let cfg = + AppConfig::new(false, local_addr, format!("{}", local_addr)); + HttpService::build() + .client_timeout(ctimeout) + .h1(map_config(factory(), move |_| cfg.clone())) + .tcp() + }), + HttpVer::Http2 => builder.listen("test", tcp, move || { + let cfg = + AppConfig::new(false, local_addr, format!("{}", local_addr)); + HttpService::build() + .client_timeout(ctimeout) + .h2(map_config(factory(), move |_| cfg.clone())) + .tcp() + }), + HttpVer::Both => builder.listen("test", tcp, move || { + let cfg = + AppConfig::new(false, local_addr, format!("{}", local_addr)); + HttpService::build() + .client_timeout(ctimeout) + .finish(map_config(factory(), move |_| cfg.clone())) + .tcp() + }), + }, + #[cfg(feature = "openssl")] + StreamType::Openssl(acceptor) => match cfg.tp { + HttpVer::Http1 => builder.listen("test", tcp, move || { + let cfg = + AppConfig::new(true, local_addr, format!("{}", local_addr)); + HttpService::build() + .client_timeout(ctimeout) + .h1(map_config(factory(), move |_| cfg.clone())) + .openssl(acceptor.clone()) + }), + HttpVer::Http2 => builder.listen("test", tcp, move || { + let cfg = + AppConfig::new(true, local_addr, format!("{}", local_addr)); + HttpService::build() + .client_timeout(ctimeout) + .h2(map_config(factory(), move |_| cfg.clone())) + .openssl(acceptor.clone()) + }), + HttpVer::Both => builder.listen("test", tcp, move || { + let cfg = + AppConfig::new(true, local_addr, format!("{}", local_addr)); + HttpService::build() + .client_timeout(ctimeout) + .finish(map_config(factory(), move |_| cfg.clone())) + .openssl(acceptor.clone()) + }), + }, + #[cfg(feature = "rustls")] + StreamType::Rustls(config) => match cfg.tp { + HttpVer::Http1 => builder.listen("test", tcp, move || { + let cfg = + AppConfig::new(true, local_addr, format!("{}", local_addr)); + HttpService::build() + .client_timeout(ctimeout) + .h1(map_config(factory(), move |_| cfg.clone())) + .rustls(config.clone()) + }), + HttpVer::Http2 => builder.listen("test", tcp, move || { + let cfg = + AppConfig::new(true, local_addr, format!("{}", local_addr)); + HttpService::build() + .client_timeout(ctimeout) + .h2(map_config(factory(), move |_| cfg.clone())) + .rustls(config.clone()) + }), + HttpVer::Both => builder.listen("test", tcp, move || { + let cfg = + AppConfig::new(true, local_addr, format!("{}", local_addr)); + HttpService::build() + .client_timeout(ctimeout) + .finish(map_config(factory(), move |_| cfg.clone())) + .rustls(config.clone()) + }), + }, + } + .unwrap() + .start() + }); tx.send((System::current(), srv, local_addr)).unwrap(); sys.run() @@ -843,7 +847,7 @@ pub fn unused_addr() -> net::SocketAddr { pub struct TestServer { addr: net::SocketAddr, client: Client, - system: actix_rt::System, + system: crate::rt::System, ssl: bool, server: Server, } @@ -957,7 +961,7 @@ mod tests { use crate::http::HttpMessage; use crate::web::{self, App, Data, Error, HttpResponse}; - #[crate::test] + #[ntex_rt::test] async fn test_basics() { let req = TestRequest::with_header(header::CONTENT_TYPE, "application/json") .version(Version::HTTP_2) @@ -978,7 +982,7 @@ mod tests { assert_eq!(*data.get_ref(), 20); } - #[crate::test] + #[ntex_rt::test] async fn test_request_methods() { let mut app = init_service( App::new().service( @@ -1016,7 +1020,7 @@ mod tests { assert_eq!(result, Bytes::from_static(b"delete!")); } - #[crate::test] + #[ntex_rt::test] async fn test_response() { let mut app = init_service(App::new().service(web::resource("/index.html").route( @@ -1039,7 +1043,7 @@ mod tests { name: String, } - #[crate::test] + #[ntex_rt::test] async fn test_response_json() { let mut app = init_service(App::new().service(web::resource("/people").route( web::post().to(|person: web::types::Json| async { @@ -1060,7 +1064,7 @@ mod tests { assert_eq!(&result.id, "12345"); } - #[crate::test] + #[ntex_rt::test] async fn test_request_response_form() { let mut app = init_service(App::new().service(web::resource("/people").route( web::post().to(|person: web::types::Form| async { @@ -1086,7 +1090,7 @@ mod tests { assert_eq!(&result.name, "User name"); } - #[crate::test] + #[ntex_rt::test] async fn test_request_response_json() { let mut app = init_service(App::new().service(web::resource("/people").route( web::post().to(|person: web::types::Json| async { @@ -1112,7 +1116,7 @@ mod tests { assert_eq!(&result.name, "User name"); } - #[crate::test] + #[ntex_rt::test] async fn test_async_with_block() { async fn async_with_block() -> Result { let res = web::block(move || Some(4usize).ok_or("wrong")).await; @@ -1138,7 +1142,7 @@ mod tests { assert!(res.status().is_success()); } - #[crate::test] + #[ntex_rt::test] async fn test_server_data() { async fn handler(data: web::Data) -> crate::http::ResponseBuilder { assert_eq!(**data, 10); diff --git a/ntex/src/web/types/form.rs b/ntex/src/web/types/form.rs index 30f18c04..4c4c91f1 100644 --- a/ntex/src/web/types/form.rs +++ b/ntex/src/web/types/form.rs @@ -362,7 +362,7 @@ where // counter: i64, // } -// #[crate::test] +// #[ntex_rt::test] // async fn test_form() { // let (req, mut pl) = // TestRequest::with_header(CONTENT_TYPE, "application/x-www-form-urlencoded") @@ -398,7 +398,7 @@ where // } // } -// #[crate::test] +// #[ntex_rt::test] // async fn test_urlencoded_error() { // let (req, mut pl) = // TestRequest::with_header(CONTENT_TYPE, "application/x-www-form-urlencoded") @@ -424,7 +424,7 @@ where // assert!(eq(info.err().unwrap(), UrlencodedError::ContentType)); // } -// #[crate::test] +// #[ntex_rt::test] // async fn test_urlencoded() { // let (req, mut pl) = // TestRequest::with_header(CONTENT_TYPE, "application/x-www-form-urlencoded") @@ -459,7 +459,7 @@ where // ); // } -// #[crate::test] +// #[ntex_rt::test] // async fn test_responder() { // let req = TestRequest::default().to_http_request(); diff --git a/ntex/src/web/types/json.rs b/ntex/src/web/types/json.rs index 7ec9e2f9..1f7ff95d 100644 --- a/ntex/src/web/types/json.rs +++ b/ntex/src/web/types/json.rs @@ -414,7 +414,7 @@ where // } // } -// #[crate::test] +// #[ntex_rt::test] // async fn test_responder() { // let req = TestRequest::default().to_http_request(); @@ -431,7 +431,7 @@ where // assert_eq!(resp.body().bin_ref(), b"{\"name\":\"test\"}"); // } -// #[crate::test] +// #[ntex_rt::test] // async fn test_custom_error_responder() { // let (req, mut pl) = TestRequest::default() // .header( @@ -462,7 +462,7 @@ where // assert_eq!(msg.name, "invalid request"); // } -// #[crate::test] +// #[ntex_rt::test] // async fn test_extract() { // let (req, mut pl) = TestRequest::default() // .header( @@ -522,7 +522,7 @@ where // assert!(format!("{}", s.err().unwrap()).contains("Content type error")); // } -// #[crate::test] +// #[ntex_rt::test] // async fn test_json_body() { // let (req, mut pl) = TestRequest::default().to_http_parts(); // let json = JsonBody::::new(&req, &mut pl, None).await; @@ -574,7 +574,7 @@ where // ); // } -// #[crate::test] +// #[ntex_rt::test] // async fn test_with_json_and_bad_content_type() { // let (req, mut pl) = TestRequest::with_header( // header::CONTENT_TYPE, @@ -592,7 +592,7 @@ where // assert!(s.is_err()) // } -// #[crate::test] +// #[ntex_rt::test] // async fn test_with_json_and_good_custom_content_type() { // let (req, mut pl) = TestRequest::with_header( // header::CONTENT_TYPE, @@ -612,7 +612,7 @@ where // assert!(s.is_ok()) // } -// #[crate::test] +// #[ntex_rt::test] // async fn test_with_json_and_bad_custom_content_type() { // let (req, mut pl) = TestRequest::with_header( // header::CONTENT_TYPE, diff --git a/ntex/src/web/types/path.rs b/ntex/src/web/types/path.rs index efab936a..5ea14c0c 100644 --- a/ntex/src/web/types/path.rs +++ b/ntex/src/web/types/path.rs @@ -202,7 +202,7 @@ where // value: u32, // } -// #[crate::test] +// #[ntex_rt::test] // async fn test_extract_path_single() { // let resource = ResourceDef::new("/{value}/"); @@ -214,7 +214,7 @@ where // assert!(Path::::from_request(&req, &mut pl).await.is_err()); // } -// #[crate::test] +// #[ntex_rt::test] // async fn test_tuple_extract() { // let resource = ResourceDef::new("/{key}/{value}/"); @@ -241,7 +241,7 @@ where // let () = <()>::from_request(&req, &mut pl).await.unwrap(); // } -// #[crate::test] +// #[ntex_rt::test] // async fn test_request_extract() { // let mut req = TestRequest::with_uri("/name/user1/?id=test").to_srv_request(); @@ -289,7 +289,7 @@ where // assert_eq!(res[1], "32".to_owned()); // } -// #[crate::test] +// #[ntex_rt::test] // async fn test_custom_err_handler() { // let (req, mut pl) = TestRequest::with_uri("/name/user1/") // .data(PathConfig::default().error_handler(|err, _| { diff --git a/ntex/src/web/types/payload.rs b/ntex/src/web/types/payload.rs index 7ecf17bb..452875f2 100644 --- a/ntex/src/web/types/payload.rs +++ b/ntex/src/web/types/payload.rs @@ -422,7 +422,7 @@ impl Future for HttpMessageBody { // use crate::http::header; // use crate::web::test::TestRequest; -// #[crate::test] +// #[ntex_rt::test] // async fn test_payload_config() { // let req = TestRequest::default().to_http_request(); // let cfg = PayloadConfig::default().mimetype(mime::APPLICATION_JSON); @@ -440,7 +440,7 @@ impl Future for HttpMessageBody { // assert!(cfg.check_mimetype(&req).is_ok()); // } -// #[crate::test] +// #[ntex_rt::test] // async fn test_bytes() { // let (req, mut pl) = TestRequest::with_header(header::CONTENT_LENGTH, "11") // .set_payload(Bytes::from_static(b"hello=world")) @@ -450,7 +450,7 @@ impl Future for HttpMessageBody { // assert_eq!(s, Bytes::from_static(b"hello=world")); // } -// #[crate::test] +// #[ntex_rt::test] // async fn test_string() { // let (req, mut pl) = TestRequest::with_header(header::CONTENT_LENGTH, "11") // .set_payload(Bytes::from_static(b"hello=world")) @@ -460,7 +460,7 @@ impl Future for HttpMessageBody { // assert_eq!(s, "hello=world"); // } -// #[crate::test] +// #[ntex_rt::test] // async fn test_message_body() { // let (req, mut pl) = TestRequest::with_header(header::CONTENT_LENGTH, "xxxx") // .to_srv_request() diff --git a/ntex/src/web/types/query.rs b/ntex/src/web/types/query.rs index 6740d55e..b0c6de8f 100644 --- a/ntex/src/web/types/query.rs +++ b/ntex/src/web/types/query.rs @@ -169,7 +169,7 @@ where // id: String, // } -// #[crate::test] +// #[ntex_rt::test] // async fn test_service_request_extract() { // let req = TestRequest::with_uri("/name/user1/").to_srv_request(); // assert!(Query::::from_query(&req.query_string()).is_err()); @@ -185,7 +185,7 @@ where // assert_eq!(s.id, "test1"); // } -// #[crate::test] +// #[ntex_rt::test] // async fn test_request_extract() { // let req = TestRequest::with_uri("/name/user1/").to_srv_request(); // let (req, mut pl) = req.into_parts(); diff --git a/ntex/tests/server.rs b/ntex/tests/server.rs index b9e85bba..cd6b175a 100644 --- a/ntex/tests/server.rs +++ b/ntex/tests/server.rs @@ -28,13 +28,15 @@ fn test_bind() { let (tx, rx) = mpsc::channel(); let h = thread::spawn(move || { - let sys = ntex::rt::System::new("test"); - let srv = Server::build() - .workers(1) - .disable_signals() - .bind("test", addr, move || fn_service(|_| ok::<_, ()>(()))) - .unwrap() - .start(); + let mut sys = ntex::rt::System::new("test"); + let srv = sys.exec(|| { + Server::build() + .workers(1) + .disable_signals() + .bind("test", addr, move || fn_service(|_| ok::<_, ()>(()))) + .unwrap() + .start() + }); let _ = tx.send((srv, ntex::rt::System::current())); let _ = sys.run(); }); @@ -52,14 +54,16 @@ fn test_listen() { let (tx, rx) = mpsc::channel(); let h = thread::spawn(move || { - let sys = ntex::rt::System::new("test"); + let mut sys = ntex::rt::System::new("test"); let lst = net::TcpListener::bind(addr).unwrap(); - Server::build() - .disable_signals() - .workers(1) - .listen("test", lst, move || fn_service(|_| ok::<_, ()>(()))) - .unwrap() - .start(); + sys.exec(|| { + Server::build() + .disable_signals() + .workers(1) + .listen("test", lst, move || fn_service(|_| ok::<_, ()>(()))) + .unwrap() + .start() + }); let _ = tx.send(ntex::rt::System::current()); let _ = sys.run(); }); @@ -78,19 +82,21 @@ fn test_start() { let (tx, rx) = mpsc::channel(); let h = thread::spawn(move || { - let sys = ntex::rt::System::new("test"); - let srv: Server = Server::build() - .backlog(100) - .disable_signals() - .bind("test", addr, move || { - fn_service(|io: TcpStream| async move { - let mut f = Framed::new(io, BytesCodec); - f.send(Bytes::from_static(b"test")).await.unwrap(); - Ok::<_, ()>(()) + let mut sys = ntex::rt::System::new("test"); + let srv = sys.exec(|| { + Server::build() + .backlog(100) + .disable_signals() + .bind("test", addr, move || { + fn_service(|io: TcpStream| async move { + let mut f = Framed::new(io, BytesCodec); + f.send(Bytes::from_static(b"test")).await.unwrap(); + Ok::<_, ()>(()) + }) }) - }) - .unwrap() - .start(); + .unwrap() + .start() + }); let _ = tx.send((srv, ntex::rt::System::current())); let _ = sys.run(); @@ -144,29 +150,31 @@ fn test_configure() { let h = thread::spawn(move || { let num = num2.clone(); - let sys = ntex::rt::System::new("test"); - let srv = Server::build() - .disable_signals() - .configure(move |cfg| { - let num = num.clone(); - let lst = net::TcpListener::bind(addr3).unwrap(); - cfg.bind("addr1", addr1) - .unwrap() - .bind("addr2", addr2) - .unwrap() - .listen("addr3", lst) - .apply(move |rt| { - let num = num.clone(); - rt.service("addr1", fn_service(|_| ok::<_, ()>(()))); - rt.service("addr3", fn_service(|_| ok::<_, ()>(()))); - rt.on_start(lazy(move |_| { - let _ = num.fetch_add(1, Relaxed); - })) - }) - }) - .unwrap() - .workers(1) - .start(); + let mut sys = ntex::rt::System::new("test"); + let srv = sys.exec(|| { + Server::build() + .disable_signals() + .configure(move |cfg| { + let num = num.clone(); + let lst = net::TcpListener::bind(addr3).unwrap(); + cfg.bind("addr1", addr1) + .unwrap() + .bind("addr2", addr2) + .unwrap() + .listen("addr3", lst) + .apply(move |rt| { + let num = num.clone(); + rt.service("addr1", fn_service(|_| ok::<_, ()>(()))); + rt.service("addr3", fn_service(|_| ok::<_, ()>(()))); + rt.on_start(lazy(move |_| { + let _ = num.fetch_add(1, Relaxed); + })) + }) + }) + .unwrap() + .workers(1) + .start() + }); let _ = tx.send((srv, ntex::rt::System::current())); let _ = sys.run(); }); diff --git a/ntex/tests/web_httpserver.rs b/ntex/tests/web_httpserver.rs index c501ac97..09f364b1 100644 --- a/ntex/tests/web_httpserver.rs +++ b/ntex/tests/web_httpserver.rs @@ -23,27 +23,29 @@ async fn test_start() { let (tx, rx) = mpsc::channel(); thread::spawn(move || { - let sys = ntex::rt::System::new("test"); + let mut sys = ntex::rt::System::new("test"); - let srv = HttpServer::new(|| { - App::new().service( - web::resource("/") - .route(web::to(|| async { HttpResponse::Ok().body("test") })), - ) - }) - .workers(1) - .backlog(1) - .maxconn(10) - .maxconnrate(10) - .keep_alive(10) - .client_timeout(5000) - .client_shutdown(0) - .server_hostname("localhost") - .system_exit() - .disable_signals() - .bind(format!("{}", addr)) - .unwrap() - .run(); + let srv = sys.exec(|| { + HttpServer::new(|| { + App::new().service( + web::resource("/") + .route(web::to(|| async { HttpResponse::Ok().body("test") })), + ) + }) + .workers(1) + .backlog(1) + .maxconn(10) + .maxconnrate(10) + .keep_alive(10) + .client_timeout(5000) + .client_shutdown(0) + .server_hostname("localhost") + .system_exit() + .disable_signals() + .bind(format!("{}", addr)) + .unwrap() + .run() + }); let _ = tx.send((srv, ntex::rt::System::current())); let _ = sys.run(); @@ -94,24 +96,26 @@ async fn test_start_ssl() { let (tx, rx) = mpsc::channel(); thread::spawn(move || { - let sys = ntex::rt::System::new("test"); + let mut sys = ntex::rt::System::new("test"); let builder = ssl_acceptor().unwrap(); - let srv = HttpServer::new(|| { - App::new().service(web::resource("/").route(web::to( - |req: HttpRequest| async move { - assert!(req.app_config().secure()); - HttpResponse::Ok().body("test") - }, - ))) - }) - .workers(1) - .shutdown_timeout(1) - .system_exit() - .disable_signals() - .bind_openssl(format!("{}", addr), builder) - .unwrap() - .run(); + let srv = sys.exec(|| { + HttpServer::new(|| { + App::new().service(web::resource("/").route(web::to( + |req: HttpRequest| async move { + assert!(req.app_config().secure()); + HttpResponse::Ok().body("test") + }, + ))) + }) + .workers(1) + .shutdown_timeout(1) + .system_exit() + .disable_signals() + .bind_openssl(format!("{}", addr), builder) + .unwrap() + .run() + }); let _ = tx.send((srv, ntex::rt::System::current())); let _ = sys.run();