actix-web-codegen-4.3.0/.cargo_vcs_info.json0000644000000001570000000000100143300ustar { "git": { "sha1": "a5c78483f9d83d3f916d75c8a5ce46909faf32bc" }, "path_in_vcs": "actix-web-codegen" }actix-web-codegen-4.3.0/CHANGES.md000064400000000000000000000070231046102023000145110ustar 00000000000000# Changes ## Unreleased ## 4.3.0 - Add `#[scope]` macro. - Add `compat-routing-macros-force-pub` crate feature which, on-by-default, which when disabled causes handlers to inherit their attached function's visibility. - Prevent inclusion of default `actix-router` features. - Minimum supported Rust version (MSRV) is now 1.72. ## 4.2.2 - Fix regression when declaring `wrap` attribute using an expression. ## 4.2.1 - Update `syn` dependency to `2`. - Minimum supported Rust version (MSRV) is now 1.68 due to transitive `time` dependency. ## 4.2.0 - Add support for custom methods with the `#[route]` macro. [#2969] [#2969]: https://github.com/actix/actix-web/pull/2969 ## 4.1.0 - Add `#[routes]` macro to support multiple paths for one handler. [#2718] - Minimum supported Rust version (MSRV) is now 1.59 due to transitive `time` dependency. [#2718]: https://github.com/actix/actix-web/pull/2718 ## 4.0.1 - Fix support for guard paths in route handler macros. [#2771] - Minimum supported Rust version (MSRV) is now 1.56 due to transitive `hashbrown` dependency. [#2771]: https://github.com/actix/actix-web/pull/2771 ## 4.0.0 - Version aligned with `actix-web` and will remain in sync going forward. - No significant changes since `0.5.0`. ## 0.5.0 - No significant changes since `0.5.0-rc.2`. ## 0.5.0-rc.2 - No significant changes since `0.5.0-rc.1`. ## 0.5.0-rc.1 - Minimum supported Rust version (MSRV) is now 1.54. ## 0.5.0-beta.6 - No significant changes since `0.5.0-beta.5`. ## 0.5.0-beta.5 - Improve error recovery potential when macro input is invalid. [#2410] - Add `#[actix_web::test]` macro for setting up tests with a runtime. [#2409] - Minimum supported Rust version (MSRV) is now 1.52. [#2410]: https://github.com/actix/actix-web/pull/2410 [#2409]: https://github.com/actix/actix-web/pull/2409 ## 0.5.0-beta.4 - In routing macros, paths are now validated at compile time. [#2350] - Minimum supported Rust version (MSRV) is now 1.51. [#2350]: https://github.com/actix/actix-web/pull/2350 ## 0.5.0-beta.3 - No notable changes. ## 0.5.0-beta.2 - Preserve doc comments when using route macros. [#2022] - Add `name` attribute to `route` macro. [#1934] [#2022]: https://github.com/actix/actix-web/pull/2022 [#1934]: https://github.com/actix/actix-web/pull/1934 ## 0.5.0-beta.1 - Use new call signature for `System::new`. ## 0.4.0 - Added compile success and failure testing. [#1677] - Add `route` macro for supporting multiple HTTP methods guards. [#1674] [#1677]: https://github.com/actix/actix-web/pull/1677 [#1674]: https://github.com/actix/actix-web/pull/1674 ## 0.3.0 - No significant changes from `0.3.0-beta.1`. ## 0.3.0-beta.1 - Add main entry-point macro that uses re-exported runtime. [#1559] [#1559]: https://github.com/actix/actix-web/pull/1559 ## 0.2.2 - Add resource middleware on actix-web-codegen [#1467] [#1467]: https://github.com/actix/actix-web/pull/1467 ## 0.2.1 - Add `#[allow(missing_docs)]` attribute to generated structs [#1368] - Allow the handler function to be named as `config` [#1290] [#1368]: https://github.com/actix/actix-web/issues/1368 [#1290]: https://github.com/actix/actix-web/issues/1290 ## 0.2.0 - Generate code for actix-web 2.0 ## 0.1.3 - Bump up `syn` & `quote` to 1.0 - Provide better error message ## 0.1.2 - Add macros for head, options, trace, connect and patch http methods ## 0.1.1 - Add syn "extra-traits" feature ## 0.1.0 - Release ## 0.1.0-beta.1 - Gen code for actix-web 1.0.0-beta.1 ## 0.1.0-alpha.6 - Gen code for actix-web 1.0.0-alpha.6 ## 0.1.0-alpha.1 - Initial impl actix-web-codegen-4.3.0/Cargo.toml0000644000000031110000000000100123170ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2021" rust-version = "1.72" name = "actix-web-codegen" version = "4.3.0" authors = [ "Nikolay Kim ", "Rob Ede ", ] description = "Routing and runtime macros for Actix Web" homepage = "https://actix.rs" readme = "README.md" license = "MIT OR Apache-2.0" repository = "https://github.com/actix/actix-web" [lib] proc-macro = true [dependencies.actix-router] version = "0.5" default-features = false [dependencies.proc-macro2] version = "1" [dependencies.quote] version = "1" [dependencies.syn] version = "2" features = [ "full", "extra-traits", ] [dev-dependencies.actix-macros] version = "0.2.4" [dev-dependencies.actix-rt] version = "2.2" [dev-dependencies.actix-test] version = "0.1" [dev-dependencies.actix-utils] version = "3" [dev-dependencies.actix-web] version = "4" [dev-dependencies.futures-core] version = "0.3.17" features = ["alloc"] default-features = false [dev-dependencies.rustversion] version = "1" [dev-dependencies.trybuild] version = "1" [features] compat-routing-macros-force-pub = [] default = ["compat-routing-macros-force-pub"] actix-web-codegen-4.3.0/Cargo.toml.orig000064400000000000000000000015321046102023000160050ustar 00000000000000[package] name = "actix-web-codegen" version = "4.3.0" description = "Routing and runtime macros for Actix Web" authors = [ "Nikolay Kim ", "Rob Ede ", ] homepage.workspace = true repository.workspace = true license.workspace = true edition.workspace = true rust-version.workspace = true [lib] proc-macro = true [features] default = ["compat-routing-macros-force-pub"] compat-routing-macros-force-pub = [] [dependencies] actix-router = { version = "0.5", default-features = false } proc-macro2 = "1" quote = "1" syn = { version = "2", features = ["full", "extra-traits"] } [dev-dependencies] actix-macros = "0.2.4" actix-rt = "2.2" actix-test = "0.1" actix-utils = "3" actix-web = "4" futures-core = { version = "0.3.17", default-features = false, features = ["alloc"] } trybuild = "1" rustversion = "1" actix-web-codegen-4.3.0/LICENSE-APACHE000064400000000000000000000261201046102023000150420ustar 00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "{}" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright 2017-NOW Actix Team Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. actix-web-codegen-4.3.0/LICENSE-MIT000064400000000000000000000020421046102023000145470ustar 00000000000000Copyright (c) 2017-NOW Actix Team 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. actix-web-codegen-4.3.0/README.md000064400000000000000000000022311046102023000143720ustar 00000000000000# `actix-web-codegen` > Routing and runtime macros for Actix Web. [![crates.io](https://img.shields.io/crates/v/actix-web-codegen?label=latest)](https://crates.io/crates/actix-web-codegen) [![Documentation](https://docs.rs/actix-web-codegen/badge.svg?version=4.3.0)](https://docs.rs/actix-web-codegen/4.3.0) ![Version](https://img.shields.io/badge/rustc-1.72+-ab6000.svg) ![License](https://img.shields.io/crates/l/actix-web-codegen.svg)
[![dependency status](https://deps.rs/crate/actix-web-codegen/4.3.0/status.svg)](https://deps.rs/crate/actix-web-codegen/4.3.0) [![Download](https://img.shields.io/crates/d/actix-web-codegen.svg)](https://crates.io/crates/actix-web-codegen) [![Chat on Discord](https://img.shields.io/discord/771444961383153695?label=chat&logo=discord)](https://discord.gg/NWpN5mmg3x) ## Compile Testing Uses the [`trybuild`] crate. All compile fail tests should include a stderr file generated by `trybuild`. See the [workflow section](https://github.com/dtolnay/trybuild#workflow) of the trybuild docs for info on how to do this. [`trybuild`]: https://github.com/dtolnay/trybuild actix-web-codegen-4.3.0/src/lib.rs000064400000000000000000000221061046102023000150210ustar 00000000000000//! Routing and runtime macros for Actix Web. //! //! # Actix Web Re-exports //! Actix Web re-exports a version of this crate in it's entirety so you usually don't have to //! specify a dependency on this crate explicitly. Sometimes, however, updates are made to this //! crate before the actix-web dependency is updated. Therefore, code examples here will show //! explicit imports. Check the latest [actix-web attributes docs] to see which macros //! are re-exported. //! //! # Runtime Setup //! Used for setting up the actix async runtime. See [macro@main] macro docs. //! //! ``` //! #[actix_web_codegen::main] // or `#[actix_web::main]` in Actix Web apps //! async fn main() { //! async { println!("Hello world"); }.await //! } //! ``` //! //! # Single Method Handler //! There is a macro to set up a handler for each of the most common HTTP methods that also define //! additional guards and route-specific middleware. //! //! See docs for: [GET], [POST], [PATCH], [PUT], [DELETE], [HEAD], [CONNECT], [OPTIONS], [TRACE] //! //! ``` //! # use actix_web::HttpResponse; //! # use actix_web_codegen::get; //! #[get("/test")] //! async fn get_handler() -> HttpResponse { //! HttpResponse::Ok().finish() //! } //! ``` //! //! # Multiple Method Handlers //! Similar to the single method handler macro but takes one or more arguments for the HTTP methods //! it should respond to. See [macro@route] macro docs. //! //! ``` //! # use actix_web::HttpResponse; //! # use actix_web_codegen::route; //! #[route("/test", method = "GET", method = "HEAD")] //! async fn get_and_head_handler() -> HttpResponse { //! HttpResponse::Ok().finish() //! } //! ``` //! //! # Multiple Path Handlers //! Acts as a wrapper for multiple single method handler macros. It takes no arguments and //! delegates those to the macros for the individual methods. See [macro@routes] macro docs. //! //! ``` //! # use actix_web::HttpResponse; //! # use actix_web_codegen::routes; //! #[routes] //! #[get("/test")] //! #[get("/test2")] //! #[delete("/test")] //! async fn example() -> HttpResponse { //! HttpResponse::Ok().finish() //! } //! ``` //! //! [actix-web attributes docs]: https://docs.rs/actix-web/latest/actix_web/#attributes //! [GET]: macro@get //! [POST]: macro@post //! [PUT]: macro@put //! [HEAD]: macro@head //! [CONNECT]: macro@macro@connect //! [OPTIONS]: macro@options //! [TRACE]: macro@trace //! [PATCH]: macro@patch //! [DELETE]: macro@delete #![recursion_limit = "512"] #![deny(rust_2018_idioms, nonstandard_style)] #![warn(future_incompatible)] #![doc(html_logo_url = "https://actix.rs/img/logo.png")] #![doc(html_favicon_url = "https://actix.rs/favicon.ico")] #![cfg_attr(docsrs, feature(doc_auto_cfg))] use proc_macro::TokenStream; use quote::quote; mod route; mod scope; /// Creates resource handler, allowing multiple HTTP method guards. /// /// # Syntax /// ```plain /// #[route("path", method="HTTP_METHOD"[, attributes])] /// ``` /// /// # Attributes /// - `"path"`: Raw literal string with path for which to register handler. /// - `name = "resource_name"`: Specifies resource name for the handler. If not set, the function /// name of handler is used. /// - `method = "HTTP_METHOD"`: Registers HTTP method to provide guard for. Upper-case string, /// "GET", "POST" for example. /// - `guard = "function_name"`: Registers function as guard using `actix_web::guard::fn_guard`. /// - `wrap = "Middleware"`: Registers a resource middleware. /// /// # Notes /// Function name can be specified as any expression that is going to be accessible to the generate /// code, e.g `my_guard` or `my_module::my_guard`. /// /// # Examples /// ``` /// # use actix_web::HttpResponse; /// # use actix_web_codegen::route; /// #[route("/test", method = "GET", method = "HEAD", method = "CUSTOM")] /// async fn example() -> HttpResponse { /// HttpResponse::Ok().finish() /// } /// ``` #[proc_macro_attribute] pub fn route(args: TokenStream, input: TokenStream) -> TokenStream { route::with_method(None, args, input) } /// Creates resource handler, allowing multiple HTTP methods and paths. /// /// # Syntax /// ```plain /// #[routes] /// #[("path", ...)] /// #[("path", ...)] /// ... /// ``` /// /// # Attributes /// The `routes` macro itself has no parameters, but allows specifying the attribute macros for /// the multiple paths and/or methods, e.g. [`GET`](macro@get) and [`POST`](macro@post). /// /// These helper attributes take the same parameters as the [single method handlers](crate#single-method-handler). /// /// # Examples /// ``` /// # use actix_web::HttpResponse; /// # use actix_web_codegen::routes; /// #[routes] /// #[get("/test")] /// #[get("/test2")] /// #[delete("/test")] /// async fn example() -> HttpResponse { /// HttpResponse::Ok().finish() /// } /// ``` #[proc_macro_attribute] pub fn routes(_: TokenStream, input: TokenStream) -> TokenStream { route::with_methods(input) } macro_rules! method_macro { ($variant:ident, $method:ident) => { #[doc = concat!("Creates route handler with `actix_web::guard::", stringify!($variant), "`.")] /// /// # Syntax /// ```plain #[doc = concat!("#[", stringify!($method), r#"("path"[, attributes])]"#)] /// ``` /// /// # Attributes /// - `"path"`: Raw literal string with path for which to register handler. /// - `name = "resource_name"`: Specifies resource name for the handler. If not set, the /// function name of handler is used. /// - `guard = "function_name"`: Registers function as guard using `actix_web::guard::fn_guard`. /// - `wrap = "Middleware"`: Registers a resource middleware. /// /// # Notes /// Function name can be specified as any expression that is going to be accessible to the /// generate code, e.g `my_guard` or `my_module::my_guard`. /// /// # Examples /// ``` /// # use actix_web::HttpResponse; #[doc = concat!("# use actix_web_codegen::", stringify!($method), ";")] #[doc = concat!("#[", stringify!($method), r#"("/")]"#)] /// async fn example() -> HttpResponse { /// HttpResponse::Ok().finish() /// } /// ``` #[proc_macro_attribute] pub fn $method(args: TokenStream, input: TokenStream) -> TokenStream { route::with_method(Some(route::MethodType::$variant), args, input) } }; } method_macro!(Get, get); method_macro!(Post, post); method_macro!(Put, put); method_macro!(Delete, delete); method_macro!(Head, head); method_macro!(Connect, connect); method_macro!(Options, options); method_macro!(Trace, trace); method_macro!(Patch, patch); /// Prepends a path prefix to all handlers using routing macros inside the attached module. /// /// # Syntax /// /// ``` /// # use actix_web_codegen::scope; /// #[scope("/prefix")] /// mod api { /// // ... /// } /// ``` /// /// # Arguments /// /// - `"/prefix"` - Raw literal string to be prefixed onto contained handlers' paths. /// /// # Example /// /// ``` /// # use actix_web_codegen::{scope, get}; /// # use actix_web::Responder; /// #[scope("/api")] /// mod api { /// # use super::*; /// #[get("/hello")] /// pub async fn hello() -> impl Responder { /// // this has path /api/hello /// "Hello, world!" /// } /// } /// # fn main() {} /// ``` #[proc_macro_attribute] pub fn scope(args: TokenStream, input: TokenStream) -> TokenStream { scope::with_scope(args, input) } /// Marks async main function as the Actix Web system entry-point. /// /// Note that Actix Web also works under `#[tokio::main]` since version 4.0. However, this macro is /// still necessary for actor support (since actors use a `System`). Read more in the /// [`actix_web::rt`](https://docs.rs/actix-web/4/actix_web/rt) module docs. /// /// # Examples /// ``` /// #[actix_web::main] /// async fn main() { /// async { println!("Hello world"); }.await /// } /// ``` #[proc_macro_attribute] pub fn main(_: TokenStream, item: TokenStream) -> TokenStream { let mut output: TokenStream = (quote! { #[::actix_web::rt::main(system = "::actix_web::rt::System")] }) .into(); output.extend(item); output } /// Marks async test functions to use the Actix Web system entry-point. /// /// # Examples /// ``` /// #[actix_web::test] /// async fn test() { /// assert_eq!(async { "Hello world" }.await, "Hello world"); /// } /// ``` #[proc_macro_attribute] pub fn test(_: TokenStream, item: TokenStream) -> TokenStream { let mut output: TokenStream = (quote! { #[::actix_web::rt::test(system = "::actix_web::rt::System")] }) .into(); output.extend(item); output } /// Converts the error to a token stream and appends it to the original input. /// /// Returning the original input in addition to the error is good for IDEs which can gracefully /// recover and show more precise errors within the macro body. /// /// See for more info. fn input_and_compile_error(mut item: TokenStream, err: syn::Error) -> TokenStream { let compile_err = TokenStream::from(err.to_compile_error()); item.extend(compile_err); item } actix-web-codegen-4.3.0/src/route.rs000064400000000000000000000422541046102023000154170ustar 00000000000000use std::collections::HashSet; use actix_router::ResourceDef; use proc_macro::TokenStream; use proc_macro2::{Span, TokenStream as TokenStream2}; use quote::{quote, ToTokens, TokenStreamExt}; use syn::{punctuated::Punctuated, Ident, LitStr, Path, Token}; use crate::input_and_compile_error; #[derive(Debug)] pub struct RouteArgs { pub(crate) path: syn::LitStr, pub(crate) options: Punctuated, } impl syn::parse::Parse for RouteArgs { fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result { // path to match: "/foo" let path = input.parse::().map_err(|mut err| { err.combine(syn::Error::new( err.span(), r#"invalid service definition, expected #[("")]"#, )); err })?; // verify that path pattern is valid let _ = ResourceDef::new(path.value()); // if there's no comma, assume that no options are provided if !input.peek(Token![,]) { return Ok(Self { path, options: Punctuated::new(), }); } // advance past comma separator input.parse::()?; // if next char is a literal, assume that it is a string and show multi-path error if input.cursor().literal().is_some() { return Err(syn::Error::new( Span::call_site(), r#"Multiple paths specified! There should be only one."#, )); } // zero or more options: name = "foo" let options = input.parse_terminated(syn::MetaNameValue::parse, Token![,])?; Ok(Self { path, options }) } } macro_rules! standard_method_type { ( $($variant:ident, $upper:ident, $lower:ident,)+ ) => { #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub enum MethodType { $( $variant, )+ } impl MethodType { fn as_str(&self) -> &'static str { match self { $(Self::$variant => stringify!($variant),)+ } } fn parse(method: &str) -> Result { match method { $(stringify!($upper) => Ok(Self::$variant),)+ _ => Err(format!("HTTP method must be uppercase: `{}`", method)), } } pub(crate) fn from_path(method: &Path) -> Result { match () { $(_ if method.is_ident(stringify!($lower)) => Ok(Self::$variant),)+ _ => Err(()), } } } }; } standard_method_type! { Get, GET, get, Post, POST, post, Put, PUT, put, Delete, DELETE, delete, Head, HEAD, head, Connect, CONNECT, connect, Options, OPTIONS, options, Trace, TRACE, trace, Patch, PATCH, patch, } impl TryFrom<&syn::LitStr> for MethodType { type Error = syn::Error; fn try_from(value: &syn::LitStr) -> Result { Self::parse(value.value().as_str()) .map_err(|message| syn::Error::new_spanned(value, message)) } } impl ToTokens for MethodType { fn to_tokens(&self, stream: &mut TokenStream2) { let ident = Ident::new(self.as_str(), Span::call_site()); stream.append(ident); } } #[derive(Debug, Clone, PartialEq, Eq, Hash)] enum MethodTypeExt { Standard(MethodType), Custom(LitStr), } impl MethodTypeExt { /// Returns a single method guard token stream. fn to_tokens_single_guard(&self) -> TokenStream2 { match self { MethodTypeExt::Standard(method) => { quote! { .guard(::actix_web::guard::#method()) } } MethodTypeExt::Custom(lit) => { quote! { .guard(::actix_web::guard::Method( ::actix_web::http::Method::from_bytes(#lit.as_bytes()).unwrap() )) } } } } /// Returns a multi-method guard chain token stream. fn to_tokens_multi_guard(&self, or_chain: Vec) -> TokenStream2 { debug_assert!( !or_chain.is_empty(), "empty or_chain passed to multi-guard constructor" ); match self { MethodTypeExt::Standard(method) => { quote! { .guard( ::actix_web::guard::Any(::actix_web::guard::#method()) #(#or_chain)* ) } } MethodTypeExt::Custom(lit) => { quote! { .guard( ::actix_web::guard::Any( ::actix_web::guard::Method( ::actix_web::http::Method::from_bytes(#lit.as_bytes()).unwrap() ) ) #(#or_chain)* ) } } } } /// Returns a token stream containing the `.or` chain to be passed in to /// [`MethodTypeExt::to_tokens_multi_guard()`]. fn to_tokens_multi_guard_or_chain(&self) -> TokenStream2 { match self { MethodTypeExt::Standard(method_type) => { quote! { .or(::actix_web::guard::#method_type()) } } MethodTypeExt::Custom(lit) => { quote! { .or( ::actix_web::guard::Method( ::actix_web::http::Method::from_bytes(#lit.as_bytes()).unwrap() ) ) } } } } } impl ToTokens for MethodTypeExt { fn to_tokens(&self, stream: &mut TokenStream2) { match self { MethodTypeExt::Custom(lit_str) => { let ident = Ident::new(lit_str.value().as_str(), Span::call_site()); stream.append(ident); } MethodTypeExt::Standard(method) => method.to_tokens(stream), } } } impl TryFrom<&syn::LitStr> for MethodTypeExt { type Error = syn::Error; fn try_from(value: &syn::LitStr) -> Result { match MethodType::try_from(value) { Ok(method) => Ok(MethodTypeExt::Standard(method)), Err(_) if value.value().chars().all(|c| c.is_ascii_uppercase()) => { Ok(MethodTypeExt::Custom(value.clone())) } Err(err) => Err(err), } } } struct Args { path: syn::LitStr, resource_name: Option, guards: Vec, wrappers: Vec, methods: HashSet, } impl Args { fn new(args: RouteArgs, method: Option) -> syn::Result { let mut resource_name = None; let mut guards = Vec::new(); let mut wrappers = Vec::new(); let mut methods = HashSet::new(); let is_route_macro = method.is_none(); if let Some(method) = method { methods.insert(MethodTypeExt::Standard(method)); } for nv in args.options { if nv.path.is_ident("name") { if let syn::Expr::Lit(syn::ExprLit { lit: syn::Lit::Str(lit), .. }) = nv.value { resource_name = Some(lit); } else { return Err(syn::Error::new_spanned( nv.value, "Attribute name expects literal string", )); } } else if nv.path.is_ident("guard") { if let syn::Expr::Lit(syn::ExprLit { lit: syn::Lit::Str(lit), .. }) = nv.value { guards.push(lit.parse::()?); } else { return Err(syn::Error::new_spanned( nv.value, "Attribute guard expects literal string", )); } } else if nv.path.is_ident("wrap") { if let syn::Expr::Lit(syn::ExprLit { lit: syn::Lit::Str(lit), .. }) = nv.value { wrappers.push(lit.parse()?); } else { return Err(syn::Error::new_spanned( nv.value, "Attribute wrap expects type", )); } } else if nv.path.is_ident("method") { if !is_route_macro { return Err(syn::Error::new_spanned( &nv, "HTTP method forbidden here; to handle multiple methods, use `route` instead", )); } else if let syn::Expr::Lit(syn::ExprLit { lit: syn::Lit::Str(lit), .. }) = nv.value.clone() { if !methods.insert(MethodTypeExt::try_from(&lit)?) { return Err(syn::Error::new_spanned( nv.value, format!("HTTP method defined more than once: `{}`", lit.value()), )); } } else { return Err(syn::Error::new_spanned( nv.value, "Attribute method expects literal string", )); } } else { return Err(syn::Error::new_spanned( nv.path, "Unknown attribute key is specified; allowed: guard, method and wrap", )); } } Ok(Args { path: args.path, resource_name, guards, wrappers, methods, }) } } pub struct Route { /// Name of the handler function being annotated. name: syn::Ident, /// Args passed to routing macro. /// /// When using `#[routes]`, this will contain args for each specific routing macro. args: Vec, /// AST of the handler function being annotated. ast: syn::ItemFn, /// The doc comment attributes to copy to generated struct, if any. doc_attributes: Vec, } impl Route { pub fn new(args: RouteArgs, ast: syn::ItemFn, method: Option) -> syn::Result { let name = ast.sig.ident.clone(); // Try and pull out the doc comments so that we can reapply them to the generated struct. // Note that multi line doc comments are converted to multiple doc attributes. let doc_attributes = ast .attrs .iter() .filter(|attr| attr.path().is_ident("doc")) .cloned() .collect(); let args = Args::new(args, method)?; if args.methods.is_empty() { return Err(syn::Error::new( Span::call_site(), "The #[route(..)] macro requires at least one `method` attribute", )); } if matches!(ast.sig.output, syn::ReturnType::Default) { return Err(syn::Error::new_spanned( ast, "Function has no return type. Cannot be used as handler", )); } Ok(Self { name, args: vec![args], ast, doc_attributes, }) } fn multiple(args: Vec, ast: syn::ItemFn) -> syn::Result { let name = ast.sig.ident.clone(); // Try and pull out the doc comments so that we can reapply them to the generated struct. // Note that multi line doc comments are converted to multiple doc attributes. let doc_attributes = ast .attrs .iter() .filter(|attr| attr.path().is_ident("doc")) .cloned() .collect(); if matches!(ast.sig.output, syn::ReturnType::Default) { return Err(syn::Error::new_spanned( ast, "Function has no return type. Cannot be used as handler", )); } Ok(Self { name, args, ast, doc_attributes, }) } } impl ToTokens for Route { fn to_tokens(&self, output: &mut TokenStream2) { let Self { name, ast, args, doc_attributes, } = self; #[allow(unused_variables)] // used when force-pub feature is disabled let vis = &ast.vis; // TODO(breaking): remove this force-pub forwards-compatibility feature #[cfg(feature = "compat-routing-macros-force-pub")] let vis = syn::Visibility::Public(::default()); let registrations: TokenStream2 = args .iter() .map(|args| { let Args { path, resource_name, guards, wrappers, methods, } = args; let resource_name = resource_name .as_ref() .map_or_else(|| name.to_string(), LitStr::value); let method_guards = { debug_assert!(!methods.is_empty(), "Args::methods should not be empty"); let mut others = methods.iter(); let first = others.next().unwrap(); if methods.len() > 1 { let other_method_guards = others .map(|method_ext| method_ext.to_tokens_multi_guard_or_chain()) .collect(); first.to_tokens_multi_guard(other_method_guards) } else { first.to_tokens_single_guard() } }; quote! { let __resource = ::actix_web::Resource::new(#path) .name(#resource_name) #method_guards #(.guard(::actix_web::guard::fn_guard(#guards)))* #(.wrap(#wrappers))* .to(#name); ::actix_web::dev::HttpServiceFactory::register(__resource, __config); } }) .collect(); let stream = quote! { #(#doc_attributes)* #[allow(non_camel_case_types, missing_docs)] #vis struct #name; impl ::actix_web::dev::HttpServiceFactory for #name { fn register(self, __config: &mut actix_web::dev::AppService) { #ast #registrations } } }; output.extend(stream); } } pub(crate) fn with_method( method: Option, args: TokenStream, input: TokenStream, ) -> TokenStream { let args = match syn::parse(args) { Ok(args) => args, // on parse error, make IDEs happy; see fn docs Err(err) => return input_and_compile_error(input, err), }; let ast = match syn::parse::(input.clone()) { Ok(ast) => ast, // on parse error, make IDEs happy; see fn docs Err(err) => return input_and_compile_error(input, err), }; match Route::new(args, ast, method) { Ok(route) => route.into_token_stream().into(), // on macro related error, make IDEs happy; see fn docs Err(err) => input_and_compile_error(input, err), } } pub(crate) fn with_methods(input: TokenStream) -> TokenStream { let mut ast = match syn::parse::(input.clone()) { Ok(ast) => ast, // on parse error, make IDEs happy; see fn docs Err(err) => return input_and_compile_error(input, err), }; let (methods, others) = ast .attrs .into_iter() .map(|attr| match MethodType::from_path(attr.path()) { Ok(method) => Ok((method, attr)), Err(_) => Err(attr), }) .partition::, _>(Result::is_ok); ast.attrs = others.into_iter().map(Result::unwrap_err).collect(); let methods = match methods .into_iter() .map(Result::unwrap) .map(|(method, attr)| { attr.parse_args() .and_then(|args| Args::new(args, Some(method))) }) .collect::, _>>() { Ok(methods) if methods.is_empty() => { return input_and_compile_error( input, syn::Error::new( Span::call_site(), "The #[routes] macro requires at least one `#[(..)]` attribute.", ), ) } Ok(methods) => methods, Err(err) => return input_and_compile_error(input, err), }; match Route::multiple(methods, ast) { Ok(route) => route.into_token_stream().into(), // on macro related error, make IDEs happy; see fn docs Err(err) => input_and_compile_error(input, err), } } actix-web-codegen-4.3.0/src/scope.rs000064400000000000000000000067451046102023000153770ustar 00000000000000use proc_macro::TokenStream; use proc_macro2::{Span, TokenStream as TokenStream2}; use quote::{quote, ToTokens as _}; use crate::{ input_and_compile_error, route::{MethodType, RouteArgs}, }; pub fn with_scope(args: TokenStream, input: TokenStream) -> TokenStream { match with_scope_inner(args, input.clone()) { Ok(stream) => stream, Err(err) => input_and_compile_error(input, err), } } fn with_scope_inner(args: TokenStream, input: TokenStream) -> syn::Result { if args.is_empty() { return Err(syn::Error::new( Span::call_site(), "missing arguments for scope macro, expected: #[scope(\"/prefix\")]", )); } let scope_prefix = syn::parse::(args.clone()).map_err(|err| { syn::Error::new( err.span(), "argument to scope macro is not a string literal, expected: #[scope(\"/prefix\")]", ) })?; let scope_prefix_value = scope_prefix.value(); if scope_prefix_value.ends_with('/') { // trailing slashes cause non-obvious problems // it's better to point them out to developers rather than return Err(syn::Error::new( scope_prefix.span(), "scopes should not have trailing slashes; see https://docs.rs/actix-web/4/actix_web/struct.Scope.html#avoid-trailing-slashes", )); } let mut module = syn::parse::(input).map_err(|err| { syn::Error::new(err.span(), "#[scope] macro must be attached to a module") })?; // modify any routing macros (method or route[s]) attached to // functions by prefixing them with this scope macro's argument if let Some((_, items)) = &mut module.content { for item in items { if let syn::Item::Fn(fun) = item { fun.attrs = fun .attrs .iter() .map(|attr| modify_attribute_with_scope(attr, &scope_prefix_value)) .collect(); } } } Ok(module.to_token_stream().into()) } /// Checks if the attribute is a method type and has a route path, then modifies it. fn modify_attribute_with_scope(attr: &syn::Attribute, scope_path: &str) -> syn::Attribute { match (attr.parse_args::(), attr.clone().meta) { (Ok(route_args), syn::Meta::List(meta_list)) if has_allowed_methods_in_scope(attr) => { let modified_path = format!("{}{}", scope_path, route_args.path.value()); let options_tokens: Vec = route_args .options .iter() .map(|option| { quote! { ,#option } }) .collect(); let combined_options_tokens: TokenStream2 = options_tokens .into_iter() .fold(TokenStream2::new(), |mut acc, ts| { acc.extend(std::iter::once(ts)); acc }); syn::Attribute { meta: syn::Meta::List(syn::MetaList { tokens: quote! { #modified_path #combined_options_tokens }, ..meta_list.clone() }), ..attr.clone() } } _ => attr.clone(), } } fn has_allowed_methods_in_scope(attr: &syn::Attribute) -> bool { MethodType::from_path(attr.path()).is_ok() || attr.path().is_ident("route") || attr.path().is_ident("ROUTE") } actix-web-codegen-4.3.0/tests/routes.rs000064400000000000000000000276561046102023000161660ustar 00000000000000use std::future::Future; use actix_utils::future::{ok, Ready}; use actix_web::{ dev::{Service, ServiceRequest, ServiceResponse, Transform}, http::{ self, header::{HeaderName, HeaderValue}, StatusCode, }, web, App, Error, HttpRequest, HttpResponse, Responder, }; use actix_web_codegen::{ connect, delete, get, head, options, patch, post, put, route, routes, trace, }; use futures_core::future::LocalBoxFuture; // Make sure that we can name function as 'config' #[get("/config")] async fn config() -> impl Responder { HttpResponse::Ok() } #[get("/test")] async fn test_handler() -> impl Responder { HttpResponse::Ok() } #[put("/test")] async fn put_test() -> impl Responder { HttpResponse::Created() } #[patch("/test")] async fn patch_test() -> impl Responder { HttpResponse::Ok() } #[post("/test")] async fn post_test() -> impl Responder { HttpResponse::NoContent() } #[head("/test")] async fn head_test() -> impl Responder { HttpResponse::Ok() } #[connect("/test")] async fn connect_test() -> impl Responder { HttpResponse::Ok() } #[options("/test")] async fn options_test() -> impl Responder { HttpResponse::Ok() } #[trace("/test")] async fn trace_test() -> impl Responder { HttpResponse::Ok() } #[get("/test")] fn auto_async() -> impl Future> { ok(HttpResponse::Ok().finish()) } #[get("/test")] fn auto_sync() -> impl Future> { ok(HttpResponse::Ok().finish()) } #[put("/test/{param}")] async fn put_param_test(_: web::Path) -> impl Responder { HttpResponse::Created() } #[delete("/test/{param}")] async fn delete_param_test(_: web::Path) -> impl Responder { HttpResponse::NoContent() } #[get("/test/{param}")] async fn get_param_test(_: web::Path) -> impl Responder { HttpResponse::Ok() } #[route("/hello", method = "HELLO")] async fn custom_route_test() -> impl Responder { HttpResponse::Ok() } #[route( "/multi", method = "GET", method = "POST", method = "HEAD", method = "HELLO" )] async fn route_test() -> impl Responder { HttpResponse::Ok() } #[routes] #[get("/routes/test")] #[get("/routes/test2")] #[post("/routes/test")] async fn routes_test() -> impl Responder { HttpResponse::Ok() } // routes overlap with the more specific route first, therefore accessible #[routes] #[get("/routes/overlap/test")] #[get("/routes/overlap/{foo}")] async fn routes_overlapping_test(req: HttpRequest) -> impl Responder { // foo is only populated when route is not /routes/overlap/test match req.match_info().get("foo") { None => assert!(req.uri() == "/routes/overlap/test"), Some(_) => assert!(req.uri() != "/routes/overlap/test"), } HttpResponse::Ok() } // routes overlap with the more specific route last, therefore inaccessible #[routes] #[get("/routes/overlap2/{foo}")] #[get("/routes/overlap2/test")] async fn routes_overlapping_inaccessible_test(req: HttpRequest) -> impl Responder { // foo is always populated even when path is /routes/overlap2/test assert!(req.match_info().get("foo").is_some()); HttpResponse::Ok() } #[get("/custom_resource_name", name = "custom")] async fn custom_resource_name_test<'a>(req: HttpRequest) -> impl Responder { assert!(req.url_for_static("custom").is_ok()); assert!(req.url_for_static("custom_resource_name_test").is_err()); HttpResponse::Ok() } mod guard_module { use actix_web::{guard::GuardContext, http::header}; pub fn guard(ctx: &GuardContext) -> bool { ctx.header::() .map(|h| h.preference() == "image/*") .unwrap_or(false) } } #[get("/test/guard", guard = "guard_module::guard")] async fn guard_test() -> impl Responder { HttpResponse::Ok() } pub struct ChangeStatusCode; impl Transform for ChangeStatusCode where S: Service, Error = Error>, S::Future: 'static, B: 'static, { type Response = ServiceResponse; type Error = Error; type Transform = ChangeStatusCodeMiddleware; type InitError = (); type Future = Ready>; fn new_transform(&self, service: S) -> Self::Future { ok(ChangeStatusCodeMiddleware { service }) } } pub struct ChangeStatusCodeMiddleware { service: S, } impl Service for ChangeStatusCodeMiddleware where S: Service, Error = Error>, S::Future: 'static, B: 'static, { type Response = ServiceResponse; type Error = Error; type Future = LocalBoxFuture<'static, Result>; actix_web::dev::forward_ready!(service); fn call(&self, req: ServiceRequest) -> Self::Future { let fut = self.service.call(req); Box::pin(async move { let mut res = fut.await?; let headers = res.headers_mut(); let header_name = HeaderName::from_lowercase(b"custom-header").unwrap(); let header_value = HeaderValue::from_str("hello").unwrap(); headers.insert(header_name, header_value); Ok(res) }) } } #[get("/test/wrap", wrap = "ChangeStatusCode")] async fn get_wrap(_: web::Path) -> impl Responder { // panic!("actually never gets called because path failed to extract"); HttpResponse::Ok() } /// Using expression, not just path to type, in wrap attribute. /// /// Regression from . #[route( "/catalog", method = "GET", method = "HEAD", wrap = "actix_web::middleware::Compress::default()" )] async fn get_catalog() -> impl Responder { HttpResponse::Ok().body("123123123") } #[actix_rt::test] async fn test_params() { let srv = actix_test::start(|| { App::new() .service(get_param_test) .service(put_param_test) .service(delete_param_test) }); let request = srv.request(http::Method::GET, srv.url("/test/it")); let response = request.send().await.unwrap(); assert_eq!(response.status(), http::StatusCode::OK); let request = srv.request(http::Method::PUT, srv.url("/test/it")); let response = request.send().await.unwrap(); assert_eq!(response.status(), http::StatusCode::CREATED); let request = srv.request(http::Method::DELETE, srv.url("/test/it")); let response = request.send().await.unwrap(); assert_eq!(response.status(), http::StatusCode::NO_CONTENT); } #[actix_rt::test] async fn test_body() { let srv = actix_test::start(|| { App::new() .service(post_test) .service(put_test) .service(head_test) .service(connect_test) .service(options_test) .service(trace_test) .service(patch_test) .service(test_handler) .service(route_test) .service(routes_overlapping_test) .service(routes_overlapping_inaccessible_test) .service(routes_test) .service(custom_resource_name_test) .service(guard_test) }); let request = srv.request(http::Method::GET, srv.url("/test")); let response = request.send().await.unwrap(); assert!(response.status().is_success()); let request = srv.request(http::Method::HEAD, srv.url("/test")); let response = request.send().await.unwrap(); assert!(response.status().is_success()); let request = srv.request(http::Method::CONNECT, srv.url("/test")); let response = request.send().await.unwrap(); assert!(response.status().is_success()); let request = srv.request(http::Method::OPTIONS, srv.url("/test")); let response = request.send().await.unwrap(); assert!(response.status().is_success()); let request = srv.request(http::Method::TRACE, srv.url("/test")); let response = request.send().await.unwrap(); assert!(response.status().is_success()); let request = srv.request(http::Method::PATCH, srv.url("/test")); let response = request.send().await.unwrap(); assert!(response.status().is_success()); let request = srv.request(http::Method::PUT, srv.url("/test")); let response = request.send().await.unwrap(); assert!(response.status().is_success()); assert_eq!(response.status(), http::StatusCode::CREATED); let request = srv.request(http::Method::POST, srv.url("/test")); let response = request.send().await.unwrap(); assert!(response.status().is_success()); assert_eq!(response.status(), http::StatusCode::NO_CONTENT); let request = srv.request(http::Method::GET, srv.url("/test")); let response = request.send().await.unwrap(); assert!(response.status().is_success()); let request = srv.request(http::Method::GET, srv.url("/multi")); let response = request.send().await.unwrap(); assert!(response.status().is_success()); let request = srv.request(http::Method::POST, srv.url("/multi")); let response = request.send().await.unwrap(); assert!(response.status().is_success()); let request = srv.request(http::Method::HEAD, srv.url("/multi")); let response = request.send().await.unwrap(); assert!(response.status().is_success()); let request = srv.request(http::Method::PATCH, srv.url("/multi")); let response = request.send().await.unwrap(); assert!(!response.status().is_success()); let request = srv.request(http::Method::GET, srv.url("/routes/test")); let response = request.send().await.unwrap(); assert!(response.status().is_success()); let request = srv.request(http::Method::GET, srv.url("/routes/test2")); let response = request.send().await.unwrap(); assert!(response.status().is_success()); let request = srv.request(http::Method::POST, srv.url("/routes/test")); let response = request.send().await.unwrap(); assert!(response.status().is_success()); let request = srv.request(http::Method::GET, srv.url("/routes/not-set")); let response = request.send().await.unwrap(); assert!(response.status().is_client_error()); let request = srv.request(http::Method::GET, srv.url("/routes/overlap/test")); let response = request.send().await.unwrap(); assert!(response.status().is_success()); let request = srv.request(http::Method::GET, srv.url("/routes/overlap/bar")); let response = request.send().await.unwrap(); assert!(response.status().is_success()); let request = srv.request(http::Method::GET, srv.url("/routes/overlap2/test")); let response = request.send().await.unwrap(); assert!(response.status().is_success()); let request = srv.request(http::Method::GET, srv.url("/routes/overlap2/bar")); let response = request.send().await.unwrap(); assert!(response.status().is_success()); let request = srv.request(http::Method::GET, srv.url("/custom_resource_name")); let response = request.send().await.unwrap(); assert!(response.status().is_success()); let request = srv .request(http::Method::GET, srv.url("/test/guard")) .insert_header(("Accept", "image/*")); let response = request.send().await.unwrap(); assert!(response.status().is_success()); } #[actix_rt::test] async fn test_auto_async() { let srv = actix_test::start(|| App::new().service(auto_async)); let request = srv.request(http::Method::GET, srv.url("/test")); let response = request.send().await.unwrap(); assert!(response.status().is_success()); } #[actix_web::test] async fn test_wrap() { let srv = actix_test::start(|| App::new().service(get_wrap)); let request = srv.request(http::Method::GET, srv.url("/test/wrap")); let mut response = request.send().await.unwrap(); assert_eq!(response.status(), StatusCode::NOT_FOUND); assert!(response.headers().contains_key("custom-header")); let body = response.body().await.unwrap(); let body = String::from_utf8(body.to_vec()).unwrap(); assert!(body.contains("wrong number of parameters")); } actix-web-codegen-4.3.0/tests/scopes.rs000064400000000000000000000145431046102023000161300ustar 00000000000000use actix_web::{guard::GuardContext, http, http::header, web, App, HttpResponse, Responder}; use actix_web_codegen::{delete, get, post, route, routes, scope}; pub fn image_guard(ctx: &GuardContext) -> bool { ctx.header::() .map(|h| h.preference() == "image/*") .unwrap_or(false) } #[scope("/test")] mod scope_module { // ensure that imports can be brought into the scope use super::*; #[get("/test/guard", guard = "image_guard")] pub async fn guard() -> impl Responder { HttpResponse::Ok() } #[get("/test")] pub async fn test() -> impl Responder { HttpResponse::Ok().finish() } #[get("/twice-test/{value}")] pub async fn twice(value: web::Path) -> impl actix_web::Responder { let int_value: i32 = value.parse().unwrap_or(0); let doubled = int_value * 2; HttpResponse::Ok().body(format!("Twice value: {}", doubled)) } #[post("/test")] pub async fn post() -> impl Responder { HttpResponse::Ok().body("post works") } #[delete("/test")] pub async fn delete() -> impl Responder { "delete works" } #[route("/test", method = "PUT", method = "PATCH", method = "CUSTOM")] pub async fn multiple_shared_path() -> impl Responder { HttpResponse::Ok().finish() } #[routes] #[head("/test1")] #[connect("/test2")] #[options("/test3")] #[trace("/test4")] pub async fn multiple_separate_paths() -> impl Responder { HttpResponse::Ok().finish() } // test calling this from other mod scope with scope attribute... pub fn mod_common(message: String) -> impl actix_web::Responder { HttpResponse::Ok().body(message) } } /// Scope doc string to check in cargo expand. #[scope("/v1")] mod mod_scope_v1 { use super::*; /// Route doc string to check in cargo expand. #[get("/test")] pub async fn test() -> impl Responder { scope_module::mod_common("version1 works".to_string()) } } #[scope("/v2")] mod mod_scope_v2 { use super::*; // check to make sure non-function tokens in the scope block are preserved... enum TestEnum { Works, } #[get("/test")] pub async fn test() -> impl Responder { // make sure this type still exists... let test_enum = TestEnum::Works; match test_enum { TestEnum::Works => scope_module::mod_common("version2 works".to_string()), } } } #[actix_rt::test] async fn scope_get_async() { let srv = actix_test::start(|| App::new().service(scope_module::test)); let request = srv.request(http::Method::GET, srv.url("/test/test")); let response = request.send().await.unwrap(); assert!(response.status().is_success()); } #[actix_rt::test] async fn scope_get_param_async() { let srv = actix_test::start(|| App::new().service(scope_module::twice)); let request = srv.request(http::Method::GET, srv.url("/test/twice-test/4")); let mut response = request.send().await.unwrap(); let body = response.body().await.unwrap(); let body_str = String::from_utf8(body.to_vec()).unwrap(); assert_eq!(body_str, "Twice value: 8"); } #[actix_rt::test] async fn scope_post_async() { let srv = actix_test::start(|| App::new().service(scope_module::post)); let request = srv.request(http::Method::POST, srv.url("/test/test")); let mut response = request.send().await.unwrap(); let body = response.body().await.unwrap(); let body_str = String::from_utf8(body.to_vec()).unwrap(); assert_eq!(body_str, "post works"); } #[actix_rt::test] async fn multiple_shared_path_async() { let srv = actix_test::start(|| App::new().service(scope_module::multiple_shared_path)); let request = srv.request(http::Method::PUT, srv.url("/test/test")); let response = request.send().await.unwrap(); assert!(response.status().is_success()); let request = srv.request(http::Method::PATCH, srv.url("/test/test")); let response = request.send().await.unwrap(); assert!(response.status().is_success()); } #[actix_rt::test] async fn multiple_multi_path_async() { let srv = actix_test::start(|| App::new().service(scope_module::multiple_separate_paths)); let request = srv.request(http::Method::HEAD, srv.url("/test/test1")); let response = request.send().await.unwrap(); assert!(response.status().is_success()); let request = srv.request(http::Method::CONNECT, srv.url("/test/test2")); let response = request.send().await.unwrap(); assert!(response.status().is_success()); let request = srv.request(http::Method::OPTIONS, srv.url("/test/test3")); let response = request.send().await.unwrap(); assert!(response.status().is_success()); let request = srv.request(http::Method::TRACE, srv.url("/test/test4")); let response = request.send().await.unwrap(); assert!(response.status().is_success()); } #[actix_rt::test] async fn scope_delete_async() { let srv = actix_test::start(|| App::new().service(scope_module::delete)); let request = srv.request(http::Method::DELETE, srv.url("/test/test")); let mut response = request.send().await.unwrap(); let body = response.body().await.unwrap(); let body_str = String::from_utf8(body.to_vec()).unwrap(); assert_eq!(body_str, "delete works"); } #[actix_rt::test] async fn scope_get_with_guard_async() { let srv = actix_test::start(|| App::new().service(scope_module::guard)); let request = srv .request(http::Method::GET, srv.url("/test/test/guard")) .insert_header(("Accept", "image/*")); let response = request.send().await.unwrap(); assert!(response.status().is_success()); } #[actix_rt::test] async fn scope_v1_v2_async() { let srv = actix_test::start(|| { App::new() .service(mod_scope_v1::test) .service(mod_scope_v2::test) }); let request = srv.request(http::Method::GET, srv.url("/v1/test")); let mut response = request.send().await.unwrap(); let body = response.body().await.unwrap(); let body_str = String::from_utf8(body.to_vec()).unwrap(); assert_eq!(body_str, "version1 works"); let request = srv.request(http::Method::GET, srv.url("/v2/test")); let mut response = request.send().await.unwrap(); let body = response.body().await.unwrap(); let body_str = String::from_utf8(body.to_vec()).unwrap(); assert_eq!(body_str, "version2 works"); } actix-web-codegen-4.3.0/tests/trybuild/docstring-ok.rs000064400000000000000000000006451046102023000210730ustar 00000000000000use actix_web::{Responder, HttpResponse, App}; use actix_web_codegen::*; /// doc comments shouldn't break anything #[get("/")] async fn index() -> impl Responder { HttpResponse::Ok() } #[actix_web::main] async fn main() { let srv = actix_test::start(|| App::new().service(index)); let request = srv.get("/"); let response = request.send().await.unwrap(); assert!(response.status().is_success()); } actix-web-codegen-4.3.0/tests/trybuild/route-custom-lowercase.rs000064400000000000000000000007351046102023000231200ustar 00000000000000use actix_web_codegen::*; use actix_web::http::Method; use std::str::FromStr; #[route("/", method = "hello")] async fn index() -> String { "Hello World!".to_owned() } #[actix_web::main] async fn main() { use actix_web::App; let srv = actix_test::start(|| App::new().service(index)); let request = srv.request(Method::from_str("hello").unwrap(), srv.url("/")); let response = request.send().await.unwrap(); assert!(response.status().is_success()); } actix-web-codegen-4.3.0/tests/trybuild/route-custom-lowercase.stderr000064400000000000000000000026071046102023000237770ustar 00000000000000error: HTTP method must be uppercase: `hello` --> tests/trybuild/route-custom-lowercase.rs:5:23 | 5 | #[route("/", method = "hello")] | ^^^^^^^ error[E0277]: the trait bound `fn() -> impl std::future::Future {index}: HttpServiceFactory` is not satisfied --> tests/trybuild/route-custom-lowercase.rs:14:55 | 14 | let srv = actix_test::start(|| App::new().service(index)); | ------- ^^^^^ the trait `HttpServiceFactory` is not implemented for fn item `fn() -> impl std::future::Future {index}` | | | required by a bound introduced by this call | = help: the following other types implement trait `HttpServiceFactory`: Resource actix_web::Scope Vec Redirect (A,) (A, B) (A, B, C) (A, B, C, D) and $N others note: required by a bound in `App::::service` --> $WORKSPACE/actix-web/src/app.rs | | pub fn service(mut self, factory: F) -> Self | ------- required by a bound in this associated function | where | F: HttpServiceFactory + 'static, | ^^^^^^^^^^^^^^^^^^ required by this bound in `App::::service` actix-web-codegen-4.3.0/tests/trybuild/route-custom-method.rs000064400000000000000000000021531046102023000224100ustar 00000000000000use std::str::FromStr; use actix_web::http::Method; use actix_web_codegen::route; #[route("/single", method = "CUSTOM")] async fn index() -> String { "Hello Single!".to_owned() } #[route("/multi", method = "GET", method = "CUSTOM")] async fn custom() -> String { "Hello Multi!".to_owned() } #[actix_web::main] async fn main() { use actix_web::App; let srv = actix_test::start(|| App::new().service(index).service(custom)); let request = srv.request(Method::GET, srv.url("/")); let response = request.send().await.unwrap(); assert!(response.status().is_client_error()); let request = srv.request(Method::from_str("CUSTOM").unwrap(), srv.url("/single")); let response = request.send().await.unwrap(); assert!(response.status().is_success()); let request = srv.request(Method::GET, srv.url("/multi")); let response = request.send().await.unwrap(); assert!(response.status().is_success()); let request = srv.request(Method::from_str("CUSTOM").unwrap(), srv.url("/multi")); let response = request.send().await.unwrap(); assert!(response.status().is_success()); } actix-web-codegen-4.3.0/tests/trybuild/route-duplicate-method-fail.rs000064400000000000000000000006021046102023000237560ustar 00000000000000use actix_web_codegen::*; #[route("/", method="GET", method="GET")] async fn index() -> String { "Hello World!".to_owned() } #[actix_web::main] async fn main() { use actix_web::App; let srv = actix_test::start(|| App::new().service(index)); let request = srv.get("/"); let response = request.send().await.unwrap(); assert!(response.status().is_success()); } actix-web-codegen-4.3.0/tests/trybuild/route-duplicate-method-fail.stderr000064400000000000000000000026501046102023000246420ustar 00000000000000error: HTTP method defined more than once: `GET` --> tests/trybuild/route-duplicate-method-fail.rs:3:35 | 3 | #[route("/", method="GET", method="GET")] | ^^^^^ error[E0277]: the trait bound `fn() -> impl std::future::Future {index}: HttpServiceFactory` is not satisfied --> tests/trybuild/route-duplicate-method-fail.rs:12:55 | 12 | let srv = actix_test::start(|| App::new().service(index)); | ------- ^^^^^ the trait `HttpServiceFactory` is not implemented for fn item `fn() -> impl std::future::Future {index}` | | | required by a bound introduced by this call | = help: the following other types implement trait `HttpServiceFactory`: Resource actix_web::Scope Vec Redirect (A,) (A, B) (A, B, C) (A, B, C, D) and $N others note: required by a bound in `App::::service` --> $WORKSPACE/actix-web/src/app.rs | | pub fn service(mut self, factory: F) -> Self | ------- required by a bound in this associated function | where | F: HttpServiceFactory + 'static, | ^^^^^^^^^^^^^^^^^^ required by this bound in `App::::service` actix-web-codegen-4.3.0/tests/trybuild/route-malformed-path-fail.rs000064400000000000000000000011241046102023000234260ustar 00000000000000use actix_web_codegen::get; #[get("/{")] async fn zero() -> &'static str { "malformed resource def" } #[get("/{foo")] async fn one() -> &'static str { "malformed resource def" } #[get("/{}")] async fn two() -> &'static str { "malformed resource def" } #[get("/*")] async fn three() -> &'static str { "malformed resource def" } #[get("/{tail:\\d+}*")] async fn four() -> &'static str { "malformed resource def" } #[get("/{a}/{b}/{c}/{d}/{e}/{f}/{g}/{h}/{i}/{j}/{k}/{l}/{m}/{n}/{o}/{p}/{q}")] async fn five() -> &'static str { "malformed resource def" } fn main() {} actix-web-codegen-4.3.0/tests/trybuild/route-malformed-path-fail.stderr000064400000000000000000000021551046102023000243120ustar 00000000000000error: custom attribute panicked --> $DIR/route-malformed-path-fail.rs:3:1 | 3 | #[get("/{")] | ^^^^^^^^^^^^ | = help: message: pattern "{" contains malformed dynamic segment error: custom attribute panicked --> $DIR/route-malformed-path-fail.rs:8:1 | 8 | #[get("/{foo")] | ^^^^^^^^^^^^^^^ | = help: message: pattern "{foo" contains malformed dynamic segment error: custom attribute panicked --> $DIR/route-malformed-path-fail.rs:13:1 | 13 | #[get("/{}")] | ^^^^^^^^^^^^^ | = help: message: Wrong path pattern: "/{}" empty capture group names are not allowed error: custom attribute panicked --> $DIR/route-malformed-path-fail.rs:23:1 | 23 | #[get("/{tail:\\d+}*")] | ^^^^^^^^^^^^^^^^^^^^^^^ | = help: message: custom regex is not supported for tail match error: custom attribute panicked --> $DIR/route-malformed-path-fail.rs:28:1 | 28 | #[get("/{a}/{b}/{c}/{d}/{e}/{f}/{g}/{h}/{i}/{j}/{k}/{l}/{m}/{n}/{o}/{p}/{q}")] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | = help: message: Only 16 dynamic segments are allowed, provided: 17 actix-web-codegen-4.3.0/tests/trybuild/route-missing-method-fail.rs000064400000000000000000000005521046102023000234610ustar 00000000000000use actix_web_codegen::*; #[route("/")] async fn index() -> String { "Hello World!".to_owned() } #[actix_web::main] async fn main() { use actix_web::App; let srv = actix_test::start(|| App::new().service(index)); let request = srv.get("/"); let response = request.send().await.unwrap(); assert!(response.status().is_success()); } actix-web-codegen-4.3.0/tests/trybuild/route-missing-method-fail.stderr000064400000000000000000000030051046102023000243340ustar 00000000000000error: The #[route(..)] macro requires at least one `method` attribute --> tests/trybuild/route-missing-method-fail.rs:3:1 | 3 | #[route("/")] | ^^^^^^^^^^^^^ | = note: this error originates in the attribute macro `route` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0277]: the trait bound `fn() -> impl std::future::Future {index}: HttpServiceFactory` is not satisfied --> tests/trybuild/route-missing-method-fail.rs:12:55 | 12 | let srv = actix_test::start(|| App::new().service(index)); | ------- ^^^^^ the trait `HttpServiceFactory` is not implemented for fn item `fn() -> impl std::future::Future {index}` | | | required by a bound introduced by this call | = help: the following other types implement trait `HttpServiceFactory`: Resource actix_web::Scope Vec Redirect (A,) (A, B) (A, B, C) (A, B, C, D) and $N others note: required by a bound in `App::::service` --> $WORKSPACE/actix-web/src/app.rs | | pub fn service(mut self, factory: F) -> Self | ------- required by a bound in this associated function | where | F: HttpServiceFactory + 'static, | ^^^^^^^^^^^^^^^^^^ required by this bound in `App::::service` actix-web-codegen-4.3.0/tests/trybuild/route-ok.rs000064400000000000000000000006031046102023000202270ustar 00000000000000use actix_web_codegen::*; #[route("/", method="GET", method="HEAD")] async fn index() -> String { "Hello World!".to_owned() } #[actix_web::main] async fn main() { use actix_web::App; let srv = actix_test::start(|| App::new().service(index)); let request = srv.get("/"); let response = request.send().await.unwrap(); assert!(response.status().is_success()); } actix-web-codegen-4.3.0/tests/trybuild/routes-missing-args-fail.rs000064400000000000000000000003511046102023000233150ustar 00000000000000use actix_web_codegen::*; #[routes] #[get] async fn index() -> String { "Hello World!".to_owned() } #[actix_web::main] async fn main() { use actix_web::App; let srv = actix_test::start(|| App::new().service(index)); } actix-web-codegen-4.3.0/tests/trybuild/routes-missing-args-fail.stderr000064400000000000000000000036031046102023000241770ustar 00000000000000error: unexpected end of input, expected string literal --> tests/trybuild/routes-missing-args-fail.rs:4:1 | 4 | #[get] | ^^^^^^ | = note: this error originates in the attribute macro `get` (in Nightly builds, run with -Z macro-backtrace for more info) error: invalid service definition, expected #[("")] --> tests/trybuild/routes-missing-args-fail.rs:4:1 | 4 | #[get] | ^^^^^^ | = note: this error originates in the attribute macro `get` (in Nightly builds, run with -Z macro-backtrace for more info) error: expected attribute arguments in parentheses: #[get(...)] --> tests/trybuild/routes-missing-args-fail.rs:4:3 | 4 | #[get] | ^^^ error[E0277]: the trait bound `fn() -> impl std::future::Future {index}: HttpServiceFactory` is not satisfied --> tests/trybuild/routes-missing-args-fail.rs:13:55 | 13 | let srv = actix_test::start(|| App::new().service(index)); | ------- ^^^^^ the trait `HttpServiceFactory` is not implemented for fn item `fn() -> impl std::future::Future {index}` | | | required by a bound introduced by this call | = help: the following other types implement trait `HttpServiceFactory`: Resource actix_web::Scope Vec Redirect (A,) (A, B) (A, B, C) (A, B, C, D) and $N others note: required by a bound in `App::::service` --> $WORKSPACE/actix-web/src/app.rs | | pub fn service(mut self, factory: F) -> Self | ------- required by a bound in this associated function | where | F: HttpServiceFactory + 'static, | ^^^^^^^^^^^^^^^^^^ required by this bound in `App::::service` actix-web-codegen-4.3.0/tests/trybuild/routes-missing-method-fail.rs000064400000000000000000000003421046102023000236410ustar 00000000000000use actix_web_codegen::*; #[routes] async fn index() -> String { "Hello World!".to_owned() } #[actix_web::main] async fn main() { use actix_web::App; let srv = actix_test::start(|| App::new().service(index)); } actix-web-codegen-4.3.0/tests/trybuild/routes-missing-method-fail.stderr000064400000000000000000000030071046102023000245210ustar 00000000000000error: The #[routes] macro requires at least one `#[(..)]` attribute. --> tests/trybuild/routes-missing-method-fail.rs:3:1 | 3 | #[routes] | ^^^^^^^^^ | = note: this error originates in the attribute macro `routes` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0277]: the trait bound `fn() -> impl std::future::Future {index}: HttpServiceFactory` is not satisfied --> tests/trybuild/routes-missing-method-fail.rs:12:55 | 12 | let srv = actix_test::start(|| App::new().service(index)); | ------- ^^^^^ the trait `HttpServiceFactory` is not implemented for fn item `fn() -> impl std::future::Future {index}` | | | required by a bound introduced by this call | = help: the following other types implement trait `HttpServiceFactory`: Resource actix_web::Scope Vec Redirect (A,) (A, B) (A, B, C) (A, B, C, D) and $N others note: required by a bound in `App::::service` --> $WORKSPACE/actix-web/src/app.rs | | pub fn service(mut self, factory: F) -> Self | ------- required by a bound in this associated function | where | F: HttpServiceFactory + 'static, | ^^^^^^^^^^^^^^^^^^ required by this bound in `App::::service` actix-web-codegen-4.3.0/tests/trybuild/routes-ok.rs000064400000000000000000000007741046102023000204230ustar 00000000000000use actix_web_codegen::*; #[routes] #[get("/")] #[post("/")] async fn index() -> String { "Hello World!".to_owned() } #[actix_web::main] async fn main() { use actix_web::App; let srv = actix_test::start(|| App::new().service(index)); let request = srv.get("/"); let response = request.send().await.unwrap(); assert!(response.status().is_success()); let request = srv.post("/"); let response = request.send().await.unwrap(); assert!(response.status().is_success()); } actix-web-codegen-4.3.0/tests/trybuild/scope-invalid-args.rs000064400000000000000000000002471046102023000221550ustar 00000000000000use actix_web_codegen::scope; const PATH: &str = "/api"; #[scope(PATH)] mod api_const {} #[scope(true)] mod api_bool {} #[scope(123)] mod api_num {} fn main() {} actix-web-codegen-4.3.0/tests/trybuild/scope-invalid-args.stderr000064400000000000000000000010111046102023000230220ustar 00000000000000error: argument to scope macro is not a string literal, expected: #[scope("/prefix")] --> tests/trybuild/scope-invalid-args.rs:5:9 | 5 | #[scope(PATH)] | ^^^^ error: argument to scope macro is not a string literal, expected: #[scope("/prefix")] --> tests/trybuild/scope-invalid-args.rs:8:9 | 8 | #[scope(true)] | ^^^^ error: argument to scope macro is not a string literal, expected: #[scope("/prefix")] --> tests/trybuild/scope-invalid-args.rs:11:9 | 11 | #[scope(123)] | ^^^ actix-web-codegen-4.3.0/tests/trybuild/scope-missing-args.rs000064400000000000000000000001011046102023000221650ustar 00000000000000use actix_web_codegen::scope; #[scope] mod api {} fn main() {} actix-web-codegen-4.3.0/tests/trybuild/scope-missing-args.stderr000064400000000000000000000004261046102023000230560ustar 00000000000000error: missing arguments for scope macro, expected: #[scope("/prefix")] --> tests/trybuild/scope-missing-args.rs:3:1 | 3 | #[scope] | ^^^^^^^^ | = note: this error originates in the attribute macro `scope` (in Nightly builds, run with -Z macro-backtrace for more info) actix-web-codegen-4.3.0/tests/trybuild/scope-on-handler.rs000064400000000000000000000001661046102023000216240ustar 00000000000000use actix_web_codegen::scope; #[scope("/api")] async fn index() -> &'static str { "Hello World!" } fn main() {} actix-web-codegen-4.3.0/tests/trybuild/scope-on-handler.stderr000064400000000000000000000002241046102023000224760ustar 00000000000000error: #[scope] macro must be attached to a module --> tests/trybuild/scope-on-handler.rs:4:1 | 4 | async fn index() -> &'static str { | ^^^^^ actix-web-codegen-4.3.0/tests/trybuild/scope-trailing-slash.rs000064400000000000000000000001121046102023000225050ustar 00000000000000use actix_web_codegen::scope; #[scope("/api/")] mod api {} fn main() {} actix-web-codegen-4.3.0/tests/trybuild/scope-trailing-slash.stderr000064400000000000000000000003411046102023000233700ustar 00000000000000error: scopes should not have trailing slashes; see https://docs.rs/actix-web/4/actix_web/struct.Scope.html#avoid-trailing-slashes --> tests/trybuild/scope-trailing-slash.rs:3:9 | 3 | #[scope("/api/")] | ^^^^^^^ actix-web-codegen-4.3.0/tests/trybuild/simple-fail.rs000064400000000000000000000007631046102023000206730ustar 00000000000000use actix_web_codegen::*; #[get("/one", other)] async fn one() -> String { "Hello World!".to_owned() } #[post(/two)] async fn two() -> String { "Hello World!".to_owned() } static PATCH_PATH: &str = "/three"; #[patch(PATCH_PATH)] async fn three() -> String { "Hello World!".to_owned() } #[delete("/four", "/five")] async fn four() -> String { "Hello World!".to_owned() } #[delete("/five", method="GET")] async fn five() -> String { "Hello World!".to_owned() } fn main() {} actix-web-codegen-4.3.0/tests/trybuild/simple-fail.stderr000064400000000000000000000023051046102023000215440ustar 00000000000000error: expected `=` --> $DIR/simple-fail.rs:3:1 | 3 | #[get("/one", other)] | ^^^^^^^^^^^^^^^^^^^^^ | = note: this error originates in the attribute macro `get` (in Nightly builds, run with -Z macro-backtrace for more info) error: expected string literal --> $DIR/simple-fail.rs:8:8 | 8 | #[post(/two)] | ^ error: invalid service definition, expected #[("")] --> $DIR/simple-fail.rs:8:8 | 8 | #[post(/two)] | ^ error: expected string literal --> $DIR/simple-fail.rs:15:9 | 15 | #[patch(PATCH_PATH)] | ^^^^^^^^^^ error: invalid service definition, expected #[("")] --> $DIR/simple-fail.rs:15:9 | 15 | #[patch(PATCH_PATH)] | ^^^^^^^^^^ error: Multiple paths specified! There should be only one. --> $DIR/simple-fail.rs:20:1 | 20 | #[delete("/four", "/five")] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ | = note: this error originates in the attribute macro `delete` (in Nightly builds, run with -Z macro-backtrace for more info) error: HTTP method forbidden here; to handle multiple methods, use `route` instead --> $DIR/simple-fail.rs:25:19 | 25 | #[delete("/five", method="GET")] | ^^^^^^^^^^^^ actix-web-codegen-4.3.0/tests/trybuild/simple.rs000064400000000000000000000006111046102023000177520ustar 00000000000000use actix_web::{Responder, HttpResponse, App}; use actix_web_codegen::*; #[get("/config")] async fn config() -> impl Responder { HttpResponse::Ok() } #[actix_web::main] async fn main() { let srv = actix_test::start(|| App::new().service(config)); let request = srv.get("/config"); let response = request.send().await.unwrap(); assert!(response.status().is_success()); } actix-web-codegen-4.3.0/tests/trybuild/test-runtime.rs000064400000000000000000000001331046102023000211200ustar 00000000000000#[actix_web::test] async fn my_test() { assert!(async { 1 }.await, 1); } fn main() {} actix-web-codegen-4.3.0/tests/trybuild.rs000064400000000000000000000020701046102023000164620ustar 00000000000000#[rustversion::stable(1.72)] // MSRV #[test] fn compile_macros() { let t = trybuild::TestCases::new(); t.pass("tests/trybuild/simple.rs"); t.compile_fail("tests/trybuild/simple-fail.rs"); t.pass("tests/trybuild/route-ok.rs"); t.compile_fail("tests/trybuild/route-missing-method-fail.rs"); t.compile_fail("tests/trybuild/route-duplicate-method-fail.rs"); t.compile_fail("tests/trybuild/route-malformed-path-fail.rs"); t.pass("tests/trybuild/route-custom-method.rs"); t.compile_fail("tests/trybuild/route-custom-lowercase.rs"); t.pass("tests/trybuild/routes-ok.rs"); t.compile_fail("tests/trybuild/routes-missing-method-fail.rs"); t.compile_fail("tests/trybuild/routes-missing-args-fail.rs"); t.compile_fail("tests/trybuild/scope-on-handler.rs"); t.compile_fail("tests/trybuild/scope-missing-args.rs"); t.compile_fail("tests/trybuild/scope-invalid-args.rs"); t.compile_fail("tests/trybuild/scope-trailing-slash.rs"); t.pass("tests/trybuild/docstring-ok.rs"); t.pass("tests/trybuild/test-runtime.rs"); }