test-casing-macro-0.1.3/.cargo_vcs_info.json0000644000000001430000000000100143530ustar { "git": { "sha1": "9c6ba1fff5de67800e1191a0b3e581ae1eac03ac" }, "path_in_vcs": "macro" }test-casing-macro-0.1.3/CHANGELOG.md000064400000000000000000000014340072674642500150100ustar 00000000000000# Changelog All notable changes to this project will be documented in this file. The project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html). ## [Unreleased] ## 0.1.3 - 2024-03-03 ### Fixed - Fix `clippy::no_effect_underscore_binding` lint triggered by the generated code in Rust 1.76+. ## 0.1.2 - 2023-11-02 ### Fixed - Fix `unused_must_use` lint triggered for async functions without the explicit return value after the previous fix. - Pin a version of the macro dependency in the main library so that it does not break in the future releases. ## 0.1.1 - 2023-10-08 ### Fixed - Fix `ignored_unit_patterns` Clippy lint triggered by the generated code in Rust 1.73+. ## 0.1.0 - 2023-06-03 The initial release of `test-casing`. test-casing-macro-0.1.3/Cargo.toml0000644000000024210000000000100123520ustar # 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.65" name = "test-casing-macro" version = "0.1.3" authors = ["Alex Ostrovski "] description = "Procedural macro for `test-casing`" readme = "README.md" keywords = [ "testing", "parameterized", "case", "decorator", ] categories = ["development-tools::testing"] license = "MIT OR Apache-2.0" repository = "https://github.com/slowli/test-casing" [lib] proc-macro = true [dependencies.proc-macro2] version = "1.0" [dependencies.quote] version = "1.0" [dependencies.syn] version = "2.0" features = ["full"] [dev-dependencies.assert_matches] version = "1.5.0" [dev-dependencies.syn] version = "2.0" features = ["extra-traits"] [dev-dependencies.version-sync] version = "0.9.4" [features] default = [] nightly = ["proc-macro2/span-locations"] test-casing-macro-0.1.3/Cargo.toml.orig000064400000000000000000000015650072674642500160730ustar 00000000000000[package] name = "test-casing-macro" version.workspace = true edition.workspace = true rust-version.workspace = true authors.workspace = true license.workspace = true repository.workspace = true readme = "README.md" keywords = ["testing", "parameterized", "case", "decorator"] categories = ["development-tools::testing"] description = "Procedural macro for `test-casing`" [lib] proc-macro = true [dependencies] proc-macro2.workspace = true quote.workspace = true syn = { workspace = true, features = ["full"] } [dev-dependencies] assert_matches.workspace = true syn = { workspace = true, features = ["extra-traits"] } version-sync.workspace = true [features] default = [] # Uses custom test frameworks APIs together with a generous spicing of hacks # to include arguments in the names of the generated tests. nightly = ["proc-macro2/span-locations"] test-casing-macro-0.1.3/LICENSE-APACHE000064400000000000000000000254460072674642500151340ustar 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 [yyyy] [name of copyright owner] 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.test-casing-macro-0.1.3/LICENSE-MIT000064400000000000000000000021120072674642500146250ustar 00000000000000Copyright 2022-current Developers of test-casing 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. test-casing-macro-0.1.3/README.md000064400000000000000000000030270072674642500144560ustar 00000000000000# Proc Macro for `test-casing` [![Build Status](https://github.com/slowli/test-casing/workflows/CI/badge.svg?branch=main)](https://github.com/slowli/test-casing/actions) [![License: MIT OR Apache-2.0](https://img.shields.io/badge/License-MIT%2FApache--2.0-blue)](https://github.com/slowli/test-casing#license) ![rust 1.65+ required](https://img.shields.io/badge/rust-1.65+-blue.svg?label=Required%20Rust) **Documentation:** [![Docs.rs](https://docs.rs/test-casing-macro/badge.svg)](https://docs.rs/test-casing-macro/) [![crate docs (main)](https://img.shields.io/badge/main-yellow.svg?label=docs)](https://slowli.github.io/test-casing/test_casing_macro/) `#[test_casing]` and `#[decorate]` procedural macros to place on test functions. Used as a part of the [`test-casing`] library. ## Usage Add this to your `Crate.toml`: ```toml [dev-dependencies] test-casing-macro = "0.1.3" ``` Note that the `test-casing` crate re-exports the proc macros from this crate. Thus, it is rarely necessary to use this crate as a direct dependency. See `test-casing` docs for more details and examples of usage. ## License Licensed under either of [Apache License, Version 2.0](LICENSE-APACHE) or [MIT license](LICENSE-MIT) at your option. Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in `test-casing` by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions. [`test-casing`]: https://crates.io/crates/test-casing test-casing-macro-0.1.3/src/decorate.rs000064400000000000000000000054360072674642500161300ustar 00000000000000//! `decorate` proc macro implementation. use proc_macro::TokenStream; use quote::quote; use syn::{ parse::{Parse, ParseStream}, punctuated::Punctuated, spanned::Spanned, Error as SynError, Expr, Item, ItemFn, ReturnType, Token, }; use std::fmt; struct DecorateAttrs { decorators: Vec, } impl fmt::Debug for DecorateAttrs { fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter .debug_struct("DecorateAttrs") .field("decorators_len", &self.decorators.len()) .finish() } } impl Parse for DecorateAttrs { fn parse(input: ParseStream<'_>) -> syn::Result { let decorators = Punctuated::::parse_terminated(input)?; Ok(Self { decorators: decorators.into_iter().collect(), }) } } impl DecorateAttrs { fn decorate(&self, function: &ItemFn) -> syn::Result { let ItemFn { attrs, vis, sig, block, } = function; if let Some(asyncness) = &sig.asyncness { let message = "Cannot decorate an async function. Make sure that #[decorate] \ is applied *after* an attribute for the async test, such as #[tokio::test]"; return Err(SynError::new(asyncness.span(), message)); } if !sig.inputs.is_empty() { let message = "Cannot decorate a function with attributes"; return Err(SynError::new_spanned(&sig.inputs, message)); } let cr = quote!(test_casing::decorators); let decorators = &self.decorators; let ret_value = &sig.output; let ret_value_or_void = match &sig.output { ReturnType::Default => quote!(()), ReturnType::Type(_, ty) => quote!(#ty), }; let maybe_semicolon = if matches!(ret_value, ReturnType::Default) { Some(quote!(;)) } else { None }; Ok(quote! { #(#attrs)* #vis #sig { static __DECORATORS: &dyn #cr::DecorateTestFn<#ret_value_or_void> = &(#(#decorators,)*); let __test_fn = || #ret_value #block; #cr::DecorateTestFn::decorate_and_test_fn(__DECORATORS, __test_fn) #maybe_semicolon } }) } } pub(crate) fn impl_decorate( attr: TokenStream, item: TokenStream, ) -> syn::Result { let attrs: DecorateAttrs = syn::parse(attr)?; let item: Item = syn::parse(item)?; match item { Item::Fn(function) => attrs.decorate(&function), item => { let message = "Item is not supported; use `#[decorate] on functions"; Err(SynError::new_spanned(&item, message)) } } } test-casing-macro-0.1.3/src/lib.rs000064400000000000000000000024170072674642500151040ustar 00000000000000//! Procedural macros for the [`test-casing`] crate. //! //! - The `test_casing` macro from this crate flattens parameterized tests into a set of test cases. //! - The `decorate` macro wraps a tested function to add retries, timeouts etc. //! //! See the [`test-casing`] crate docs for macro documentation and examples of usage. //! //! [`test-casing`]: https://docs.rs/test-casing/ // Documentation settings #![doc(html_root_url = "https://docs.rs/test-casing-macro/0.1.3")] // Linter settings #![warn(missing_debug_implementations, bare_trait_objects)] #![warn(clippy::all, clippy::pedantic)] #![allow(clippy::must_use_candidate, clippy::module_name_repetitions)] extern crate proc_macro; use proc_macro::TokenStream; mod decorate; mod test_casing; use crate::{decorate::impl_decorate, test_casing::impl_test_casing}; #[proc_macro_attribute] pub fn test_casing(attr: TokenStream, item: TokenStream) -> TokenStream { match impl_test_casing(attr, item) { Ok(tokens) => tokens.into(), Err(err) => err.into_compile_error().into(), } } #[proc_macro_attribute] pub fn decorate(attr: TokenStream, item: TokenStream) -> TokenStream { match impl_decorate(attr, item) { Ok(tokens) => tokens.into(), Err(err) => err.into_compile_error().into(), } } test-casing-macro-0.1.3/src/test_casing/mod.rs000064400000000000000000000355630072674642500174300ustar 00000000000000//! `test_casing` proc macro implementation. use proc_macro::TokenStream; use quote::{quote, ToTokens}; use syn::{ ext::IdentExt, parse::{Error as SynError, Parse, ParseStream}, spanned::Spanned, Attribute, Expr, FnArg, Ident, Item, ItemFn, LitInt, Pat, PatType, Path, ReturnType, Signature, Token, }; use std::{fmt, mem}; #[cfg(feature = "nightly")] mod nightly; #[cfg(test)] mod tests; #[cfg(feature = "nightly")] use self::nightly::NightlyData; struct CaseAttrs { count: usize, expr: Expr, } impl fmt::Debug for CaseAttrs { fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter .debug_struct("CaseAttrs") .field("count", &self.count) .finish_non_exhaustive() } } impl CaseAttrs { fn parse(attr: proc_macro2::TokenStream) -> syn::Result { struct CaseAttrsSyntax { count: LitInt, _comma: Token![,], expr: Expr, } impl Parse for CaseAttrsSyntax { fn parse(input: ParseStream) -> syn::Result { Ok(Self { count: input.parse()?, _comma: input.parse()?, expr: input.parse()?, }) } } let syntax: CaseAttrsSyntax = syn::parse2(attr)?; let count: usize = syntax.count.base10_parse()?; if count == 0 { let message = "number of test cases must be positive"; return Err(SynError::new(syntax.count.span(), message)); } Ok(Self { count, expr: syntax.expr, }) } } struct MapAttrs { path: Option, } impl fmt::Debug for MapAttrs { fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter .debug_struct("MapAttrs") .field("path", &self.path.as_ref().map(|_| "_")) .finish() } } impl MapAttrs { fn map_arg(&self, arg: &Ident) -> proc_macro2::TokenStream { if let Some(path) = &self.path { quote!(#path(&#arg)) } else { quote!(&#arg) } } } impl Parse for MapAttrs { fn parse(input: ParseStream<'_>) -> syn::Result { struct MapAttrsSyntax { base: Ident, path_expr: Option<(Token![=], Path)>, } impl Parse for MapAttrsSyntax { fn parse(input: ParseStream<'_>) -> syn::Result { Ok(Self { base: input.call(Ident::parse_any)?, path_expr: if input.peek(Token![=]) { Some((input.parse()?, input.parse()?)) } else { None }, }) } } let syntax = MapAttrsSyntax::parse(input)?; if syntax.base != "ref" { let message = "unknown map transform; only `ref` is supported"; return Err(SynError::new(syntax.base.span(), message)); } Ok(Self { path: syntax.path_expr.map(|(_, path)| path), }) } } struct FunctionWrapper { #[cfg(feature = "nightly")] nightly: NightlyData, name: Ident, attrs: CaseAttrs, fn_attrs: Vec, fn_sig: Signature, arg_mappings: Vec>, } impl fmt::Debug for FunctionWrapper { fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter .debug_struct("FunctionWrapper") .field("attrs", &self.attrs) .field("name", &self.name) .field("fn_attrs_len", &self.fn_attrs.len()) .finish_non_exhaustive() } } impl FunctionWrapper { const MAX_ARGS: usize = 7; fn new(attrs: CaseAttrs, function: &mut ItemFn) -> syn::Result { if function.sig.inputs.is_empty() { let message = "tested function must have at least one arg"; return Err(SynError::new_spanned(&function.sig, message)); } else if function.sig.inputs.len() > Self::MAX_ARGS { let message = format!( "tested function must have no more than {} args", Self::MAX_ARGS ); return Err(SynError::new_spanned(&function.sig, message)); } let generic_params = &function.sig.generics.params; if !generic_params.is_empty() { let message = "generic tested functions are not supported"; return Err(SynError::new_spanned(generic_params, message)); } let mappings = function.sig.inputs.iter_mut().map(|arg| { let attrs = match arg { FnArg::Receiver(receiver) => &mut receiver.attrs, FnArg::Typed(typed) => &mut typed.attrs, }; let map_attr = attrs .iter() .enumerate() .find(|(_, attr)| attr.path().is_ident("map")); let Some((idx, map_attr)) = map_attr else { return Ok(None); }; let map_attr = map_attr.parse_args::()?; attrs.remove(idx); Ok(Some(map_attr)) }); let mappings: syn::Result> = mappings.collect(); let mappings = mappings?; let (retained_attrs, mut fn_attrs) = mem::take(&mut function.attrs) .into_iter() .partition(Self::should_be_retained); function.attrs = retained_attrs; let test_attr_position = fn_attrs .iter() .position(|attr| attr.path().is_ident("test")); if cfg!(feature = "nightly") { if let Some(position) = test_attr_position { fn_attrs.remove(position); } } else if test_attr_position.is_none() && function.sig.asyncness.is_none() { let test_attr = syn::parse_quote!(#[::core::prelude::v1::test]); fn_attrs.insert(0, test_attr); } Ok(Self { #[cfg(feature = "nightly")] nightly: NightlyData::from_attrs(&mut fn_attrs)?, name: function.sig.ident.clone(), attrs, fn_attrs, fn_sig: function.sig.clone(), arg_mappings: mappings, }) } // FIXME: this is extremely hacky. Ideally, we'd want to partition attrs by their location // before / after `#[test_casing]`, but this seems impossible on stable Rust (span locations // are unstable). fn should_be_retained(attr: &Attribute) -> bool { attr.path().is_ident("allow") || attr.path().is_ident("warn") || attr.path().is_ident("deny") || attr.path().is_ident("forbid") } fn arg_names(&self) -> impl ToTokens { let arg_count = self.fn_sig.inputs.len(); let arg_names = self .fn_sig .inputs .iter() .enumerate() .map(|(i, arg)| match arg { FnArg::Receiver(_) => String::from("self"), FnArg::Typed(PatType { pat, .. }) => { if let Pat::Ident(ident) = pat.as_ref() { ident.ident.to_string() } else { format!("(arg {i})") } } }); quote! { const __ARG_NAMES: [&'static str; #arg_count] = [#(#arg_names,)*]; } } fn test_cases_iter(&self) -> impl ToTokens { let cr = quote!(test_casing); let name = &self.name; let cases_expr = &self.attrs.expr; let (case_binding, case_args) = self.case_binding(); let maybe_output_binding = match (&self.fn_sig.asyncness, &self.fn_sig.output) { (None, ReturnType::Default) => None, _ => Some(quote!(let _ = )), }; // ^ Using `let _ = ` on the `()` return type triggers https://rust-lang.github.io/rust-clippy/master/index.html#/ignored_unit_patterns // in Rust 1.73+. quote! { const _: () = { #[allow(dead_code, clippy::no_effect_underscore_binding)] fn __test_cases_iterator() { let #case_binding = #cr::case(#cases_expr, 0); #maybe_output_binding #name(#case_args); } }; } } fn wrap(&self) -> impl ToTokens { let name = &self.name; let test_cases_iter = self.test_cases_iter(); let arg_names = self.arg_names(); let index_width = (self.attrs.count - 1).to_string().len(); let cases = (0..self.attrs.count).map(|i| self.case(i, index_width)); quote! { // Access the iterator to ensure it works even if not building for tests. #test_cases_iter #[cfg(test)] #[allow(clippy::no_effect_underscore_binding)] // ^ We use `__ident`s to not alias user-defined idents accidentally. Unfortunately, // this triggers this lint on Rust 1.76+. mod #name { use super::*; #arg_names #(#cases)* } } } #[cfg(feature = "nightly")] fn declare_test_case(&self, index: usize, test_fn_name: &Ident) -> impl ToTokens { let cr = quote!(test_casing); let cases_expr = &self.attrs.expr; let test_case_name = format!("__TEST_CASE_{index}"); let test_case_name = Ident::new(&test_case_name, self.name.span()); let additional_args = self.nightly.macro_args(); let span_start = self.name.span().start(); let start_line = span_start.line; let start_col = span_start.column; let span_end = self.name.span().end(); let end_line = span_end.line; let end_col = span_end.column; quote! { #[::core::prelude::v1::test_case] static #test_case_name: #cr::nightly::LazyTestCase = #cr::declare_test_case!( base_name: ::core::module_path!(), source_file: ::core::file!(), start_line: #start_line, start_col: #start_col, end_line: #end_line, end_col: #end_col, arg_names: __ARG_NAMES, cases: #cases_expr, index: #index, #additional_args testfn: #test_fn_name ); } } fn case(&self, index: usize, index_width: usize) -> impl ToTokens { let case_name = format!("case_{index:0>index_width$}"); let case_name = Ident::new(&case_name, self.name.span()); #[cfg(feature = "nightly")] { let case_fn = self.case_fn(index, &case_name); let test_fn_name = format!("__TEST_FN_{index}"); let test_fn_name = Ident::new(&test_fn_name, self.name.span()); let ret = &self.fn_sig.output; let case_decl = self.declare_test_case(index, &test_fn_name); quote! { #[allow(unnameable_test_items)] // ^ This is a very roundabout way to effectively drop the `#[test]` attribute // from the generated code. It should work for all kinds of test macros, // such as `async_std::test` or `tokio::test`, without any additional work. const #test_fn_name: fn() #ret = { #case_fn #case_name }; #case_decl } } #[cfg(not(feature = "nightly"))] self.case_fn(index, &case_name) } fn case_fn(&self, index: usize, case_name: &Ident) -> proc_macro2::TokenStream { let cr = quote!(test_casing); let name = &self.name; let attrs = &self.fn_attrs; let maybe_async = &self.fn_sig.asyncness; let maybe_await = maybe_async.as_ref().map(|_| quote!(.await)); let ret = &self.fn_sig.output; let maybe_semicolon = match ret { ReturnType::Default => Some(quote!(;)), ReturnType::Type { .. } => None, }; let cases_expr = &self.attrs.expr; let (case_binding, case_args) = self.case_binding(); let case_assignment = if cfg!(feature = "nightly") { quote! { let #case_binding = #cr::case(#cases_expr, #index); } } else { quote! { let __case = #cr::case(#cases_expr, #index); println!( "Testing case #{}: {}", #index, #cr::ArgNames::print_with_args(__ARG_NAMES, &__case) ); let #case_binding = __case; } }; quote! { #(#attrs)* #maybe_async fn #case_name() #ret { #case_assignment #name(#case_args) #maybe_await #maybe_semicolon } } } /// Returns the binding of args supplied to the test case and potentially mapped args /// to provide to the test function. fn case_binding(&self) -> (impl ToTokens, impl ToTokens) { if self.fn_sig.inputs.len() == 1 { let arg = self.fn_sig.inputs.first().unwrap(); let arg = Ident::new("__case_arg", arg.span()); let mapped_arg = self.arg_mappings[0] .as_ref() .map_or_else(|| quote!(#arg), |mapping| mapping.map_arg(&arg)); (quote!(#arg), mapped_arg) } else { let args = self.fn_sig.inputs.iter().enumerate(); let args = args.map(|(idx, arg)| Ident::new(&format!("__case_arg{idx}"), arg.span())); let binding_args = args.clone(); let case_binding = quote!((#(#binding_args,)*)); let args = args.zip(&self.arg_mappings).map(|(arg, mapping)| { mapping .as_ref() .map_or_else(|| quote!(#arg), |mapping| mapping.map_arg(&arg)) }); let case_args = quote!(#(#args,)*); (case_binding, case_args) } } } pub(crate) fn impl_test_casing( attr: TokenStream, item: TokenStream, ) -> syn::Result { let attrs = CaseAttrs::parse(attr.into())?; let item: Item = syn::parse(item)?; match item { Item::Fn(mut function) => { let wrapper = FunctionWrapper::new(attrs, &mut function)?; let wrapper = wrapper.wrap(); Ok(quote!(#function #wrapper)) } item => { let message = "Item is not supported; use `#[test_cases] on functions"; Err(SynError::new_spanned(&item, message)) } } } test-casing-macro-0.1.3/src/test_casing/nightly.rs000064400000000000000000000117500072674642500203170ustar 00000000000000//! Nightly-specific types and functionality. use quote::{quote, ToTokens}; use syn::{parse::Error as SynError, Attribute, Expr, ExprLit, Lit, Meta, MetaList, MetaNameValue}; use std::fmt; pub(crate) enum AttrValue { Empty, Str(syn::LitStr), } impl fmt::Debug for AttrValue { fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::Empty => formatter.debug_tuple("Empty").finish(), Self::Str(s) => formatter.debug_tuple("Str").field(&s.value()).finish(), } } } impl AttrValue { fn new(attr: &Attribute, expected_field: Option<&str>) -> syn::Result { match &attr.meta { Meta::Path(_) => Ok(Self::Empty), Meta::NameValue(MetaNameValue { value, .. }) => { if let Expr::Lit(ExprLit { lit: Lit::Str(str), .. }) = value { Ok(Self::Str(str.clone())) } else { let message = "unrecognized attribute value; should be a string literal"; Err(SynError::new_spanned(attr, message)) } } Meta::List(list) => { if let Some(expected_field) = expected_field { Self::from_list(list, expected_field) } else { let name = attr.meta.path().get_ident().unwrap(); let message = format!( "unrecognized attribute shape; should have `#[{name}] or \ `#[{name} = \"value\"]` form" ); Err(SynError::new_spanned(attr, message)) } } } } fn from_list(list: &MetaList, expected_field: &str) -> syn::Result { let mut len = 0; let mut value = None; list.parse_nested_meta(|nested| { len += 1; if !nested.path.is_ident(expected_field) { let message = format!("attribute should have a single field `{expected_field} = \"value\"`"); return Err(nested.error(message)); } value = Some(nested.value()?.parse::()?); Ok(()) })?; if len != 1 { let message = format!("attribute should have a single field `{expected_field} = \"value\"`"); return Err(SynError::new_spanned(list, message)); } let value = value.unwrap(); Ok(Self::Str(value)) } } #[derive(Debug)] pub(crate) struct NightlyData { pub ignore: Option, pub should_panic: Option, } impl NightlyData { pub fn from_attrs(attrs: &mut Vec) -> syn::Result { let mut ignore = None; let mut should_panic = None; let mut indices_to_remove = vec![]; for (i, attr) in attrs.iter().enumerate() { if attr.path().is_ident("ignore") { ignore = Some(AttrValue::new(attr, None)?); indices_to_remove.push(i); } else if attr.path().is_ident("should_panic") { should_panic = Some(AttrValue::new(attr, Some("expected"))?); indices_to_remove.push(i); } } for i in indices_to_remove.into_iter().rev() { attrs.remove(i); } Ok(Self { ignore, should_panic, }) } pub fn macro_args(&self) -> impl ToTokens { let option = quote!(::core::option::Option); let ignore = self.ignore.as_ref().map(|ignore| match ignore { AttrValue::Empty => quote!(ignore: #option::None,), AttrValue::Str(s) => quote!(ignore: #option::Some(#s),), }); let should_panic = self.should_panic.as_ref().map(|panic| match panic { AttrValue::Empty => quote!(panic_message: #option::None,), AttrValue::Str(s) => quote!(panic_message: #option::Some(#s),), }); quote! { #ignore #should_panic } } } #[cfg(test)] mod tests { use assert_matches::assert_matches; use super::*; #[test] fn extracting_attr_value() { let attr: Attribute = syn::parse_quote!(#[ignore]); let value = AttrValue::new(&attr, None).unwrap(); assert_matches!(value, AttrValue::Empty); let attr: Attribute = syn::parse_quote!(#[ignore = "TODO"]); let value = AttrValue::new(&attr, None).unwrap(); assert_matches!(value, AttrValue::Str(s) if s.value() == "TODO"); let attr: Attribute = syn::parse_quote!(#[should_panic = "not available"]); let value = AttrValue::new(&attr, Some("expected")).unwrap(); assert_matches!(value, AttrValue::Str(s) if s.value() == "not available"); let attr: Attribute = syn::parse_quote!(#[should_panic(expected = "not available")]); let value = AttrValue::new(&attr, Some("expected")).unwrap(); assert_matches!(value, AttrValue::Str(s) if s.value() == "not available"); } } test-casing-macro-0.1.3/src/test_casing/tests.rs000064400000000000000000000122670072674642500200070ustar 00000000000000//! Unit tests for the `test_casing` macro. use assert_matches::assert_matches; #[cfg(feature = "nightly")] use super::nightly::AttrValue; use super::*; #[test] fn parsing_case_attrs() { let attr = quote!(3, ["test", "this", "str"]); let attrs = CaseAttrs::parse(attr).unwrap(); assert_eq!(attrs.count, 3); assert_eq!(attrs.expr, syn::parse_quote!(["test", "this", "str"])); } #[test] fn parsing_map_attrs() { let attr: Attribute = syn::parse_quote!(#[map(ref)]); let attr = attr.parse_args::().unwrap(); assert!(attr.path.is_none()); let attr: Attribute = syn::parse_quote!(#[map(ref = String::as_str)]); let attr = attr.parse_args::().unwrap(); let expected: Path = syn::parse_quote!(String::as_str); assert_eq!(attr.path.unwrap(), expected); } #[test] fn processing_map_attr_without_path() { let attr = MapAttrs { path: None }; let ident: Ident = syn::parse_quote!(test); let mapped = attr.map_arg(&ident); let mapped: Expr = syn::parse_quote!(#mapped); let expected: Expr = syn::parse_quote!(&test); assert_eq!(mapped, expected); } #[test] fn processing_map_attr_with_path() { let attr = MapAttrs { path: Some(syn::parse_quote!(String::as_str)), }; let ident: Ident = syn::parse_quote!(test); let mapped = attr.map_arg(&ident); let mapped: Expr = syn::parse_quote!(#mapped); let expected: Expr = syn::parse_quote!(String::as_str(&test)); assert_eq!(mapped, expected); } #[test] fn initializing_fn_wrapper() { let attrs = CaseAttrs { count: 2, expr: syn::parse_quote!(CASES), }; let mut function: ItemFn = syn::parse_quote! { #[allow(unused)] #[should_panic = "oops"] fn tested_fn(number: u32, #[map(ref)] s: &str) {} }; let wrapper = FunctionWrapper::new(attrs, &mut function).unwrap(); assert_eq!(wrapper.name, "tested_fn"); assert_matches!( wrapper.arg_mappings.as_slice(), [None, Some(MapAttrs { path: None })] ); #[cfg(feature = "nightly")] { assert!(wrapper.fn_attrs.is_empty()); let nightly_data = wrapper.nightly; assert_matches!(nightly_data.should_panic.unwrap(), AttrValue::Str(_)); assert!(nightly_data.ignore.is_none()); } #[cfg(not(feature = "nightly"))] { assert_eq!(wrapper.fn_attrs.len(), 2); assert_eq!( wrapper.fn_attrs[0].path().segments.last().unwrap().ident, "test" ); assert!(wrapper.fn_attrs[1].path().is_ident("should_panic")); } let expected: ItemFn = syn::parse_quote! { #[allow(unused)] fn tested_fn(number: u32, s: &str) {} }; assert_eq!(function, expected, "{}", quote!(#function)); } fn create_wrapper() -> FunctionWrapper { let attrs = CaseAttrs { count: 2, expr: syn::parse_quote!(CASES), }; let mut function: ItemFn = syn::parse_quote! { fn tested_fn(number: u32, #[map(ref)] s: &str) {} }; FunctionWrapper::new(attrs, &mut function).unwrap() } #[test] fn computing_arg_names() { let wrapper = create_wrapper(); let arg_names = wrapper.arg_names(); let arg_names: Item = syn::parse_quote!(#arg_names); let expected: Item = syn::parse_quote! { const __ARG_NAMES: [&'static str; 2usize] = ["number", "s",]; }; assert_eq!(arg_names, expected, "{}", quote!(#arg_names)); } #[test] fn computing_case_bindings() { let wrapper = create_wrapper(); let (case_binding, case_args) = wrapper.case_binding(); let case_binding: Pat = syn::parse_quote!(#case_binding); let expected: Pat = syn::parse_quote!((__case_arg0, __case_arg1,)); assert_eq!(case_binding, expected, "{}", quote!(#case_binding)); let case_args: Expr = syn::parse_quote!((#case_args)); let expected: Expr = syn::parse_quote!((__case_arg0, &__case_arg1,)); assert_eq!(case_args, expected, "{}", quote!(#case_args)); } #[cfg(feature = "nightly")] #[test] fn generating_case() { let wrapper = create_wrapper(); let case_name: Ident = syn::parse_quote!(case0); let case_fn = wrapper.case_fn(0, &case_name); let case_fn: ItemFn = syn::parse_quote!(#case_fn); let expected: ItemFn = syn::parse_quote! { fn case0() { let (__case_arg0, __case_arg1,) = test_casing::case(CASES, 0usize); tested_fn(__case_arg0, &__case_arg1,); } }; assert_eq!(case_fn, expected, "{}", quote!(#case_fn)); } #[cfg(not(feature = "nightly"))] #[test] fn generating_case() { let wrapper = create_wrapper(); let case_name: Ident = syn::parse_quote!(case0); let case_fn = wrapper.case_fn(0, &case_name); let case_fn: ItemFn = syn::parse_quote!(#case_fn); let expected: ItemFn = syn::parse_quote! { #[::core::prelude::v1::test] fn case0() { let __case = test_casing::case(CASES, 0usize); println!( "Testing case #{}: {}", 0usize, test_casing::ArgNames::print_with_args(__ARG_NAMES, &__case) ); let (__case_arg0, __case_arg1,) = __case; tested_fn(__case_arg0, &__case_arg1,); } }; assert_eq!(case_fn, expected, "{}", quote!(#case_fn)); } test-casing-macro-0.1.3/tests/version_match.rs000064400000000000000000000004130072674642500175440ustar 00000000000000use version_sync::{assert_html_root_url_updated, assert_markdown_deps_updated}; #[test] fn readme_is_in_sync() { assert_markdown_deps_updated!("README.md"); } #[test] fn html_root_url_is_in_sync() { assert_html_root_url_updated!("src/lib.rs"); }