ctoolbox/utilities/logging/test_internal.rs
1// SPDX-License-Identifier: (Apache-2.0 OR MIT)
2// Copyright (C) 2020-2023 Threema GmbH, Danilo Bargen
3
4//! Internal functionality used by the [`#[traced_test]`](attr.traced_test.html) macro, repurposed for `#[ctb_test]`.
5//!
6//! These functions should usually not be accessed from user code. The stability of these functions
7//! is not guaranteed, the API may change even in patch releases.
8use std::sync::{Mutex, Once, OnceLock};
9
10pub use crate::utilities::logging::test_subscriber::{
11 MockWriter, get_subscriber,
12};
13
14/// Static variable to ensure that logging is only initialized once.
15pub static INITIALIZED: Once = Once::new();
16
17/// The global log output buffer used in tests.
18#[doc(hidden)]
19pub fn global_buf() -> &'static Mutex<Vec<u8>> {
20 static GLOBAL_BUF: OnceLock<Mutex<Vec<u8>>> = OnceLock::new();
21 GLOBAL_BUF.get_or_init(|| Mutex::new(vec![]))
22}
23
24/// Return whether the logs with the specified scope contain the specified value.
25///
26/// This function should usually not be used directly, instead use the `logs_contain(val: &str)`
27/// function injected by the [`#[traced_test]`](attr.traced_test.html) macro.
28pub fn logs_with_scope_contain(scope: &str, val: &str) -> bool {
29 let logs =
30 String::from_utf8(global_buf().lock().unwrap().to_vec()).unwrap();
31 for line in logs.split('\n') {
32 if line.contains(&format!(" {scope}:")) && line.contains(val) {
33 return true;
34 }
35 }
36 false
37}
38
39/// Run a function against a slice of logs for the specified scope and return
40/// its result.
41///
42/// This function should usually not be used directly, instead use the
43/// `logs_assert(F) where F: Fn(&[&str]) -> Result<(), String>` function
44/// injected by the [`#[traced_test]`](attr.traced_test.html) macro.
45pub fn logs_assert<F>(scope: &str, f: F) -> std::result::Result<(), String>
46where
47 F: Fn(&[&str]) -> std::result::Result<(), String>,
48{
49 let buf = global_buf().lock().unwrap();
50 let logs: Vec<&str> = std::str::from_utf8(&buf)
51 .expect("Logs contain invalid UTF8")
52 .lines()
53 .filter(|line| line.contains(&format!(" {scope}:")))
54 .collect();
55 f(&logs)
56}
57
58/*
59
60// From tracing-test:
61
62MIT License
63
64Copyright (C) 2020-2023 Threema GmbH, Danilo Bargen
65
66Permission is hereby granted, free of charge, to any person obtaining a copy of
67this software and associated documentation files (the "Software"), to deal in
68the Software without restriction, including without limitation the rights to
69use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
70of the Software, and to permit persons to whom the Software is furnished to do
71so, subject to the following conditions:
72
73The above copyright notice and this permission notice shall be included in all
74copies or substantial portions of the Software.
75
76THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
77IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
78FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
79AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
80LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
81OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
82SOFTWARE.
83
84 Apache License
85 Version 2.0, January 2004
86 http://www.apache.org/licenses/
87
88TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
89
901. Definitions.
91
92 "License" shall mean the terms and conditions for use, reproduction,
93 and distribution as defined by Sections 1 through 9 of this document.
94
95 "Licensor" shall mean the copyright owner or entity authorized by
96 the copyright owner that is granting the License.
97
98 "Legal Entity" shall mean the union of the acting entity and all
99 other entities that control, are controlled by, or are under common
100 control with that entity. For the purposes of this definition,
101 "control" means (i) the power, direct or indirect, to cause the
102 direction or management of such entity, whether by contract or
103 otherwise, or (ii) ownership of fifty percent (50%) or more of the
104 outstanding shares, or (iii) beneficial ownership of such entity.
105
106 "You" (or "Your") shall mean an individual or Legal Entity
107 exercising permissions granted by this License.
108
109 "Source" form shall mean the preferred form for making modifications,
110 including but not limited to software source code, documentation
111 source, and configuration files.
112
113 "Object" form shall mean any form resulting from mechanical
114 transformation or translation of a Source form, including but
115 not limited to compiled object code, generated documentation,
116 and conversions to other media types.
117
118 "Work" shall mean the work of authorship, whether in Source or
119 Object form, made available under the License, as indicated by a
120 copyright notice that is included in or attached to the work
121 (an example is provided in the Appendix below).
122
123 "Derivative Works" shall mean any work, whether in Source or Object
124 form, that is based on (or derived from) the Work and for which the
125 editorial revisions, annotations, elaborations, or other modifications
126 represent, as a whole, an original work of authorship. For the purposes
127 of this License, Derivative Works shall not include works that remain
128 separable from, or merely link (or bind by name) to the interfaces of,
129 the Work and Derivative Works thereof.
130
131 "Contribution" shall mean any work of authorship, including
132 the original version of the Work and any modifications or additions
133 to that Work or Derivative Works thereof, that is intentionally
134 submitted to Licensor for inclusion in the Work by the copyright owner
135 or by an individual or Legal Entity authorized to submit on behalf of
136 the copyright owner. For the purposes of this definition, "submitted"
137 means any form of electronic, verbal, or written communication sent
138 to the Licensor or its representatives, including but not limited to
139 communication on electronic mailing lists, source code control systems,
140 and issue tracking systems that are managed by, or on behalf of, the
141 Licensor for the purpose of discussing and improving the Work, but
142 excluding communication that is conspicuously marked or otherwise
143 designated in writing by the copyright owner as "Not a Contribution."
144
145 "Contributor" shall mean Licensor and any individual or Legal Entity
146 on behalf of whom a Contribution has been received by Licensor and
147 subsequently incorporated within the Work.
148
1492. Grant of Copyright License. Subject to the terms and conditions of
150 this License, each Contributor hereby grants to You a perpetual,
151 worldwide, non-exclusive, no-charge, royalty-free, irrevocable
152 copyright license to reproduce, prepare Derivative Works of,
153 publicly display, publicly perform, sublicense, and distribute the
154 Work and such Derivative Works in Source or Object form.
155
1563. Grant of Patent License. Subject to the terms and conditions of
157 this License, each Contributor hereby grants to You a perpetual,
158 worldwide, non-exclusive, no-charge, royalty-free, irrevocable
159 (except as stated in this section) patent license to make, have made,
160 use, offer to sell, sell, import, and otherwise transfer the Work,
161 where such license applies only to those patent claims licensable
162 by such Contributor that are necessarily infringed by their
163 Contribution(s) alone or by combination of their Contribution(s)
164 with the Work to which such Contribution(s) was submitted. If You
165 institute patent litigation against any entity (including a
166 cross-claim or counterclaim in a lawsuit) alleging that the Work
167 or a Contribution incorporated within the Work constitutes direct
168 or contributory patent infringement, then any patent licenses
169 granted to You under this License for that Work shall terminate
170 as of the date such litigation is filed.
171
1724. Redistribution. You may reproduce and distribute copies of the
173 Work or Derivative Works thereof in any medium, with or without
174 modifications, and in Source or Object form, provided that You
175 meet the following conditions:
176
177 (a) You must give any other recipients of the Work or
178 Derivative Works a copy of this License; and
179
180 (b) You must cause any modified files to carry prominent notices
181 stating that You changed the files; and
182
183 (c) You must retain, in the Source form of any Derivative Works
184 that You distribute, all copyright, patent, trademark, and
185 attribution notices from the Source form of the Work,
186 excluding those notices that do not pertain to any part of
187 the Derivative Works; and
188
189 (d) If the Work includes a "NOTICE" text file as part of its
190 distribution, then any Derivative Works that You distribute must
191 include a readable copy of the attribution notices contained
192 within such NOTICE file, excluding those notices that do not
193 pertain to any part of the Derivative Works, in at least one
194 of the following places: within a NOTICE text file distributed
195 as part of the Derivative Works; within the Source form or
196 documentation, if provided along with the Derivative Works; or,
197 within a display generated by the Derivative Works, if and
198 wherever such third-party notices normally appear. The contents
199 of the NOTICE file are for informational purposes only and
200 do not modify the License. You may add Your own attribution
201 notices within Derivative Works that You distribute, alongside
202 or as an addendum to the NOTICE text from the Work, provided
203 that such additional attribution notices cannot be construed
204 as modifying the License.
205
206 You may add Your own copyright statement to Your modifications and
207 may provide additional or different license terms and conditions
208 for use, reproduction, or distribution of Your modifications, or
209 for any such Derivative Works as a whole, provided Your use,
210 reproduction, and distribution of the Work otherwise complies with
211 the conditions stated in this License.
212
2135. Submission of Contributions. Unless You explicitly state otherwise,
214 any Contribution intentionally submitted for inclusion in the Work
215 by You to the Licensor shall be under the terms and conditions of
216 this License, without any additional terms or conditions.
217 Notwithstanding the above, nothing herein shall supersede or modify
218 the terms of any separate license agreement you may have executed
219 with Licensor regarding such Contributions.
220
2216. Trademarks. This License does not grant permission to use the trade
222 names, trademarks, service marks, or product names of the Licensor,
223 except as required for reasonable and customary use in describing the
224 origin of the Work and reproducing the content of the NOTICE file.
225
2267. Disclaimer of Warranty. Unless required by applicable law or
227 agreed to in writing, Licensor provides the Work (and each
228 Contributor provides its Contributions) on an "AS IS" BASIS,
229 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
230 implied, including, without limitation, any warranties or conditions
231 of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
232 PARTICULAR PURPOSE. You are solely responsible for determining the
233 appropriateness of using or redistributing the Work and assume any
234 risks associated with Your exercise of permissions under this License.
235
2368. Limitation of Liability. In no event and under no legal theory,
237 whether in tort (including negligence), contract, or otherwise,
238 unless required by applicable law (such as deliberate and grossly
239 negligent acts) or agreed to in writing, shall any Contributor be
240 liable to You for damages, including any direct, indirect, special,
241 incidental, or consequential damages of any character arising as a
242 result of this License or out of the use or inability to use the
243 Work (including but not limited to damages for loss of goodwill,
244 work stoppage, computer failure or malfunction, or any and all
245 other commercial damages or losses), even if such Contributor
246 has been advised of the possibility of such damages.
247
2489. Accepting Warranty or Additional Liability. While redistributing
249 the Work or Derivative Works thereof, You may choose to offer,
250 and charge a fee for, acceptance of support, warranty, indemnity,
251 or other liability obligations and/or rights consistent with this
252 License. However, in accepting such obligations, You may act only
253 on Your own behalf and on Your sole responsibility, not on behalf
254 of any other Contributor, and only if You agree to indemnify,
255 defend, and hold each Contributor harmless for any liability
256 incurred by, or claims asserted against, such Contributor by reason
257 of your accepting any such warranty or additional liability.
258
259END OF TERMS AND CONDITIONS
260
261*/