From: Woohyun Jung Date: Mon, 8 May 2023 06:21:43 +0000 (+0900) Subject: Import test-log 0.2.11 X-Git-Tag: upstream/0.2.11 X-Git-Url: http://review.tizen.org/git/?a=commitdiff_plain;h=refs%2Fheads%2Fupstream;p=platform%2Fupstream%2Frust-test-log.git Import test-log 0.2.11 --- 99d1d567eef29a854f0b185ed7025235fbe623a9 diff --git a/.cargo_vcs_info.json b/.cargo_vcs_info.json new file mode 100644 index 0000000..1d5b13d --- /dev/null +++ b/.cargo_vcs_info.json @@ -0,0 +1,6 @@ +{ + "git": { + "sha1": "f500323f947a4bfdcb015edbc814555ddb04a0fc" + }, + "path_in_vcs": "" +} \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..03406c0 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,88 @@ +0.2.11 +------ +- Fixed potential build failure due to unhygienic procedural macros +- Switched to using GitHub Actions as CI provider + + +0.2.10 +------ +- Fixed potential build failure when used from edition 2021 crates + + +0.2.9 +----- +- Added support for inner `#[test]` attribute arguments +- Added CI checks for auto generated code documentation +- Bumped minimum supported Rust version to `1.49` + + +0.2.8 +----- +- Renamed crate `test-log` + + +0.2.7 +----- +- Changed `tracing` behavior to capture output and only emit it on test + failure or when explicitly requested +- Bumped minimum `tracing-subscriber` version to 0.2.17 + + +0.2.6 +----- +- Introduced support for `RUST_LOG_SPAN_EVENTS` environment variable + that can be used to configure emitting of synthetic trace events +- Updated documentation to include wrapping of other attributes +- Bumped minimum supported Rust version to `1.45` + + +0.2.5 +----- +- Eliminated emitting of `-> ()` constructs in test function signatures + + +0.2.4 +----- +- Eliminated need for emitting of `::f` test function +- Excluded unnecessary files from being contained in release bundle + + +0.2.3 +----- +- Initialize `tracing` globally instead of individually for the run time + of each test +- Bumped minimum supported Rust version to `1.42` + + +0.2.2 +----- +- Added support for initializing `tracing` infrastructure + - Introduced `log` (enabled by default) and `trace` features (disabled + by default) +- Dropped `env_logger` dependency + + +0.2.1 +----- +- Relicensed project under terms of `Apache-2.0 OR MIT` + + +0.2.0 +----- +- Added support for providing inner `#[test]` attribute +- Bumped minimum required Rust version to `1.39.0` + + +0.1.1 +----- +- Updated `README.md` with instructions on how to retrieve test output + and change log level +- Bumped `env_logger` dependency to `0.7` +- Bumped `syn` dependency to `1.0` +- Bumped `quote` dependency to `1.0` +- Bumped `proc-macro` dependency to `1.0` + + +0.1.0 +----- +- Initial release diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..c4f890a --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,96 @@ +# 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 = "2018" +name = "test-log" +version = "0.2.11" +authors = ["Daniel Mueller "] +include = [ + "src/lib.rs", + "LICENSE-*", + "README.md", + "CHANGELOG.md", +] +description = """ +A replacement of the #[test] attribute that initializes logging and/or +tracing infrastructure before running tests. +""" +homepage = "https://github.com/d-e-s-o/test-log" +readme = "README.md" +keywords = [ + "env_logger", + "log", + "logging", + "testing", + "tracing", +] +categories = [ + "development-tools::testing", + "development-tools", + "config", + "api-bindings", +] +license = "Apache-2.0 OR MIT" +repository = "https://github.com/d-e-s-o/test-log.git" + +[lib] +proc-macro = true + +[dependencies.proc-macro2] +version = "1.0" + +[dependencies.quote] +version = "1.0" + +[dependencies.syn] +version = "1.0" +features = [ + "extra-traits", + "full", +] + +[dev-dependencies.env_logger] +version = "0.9" +default-features = false + +[dev-dependencies.logging] +version = "0.4" +package = "log" + +[dev-dependencies.tokio] +version = "1.0" +features = [ + "rt-multi-thread", + "macros", +] +default-features = false + +[dev-dependencies.tracing] +version = "0.1" + +[dev-dependencies.tracing-futures] +version = "0.2" +features = ["std-future"] +default-features = false + +[dev-dependencies.tracing-subscriber] +version = "0.3" +features = [ + "env-filter", + "fmt", +] +default-features = false + +[features] +default = ["log"] +log = [] +trace = [] diff --git a/Cargo.toml.orig b/Cargo.toml.orig new file mode 100644 index 0000000..33acf9b --- /dev/null +++ b/Cargo.toml.orig @@ -0,0 +1,48 @@ +[package] +name = "test-log" +version = "0.2.11" +authors = ["Daniel Mueller "] +edition = "2018" +license = "Apache-2.0 OR MIT" +homepage = "https://github.com/d-e-s-o/test-log" +repository = "https://github.com/d-e-s-o/test-log.git" +readme = "README.md" +categories = [ + "development-tools::testing", + "development-tools", + "config", + "api-bindings", +] +keywords = [ + "env_logger", + "log", + "logging", + "testing", + "tracing", +] +description = """ +A replacement of the #[test] attribute that initializes logging and/or +tracing infrastructure before running tests. +""" +include = ["src/lib.rs", "LICENSE-*", "README.md", "CHANGELOG.md"] + +[lib] +proc-macro = true + +[features] +default = ["log"] +trace = [] +log = [] + +[dependencies] +proc-macro2 = "1.0" +quote = {version = "1.0"} +syn = {version = "1.0", features = ["extra-traits", "full"]} + +[dev-dependencies] +env_logger = {version = "0.9", default-features = false} +logging = {version = "0.4", package = "log"} +tokio = {version = "1.0", default-features = false, features = ["rt-multi-thread", "macros"]} +tracing = {version = "0.1"} +tracing-futures = {version = "0.2", default-features = false, features = ["std-future"]} +tracing-subscriber = {version = "0.3", default-features = false, features = ["env-filter", "fmt"]} diff --git a/LICENSE-APACHE b/LICENSE-APACHE new file mode 100644 index 0000000..17d7468 --- /dev/null +++ b/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + https://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 + + https://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. diff --git a/LICENSE-MIT b/LICENSE-MIT new file mode 100644 index 0000000..dc57e10 --- /dev/null +++ b/LICENSE-MIT @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2020 Daniel Müller + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..4543658 --- /dev/null +++ b/README.md @@ -0,0 +1,133 @@ +[![pipeline](https://github.com/d-e-s-o/test-log/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/d-e-s-o/test-log/actions/workflows/ci.yml) +[![crates.io](https://img.shields.io/crates/v/test-log.svg)](https://crates.io/crates/test-log) +[![Docs](https://docs.rs/test-log/badge.svg)](https://docs.rs/test-log) +[![rustc](https://img.shields.io/badge/rustc-1.49+-blue.svg)](https://blog.rust-lang.org/2020/12/31/Rust-1.49.0.html) + +test-log +======== + +- [Documentation][docs-rs] +- [Changelog](CHANGELOG.md) + +**test-log** is a crate that takes care of automatically initializing +logging and/or tracing for Rust tests. + +When running Rust tests it can often be helpful to have easy access to +the verbose log messages emitted by the code under test. Commonly, these +log messages may be coming from the [`log`][log] crate or being emitted +through the [`tracing`][tracing] infrastructure. + +The problem with either -- in the context of testing -- is that some +form of initialization is required in order to make these crate's +messages appear on a standard output stream. + +The commonly used [`env_logger`](https://crates.io/crates/env_logger) +(which provides an easy way to configure `log` based logging), for +example, needs to be initialized like this: +```rust +let _ = env_logger::builder().is_test(true).try_init(); +``` +in **each and every** test. + +Similarly, `tracing` based solutions require a subscriber to be +registered that writes events/spans to the console. + +This crate takes care of this per-test initialization in an intuitive +way. + + +Usage +----- + +The crate provides a custom `#[test]` attribute that, when used for +running a particular test, takes care of initializing `log` and/or +`tracing` beforehand. + +#### Example + +As such, usage is as simple as importing and using said attribute: +```rust +use test_log::test; + +#[test] +fn it_works() { + info!("Checking whether it still works..."); + assert_eq!(2 + 2, 4); + info!("Looks good!"); +} +``` + +It is of course also possible to initialize logging for a chosen set of +tests, by only annotating these with the custom attribute: +```rust +#[test_log::test] +fn it_still_works() { + // ... +} +``` + +You can also wrap another attribute. For example, suppose you use +[`#[tokio::test]`][tokio-test] to run async tests: +```rust +use test_log::test; + +#[test(tokio::test)] +async fn it_still_works() { + // ... +} +``` + +#### Logging Configuration + +As usual when running `cargo test`, the output is captured by the +framework by default and only shown on test failure. The `--nocapture` +argument can be supplied in order to overwrite this setting. E.g., +```bash +$ cargo test -- --nocapture +``` + +Furthermore, the `RUST_LOG` environment variable is honored and can be +used to influence the log level to work with (among other things). +Please refer to the [`env_logger` docs][env-docs-rs] for more +information. + +If the `trace` feature is enabled, the `RUST_LOG_SPAN_EVENTS` +environment variable can be used to configure the tracing subscriber to +log synthesized events at points in the span lifecycle. Set the variable +to a comma-separated list of events you want to see. For example, +`RUST_LOG_SPAN_EVENTS=full` or `RUST_LOG_SPAN_EVENTS=new,close`. + +Valid events are `new`, `enter`, `exit`, `close`, `active`, and `full`. +See the [`tracing_subscriber` docs][tracing-events-docs-rs] for details +on what the events mean. + +#### Features + +The crate comes with two features: +- `log`, enabled by default, controls initialization for the `log` + crate. +- `trace`, disabled by default, controls initialization for the + `tracing` crate. + +Depending on what backend the crate-under-test (and its dependencies) +use, the respective feature should be enabled to make messages that are +emitted by the test manifest on the console. + +Note that as a user you are required to explicitly add `env_logger` or +`tracing-subscriber` as a dependency to your project-under-test (when +enabling the `log` or `trace` feature, respectively). E.g., + +```toml +[dev-dependencies] +env_logger = "*" +tracing = {version = "0.1", default-features = false} +tracing-subscriber = {version = "0.3", default-features = false, features = ["env-filter", "fmt"]} +``` + + +[docs-rs]: https://docs.rs/crate/test-log +[env-docs-rs]: https://docs.rs/env_logger/0.9.0/env_logger +[log]: https://crates.io/crates/log +[tokio-test]: https://docs.rs/tokio/1.4.0/tokio/attr.test.html +[tracing]: https://crates.io/crates/tracing +[tracing-events-docs-rs]: https://docs.rs/tracing-subscriber/0.3.1/tracing_subscriber/fmt/struct.SubscriberBuilder.html#method.with_span_events diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..6e4d6c8 --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,205 @@ +// Copyright (C) 2019-2022 Daniel Mueller +// SPDX-License-Identifier: (Apache-2.0 OR MIT) + +#![deny(broken_intra_doc_links, missing_docs)] + +//! A crate providing a replacement #[[macro@test]] attribute that +//! initializes logging and/or tracing infrastructure before running +//! tests. + +extern crate proc_macro; + +use proc_macro::TokenStream; +use proc_macro2::TokenStream as Tokens; + +use quote::quote; + +use syn::parse_macro_input; +use syn::parse_quote; +use syn::AttributeArgs; +use syn::ItemFn; +use syn::Meta; +use syn::NestedMeta; +use syn::ReturnType; + + +/// A procedural macro for the `test` attribute. +/// +/// The attribute can be used to define a test that has the `env_logger` +/// and/or `tracing` crates initialized (depending on the features used). +/// +/// # Example +/// +/// Specify the attribute on a per-test basis: +/// ```rust +/// # // doctests seemingly run in a slightly different environment where +/// # // `super`, which is what our macro makes use of, is not available. +/// # // By having a fake module here we work around that problem. +/// # #[cfg(feature = "log")] +/// # mod fordoctest { +/// # use logging::info; +/// # // Note that no test would actually run, regardless of `no_run`, +/// # // because we do not invoke the function. +/// #[test_log::test] +/// fn it_works() { +/// info!("Checking whether it still works..."); +/// assert_eq!(2 + 2, 4); +/// info!("Looks good!"); +/// } +/// # } +/// ``` +/// +/// It can be very convenient to convert over all tests by overriding +/// the `#[test]` attribute on a per-module basis: +/// ```rust,no_run +/// # mod fordoctest { +/// use test_log::test; +/// +/// #[test] +/// fn it_still_works() { +/// // ... +/// } +/// # } +/// ``` +/// +/// You can also wrap another attribute. For example, suppose you use +/// [`#[tokio::test]`](https://docs.rs/tokio/1.4.0/tokio/attr.test.html) +/// to run async tests: +/// ``` +/// # mod fordoctest { +/// use test_log::test; +/// +/// #[test(tokio::test)] +/// async fn it_still_works() { +/// // ... +/// } +/// # } +/// ``` +#[proc_macro_attribute] +pub fn test(attr: TokenStream, item: TokenStream) -> TokenStream { + let args = parse_macro_input!(attr as AttributeArgs); + let input = parse_macro_input!(item as ItemFn); + + let inner_test = match args.as_slice() { + [] => parse_quote! { ::core::prelude::v1::test }, + [NestedMeta::Meta(Meta::Path(path))] => quote! { #path }, + [NestedMeta::Meta(Meta::List(list))] => quote! { #list }, + _ => panic!("unsupported attributes supplied: {:?}", args), + }; + + expand_wrapper(&inner_test, &input) +} + + +/// Expand the initialization code for the `log` crate. +fn expand_logging_init() -> Tokens { + #[cfg(feature = "log")] + quote! { + { + let _ = ::env_logger::builder().is_test(true).try_init(); + } + } + #[cfg(not(feature = "log"))] + quote! {} +} + + +/// Expand the initialization code for the `tracing` crate. +fn expand_tracing_init() -> Tokens { + #[cfg(feature = "trace")] + quote! { + { + let __internal_event_filter = { + use ::tracing_subscriber::fmt::format::FmtSpan; + + match ::std::env::var("RUST_LOG_SPAN_EVENTS") { + Ok(value) => { + value + .to_ascii_lowercase() + .split(",") + .map(|filter| match filter.trim() { + "new" => FmtSpan::NEW, + "enter" => FmtSpan::ENTER, + "exit" => FmtSpan::EXIT, + "close" => FmtSpan::CLOSE, + "active" => FmtSpan::ACTIVE, + "full" => FmtSpan::FULL, + _ => panic!("test-log: RUST_LOG_SPAN_EVENTS must contain filters separated by `,`.\n\t\ + For example: `active` or `new,close`\n\t\ + Supported filters: new, enter, exit, close, active, full\n\t\ + Got: {}", value), + }) + .fold(FmtSpan::NONE, |acc, filter| filter | acc) + }, + Err(::std::env::VarError::NotUnicode(_)) => + panic!("test-log: RUST_LOG_SPAN_EVENTS must contain a valid UTF-8 string"), + Err(::std::env::VarError::NotPresent) => FmtSpan::NONE, + } + }; + + let subscriber = ::tracing_subscriber::FmtSubscriber::builder() + .with_env_filter(::tracing_subscriber::EnvFilter::from_default_env()) + .with_span_events(__internal_event_filter) + .with_test_writer() + .finish(); + let _ = ::tracing::subscriber::set_global_default(subscriber); + } + } + #[cfg(not(feature = "trace"))] + quote! {} +} + + +/// Emit code for a wrapper function around a test function. +fn expand_wrapper(inner_test: &Tokens, wrappee: &ItemFn) -> TokenStream { + let attrs = &wrappee.attrs; + let async_ = &wrappee.sig.asyncness; + let await_ = if async_.is_some() { + quote! {.await} + } else { + quote! {} + }; + let body = &wrappee.block; + let test_name = &wrappee.sig.ident; + + // Note that Rust does not allow us to have a test function with + // #[should_panic] that has a non-unit return value. + let ret = match &wrappee.sig.output { + ReturnType::Default => quote! {}, + ReturnType::Type(_, type_) => quote! {-> #type_}, + }; + + let logging_init = expand_logging_init(); + let tracing_init = expand_tracing_init(); + + let result = quote! { + #[#inner_test] + #(#attrs)* + #async_ fn #test_name() #ret { + #async_ fn test_impl() #ret { + #body + } + + // We put all initialization code into a separate module here in + // order to prevent potential ambiguities that could result in + // compilation errors. E.g., client code could use traits that + // could have methods that interfere with ones we use as part of + // initialization; with a `Foo` trait that is implemented for T + // and that contains a `map` (or similarly common named) method + // that could cause an ambiguity with `Iterator::map`, for + // example. + // The alternative would be to use fully qualified call syntax in + // all initialization code, but that's much harder to control. + mod init { + pub fn init() { + #logging_init + #tracing_init + } + } + + init::init(); + test_impl()#await_ + } + }; + result.into() +}