cargo-test-support-0.3.0/.cargo_vcs_info.json 0000644 00000000167 00000000001 0014622 0 ustar {
"git": {
"sha1": "2dbb1af80a2914475ba76827a312e29cedfa6b2f"
},
"path_in_vcs": "crates/cargo-test-support"
} cargo-test-support-0.3.0/Cargo.toml 0000644 00000004717 00000000001 0012625 0 ustar # 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.79"
name = "cargo-test-support"
version = "0.3.0"
build = "build.rs"
autobins = false
autoexamples = false
autotests = false
autobenches = false
description = "Testing framework for Cargo's testsuite."
homepage = "https://github.com/rust-lang/cargo"
readme = "README.md"
license = "MIT OR Apache-2.0"
repository = "https://github.com/rust-lang/cargo"
[lib]
name = "cargo_test_support"
path = "src/lib.rs"
doctest = false
[dependencies.anstream]
version = "0.6.13"
[dependencies.anstyle]
version = "1.0.6"
[dependencies.anyhow]
version = "1.0.82"
[dependencies.cargo-test-macro]
version = "0.3.0"
[dependencies.cargo-util]
version = "0.2.14"
[dependencies.crates-io]
version = "0.40.4"
[dependencies.filetime]
version = "0.2.23"
[dependencies.flate2]
version = "1.0.30"
features = ["zlib"]
default-features = false
[dependencies.git2]
version = "0.19.0"
[dependencies.glob]
version = "0.3.1"
[dependencies.itertools]
version = "0.13.0"
[dependencies.pasetors]
version = "0.6.8"
features = [
"v3",
"paserk",
"std",
"serde",
]
[dependencies.regex]
version = "1.10.4"
[dependencies.serde]
version = "1.0.199"
features = ["derive"]
[dependencies.serde_json]
version = "1.0.116"
[dependencies.snapbox]
version = "0.6.9"
features = [
"diff",
"dir",
"term-svg",
"regex",
"json",
]
[dependencies.tar]
version = "0.4.40"
default-features = false
[dependencies.time]
version = "0.3.36"
features = [
"parsing",
"formatting",
"serde",
]
[dependencies.toml]
version = "0.8.14"
[dependencies.url]
version = "2.5.0"
[dependencies.walkdir]
version = "2.5.0"
[target."cfg(windows)".dependencies.windows-sys]
version = "0.52"
features = ["Win32_Storage_FileSystem"]
[lints.clippy]
dbg_macro = "warn"
disallowed_methods = "warn"
print_stderr = "warn"
print_stdout = "warn"
self_named_module_files = "warn"
[lints.clippy.all]
level = "allow"
priority = -1
[lints.rust]
rust_2018_idioms = "warn"
[lints.rustdoc]
private_intra_doc_links = "allow"
cargo-test-support-0.3.0/Cargo.toml.orig 0000644 0000000 0000000 00000001722 10461020230 0016277 0 ustar 0000000 0000000 [package]
name = "cargo-test-support"
version = "0.3.0"
edition.workspace = true
rust-version = "1.79" # MSRV:1
license.workspace = true
homepage.workspace = true
repository.workspace = true
description = "Testing framework for Cargo's testsuite."
[lib]
doctest = false
[dependencies]
anstream.workspace = true
anstyle.workspace = true
anyhow.workspace = true
cargo-test-macro.workspace = true
cargo-util.workspace = true
crates-io.workspace = true
filetime.workspace = true
flate2.workspace = true
git2.workspace = true
glob.workspace = true
itertools.workspace = true
pasetors.workspace = true
regex.workspace = true
serde = { workspace = true, features = ["derive"] }
serde_json.workspace = true
snapbox.workspace = true
tar.workspace = true
time.workspace = true
toml.workspace = true
url.workspace = true
walkdir.workspace = true
[target.'cfg(windows)'.dependencies]
windows-sys = { workspace = true, features = ["Win32_Storage_FileSystem"] }
[lints]
workspace = true
cargo-test-support-0.3.0/LICENSE-APACHE 0000644 0000000 0000000 00000025154 10461020230 0015341 0 ustar 0000000 0000000 Apache License
Version 2.0, January 2004
https://www.apache.org/licenses/LICENSE-2.0
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.
cargo-test-support-0.3.0/LICENSE-MIT 0000644 0000000 0000000 00000001777 10461020230 0015056 0 ustar 0000000 0000000 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.
cargo-test-support-0.3.0/README.md 0000644 0000000 0000000 00000000376 10461020230 0014673 0 ustar 0000000 0000000 WARNING: You might not want to use this outside of Cargo.
* This is designed for testing Cargo itself. Use at your own risk.
* No guarantee on any stability across versions.
* No feature request would be accepted unless proved useful for testing Cargo.
cargo-test-support-0.3.0/build.rs 0000644 0000000 0000000 00000000425 10461020230 0015054 0 ustar 0000000 0000000 #![allow(clippy::disallowed_methods)]
fn main() {
println!("cargo:rustc-check-cfg=cfg(emulate_second_only_system)");
println!(
"cargo:rustc-env=NATIVE_ARCH={}",
std::env::var("TARGET").unwrap()
);
println!("cargo:rerun-if-changed=build.rs");
}
cargo-test-support-0.3.0/containers/apache/Dockerfile 0000644 0000000 0000000 00000001413 10461020230 0020765 0 ustar 0000000 0000000 FROM httpd:2.4-alpine
RUN apk add --no-cache git git-daemon openssl
COPY bar /repos/bar
WORKDIR /repos/bar
RUN git config --global user.email "testuser@example.com" &&\
git config --global user.name "Test User" &&\
git config --system --add safe.directory '*' &&\
git init -b master . &&\
git add Cargo.toml src &&\
git commit -m "Initial commit" &&\
cd .. &&\
git clone --bare bar bar.git &&\
rm -rf bar
WORKDIR /
EXPOSE 443
WORKDIR /usr/local/apache2/conf
COPY httpd-cargo.conf .
RUN cat httpd-cargo.conf >> httpd.conf
RUN openssl req -x509 -nodes -days 3650 -newkey rsa:2048 \
-keyout server.key -out server.crt \
-subj "/emailAddress=webmaster@example.com/C=US/ST=California/L=San Francisco/O=Rust/OU=Cargo/CN=127.0.0.1"
WORKDIR /
cargo-test-support-0.3.0/containers/apache/httpd-cargo.conf 0000644 0000000 0000000 00000000546 10461020230 0022064 0 ustar 0000000 0000000 SetEnv GIT_PROJECT_ROOT /repos
SetEnv GIT_HTTP_EXPORT_ALL
ScriptAlias /repos /usr/libexec/git-core/git-http-backend/
LoadModule cgid_module modules/mod_cgid.so
Require all granted
Include conf/extra/httpd-ssl.conf
LoadModule ssl_module modules/mod_ssl.so
LoadModule socache_shmcb_module modules/mod_socache_shmcb.so
cargo-test-support-0.3.0/containers/sshd/Dockerfile 0000644 0000000 0000000 00000001455 10461020230 0020513 0 ustar 0000000 0000000 FROM alpine:3.20
RUN apk add --no-cache openssh git
RUN ssh-keygen -A
RUN addgroup -S testuser && adduser -S testuser -G testuser -s /bin/ash
# NOTE: Ideally the password should be set to *, but I am uncertain how to do
# that in alpine. It shouldn't matter since PermitEmptyPasswords is "no".
RUN passwd -u testuser
RUN mkdir /repos && chown testuser /repos
COPY --chown=testuser:testuser bar /repos/bar
USER testuser
WORKDIR /repos/bar
RUN git config --global user.email "testuser@example.com" &&\
git config --global user.name "Test User" &&\
git init -b master . &&\
git add Cargo.toml src &&\
git commit -m "Initial commit" &&\
cd .. &&\
git clone --bare bar bar.git &&\
rm -rf bar
WORKDIR /
USER root
EXPOSE 22
ENTRYPOINT ["/usr/sbin/sshd", "-D", "-E", "/var/log/auth.log"]
cargo-test-support-0.3.0/src/compare.rs 0000644 0000000 0000000 00000074735 10461020230 0016211 0 ustar 0000000 0000000 //! Routines for comparing and diffing output.
//!
//! # Patterns
//!
//! Many of these functions support special markup to assist with comparing
//! text that may vary or is otherwise uninteresting for the test at hand. The
//! supported patterns are:
//!
//! - `[..]` is a wildcard that matches 0 or more characters on the same line
//! (similar to `.*` in a regex). It is non-greedy.
//! - `[EXE]` optionally adds `.exe` on Windows (empty string on other
//! platforms).
//! - `[ROOT]` is the path to the test directory's root.
//! - `[CWD]` is the working directory of the process that was run.
//! - There is a wide range of substitutions (such as `[COMPILING]` or
//! `[WARNING]`) to match cargo's "status" output and allows you to ignore
//! the alignment. See the source of `substitute_macros` for a complete list
//! of substitutions.
//! - `[DIRTY-MSVC]` (only when the line starts with it) would be replaced by
//! `[DIRTY]` when `cfg(target_env = "msvc")` or the line will be ignored otherwise.
//! Tests that work around [issue 7358](https://github.com/rust-lang/cargo/issues/7358)
//! can use this to avoid duplicating the `with_stderr` call like:
//! `if cfg!(target_env = "msvc") {e.with_stderr("...[DIRTY]...");} else {e.with_stderr("...");}`.
//!
//! # Normalization
//!
//! In addition to the patterns described above, the strings are normalized
//! in such a way to avoid unwanted differences. The normalizations are:
//!
//! - Raw tab characters are converted to the string ``. This is helpful
//! so that raw tabs do not need to be written in the expected string, and
//! to avoid confusion of tabs vs spaces.
//! - Backslashes are converted to forward slashes to deal with Windows paths.
//! This helps so that all tests can be written assuming forward slashes.
//! Other heuristics are applied to try to ensure Windows-style paths aren't
//! a problem.
//! - Carriage returns are removed, which can help when running on Windows.
use crate::cross_compile::try_alternate;
use crate::paths;
use crate::{diff, rustc_host};
use anyhow::{bail, Context, Result};
use serde_json::Value;
use std::fmt;
use std::path::Path;
use std::str;
use url::Url;
/// This makes it easier to write regex replacements that are guaranteed to only
/// get compiled once
macro_rules! regex {
($re:literal $(,)?) => {{
static RE: std::sync::OnceLock = std::sync::OnceLock::new();
RE.get_or_init(|| regex::Regex::new($re).unwrap())
}};
}
/// Assertion policy for UI tests
///
/// This emphasizes showing as much content as possible at the cost of more brittleness
///
/// # Snapshots
///
/// Updating of snapshots is controlled with the `SNAPSHOTS` environment variable:
///
/// - `skip`: do not run the tests
/// - `ignore`: run the tests but ignore their failure
/// - `verify`: run the tests
/// - `overwrite`: update the snapshots based on the output of the tests
///
/// # Patterns
///
/// - `[..]` is a character wildcard, stopping at line breaks
/// - `\n...\n` is a multi-line wildcard
/// - `[EXE]` matches the exe suffix for the current platform
/// - `[ROOT]` matches [`paths::root()`][crate::paths::root]
/// - `[ROOTURL]` matches [`paths::root()`][crate::paths::root] as a URL
///
/// # Normalization
///
/// In addition to the patterns described above, text is normalized
/// in such a way to avoid unwanted differences. The normalizations are:
///
/// - Backslashes are converted to forward slashes to deal with Windows paths.
/// This helps so that all tests can be written assuming forward slashes.
/// Other heuristics are applied to try to ensure Windows-style paths aren't
/// a problem.
/// - Carriage returns are removed, which can help when running on Windows.
pub fn assert_ui() -> snapbox::Assert {
let mut subs = snapbox::Redactions::new();
subs.extend(MIN_LITERAL_REDACTIONS.into_iter().cloned())
.unwrap();
add_test_support_redactions(&mut subs);
add_regex_redactions(&mut subs);
snapbox::Assert::new()
.action_env(snapbox::assert::DEFAULT_ACTION_ENV)
.redact_with(subs)
}
/// Assertion policy for functional end-to-end tests
///
/// This emphasizes showing as much content as possible at the cost of more brittleness
///
/// # Snapshots
///
/// Updating of snapshots is controlled with the `SNAPSHOTS` environment variable:
///
/// - `skip`: do not run the tests
/// - `ignore`: run the tests but ignore their failure
/// - `verify`: run the tests
/// - `overwrite`: update the snapshots based on the output of the tests
///
/// # Patterns
///
/// - `[..]` is a character wildcard, stopping at line breaks
/// - `\n...\n` is a multi-line wildcard
/// - `[EXE]` matches the exe suffix for the current platform
/// - `[ROOT]` matches [`paths::root()`][crate::paths::root]
/// - `[ROOTURL]` matches [`paths::root()`][crate::paths::root] as a URL
///
/// # Normalization
///
/// In addition to the patterns described above, text is normalized
/// in such a way to avoid unwanted differences. The normalizations are:
///
/// - Backslashes are converted to forward slashes to deal with Windows paths.
/// This helps so that all tests can be written assuming forward slashes.
/// Other heuristics are applied to try to ensure Windows-style paths aren't
/// a problem.
/// - Carriage returns are removed, which can help when running on Windows.
pub fn assert_e2e() -> snapbox::Assert {
let mut subs = snapbox::Redactions::new();
subs.extend(MIN_LITERAL_REDACTIONS.into_iter().cloned())
.unwrap();
subs.extend(E2E_LITERAL_REDACTIONS.into_iter().cloned())
.unwrap();
add_test_support_redactions(&mut subs);
add_regex_redactions(&mut subs);
snapbox::Assert::new()
.action_env(snapbox::assert::DEFAULT_ACTION_ENV)
.redact_with(subs)
}
fn add_test_support_redactions(subs: &mut snapbox::Redactions) {
let root = paths::root();
// Use `from_file_path` instead of `from_dir_path` so the trailing slash is
// put in the users output, rather than hidden in the variable
let root_url = url::Url::from_file_path(&root).unwrap().to_string();
subs.insert("[ROOT]", root).unwrap();
subs.insert("[ROOTURL]", root_url).unwrap();
subs.insert("[HOST_TARGET]", rustc_host()).unwrap();
if let Some(alt_target) = try_alternate() {
subs.insert("[ALT_TARGET]", alt_target).unwrap();
}
}
fn add_regex_redactions(subs: &mut snapbox::Redactions) {
// For e2e tests
subs.insert(
"[ELAPSED]",
regex!(r"\[FINISHED\].*in (?[0-9]+(\.[0-9]+)?(m [0-9]+)?)s"),
)
.unwrap();
// for UI tests
subs.insert(
"[ELAPSED]",
regex!(r"Finished.*in (?[0-9]+(\.[0-9]+)?(m [0-9]+)?)s"),
)
.unwrap();
// output from libtest
subs.insert(
"[ELAPSED]",
regex!(r"; finished in (?[0-9]+(\.[0-9]+)?(m [0-9]+)?)s"),
)
.unwrap();
subs.insert(
"[FILE_NUM]",
regex!(r"\[(REMOVED|SUMMARY)\] (?[0-9]+) files"),
)
.unwrap();
subs.insert(
"[FILE_SIZE]",
regex!(r"(?[0-9]+(\.[0-9]+)?([a-zA-Z]i)?)B\s"),
)
.unwrap();
subs.insert(
"[HASH]",
regex!(r"home/\.cargo/registry/src/-(?[a-z0-9]+)"),
)
.unwrap();
subs.insert(
"[HASH]",
regex!(r"\.cargo/target/(?[0-9a-f]{2}/[0-9a-f]{14})"),
)
.unwrap();
subs.insert("[HASH]", regex!(r"/[a-z0-9\-_]+-(?[0-9a-f]{16})"))
.unwrap();
subs.insert(
"[AVG_ELAPSED]",
regex!(r"(?[0-9]+(\.[0-9]+)?) ns/iter"),
)
.unwrap();
subs.insert(
"[JITTER]",
regex!(r"ns/iter \(\+/- (?[0-9]+(\.[0-9]+)?)\)"),
)
.unwrap();
// Following 3 subs redact:
// "1719325877.527949100s, 61549498ns after last build at 1719325877.466399602s"
// "1719503592.218193216s, 1h 1s after last build at 1719499991.982681034s"
// into "[DIRTY_REASON_NEW_TIME], [DIRTY_REASON_DIFF] after last build at [DIRTY_REASON_OLD_TIME]"
subs.insert(
"[TIME_DIFF_AFTER_LAST_BUILD]",
regex!(r"(?[0-9]+(\.[0-9]+)?s, (\s?[0-9]+(\.[0-9]+)?(s|ns|h))+ after last build at [0-9]+(\.[0-9]+)?s)"),
)
.unwrap();
}
static MIN_LITERAL_REDACTIONS: &[(&str, &str)] = &[
("[EXE]", std::env::consts::EXE_SUFFIX),
("[BROKEN_PIPE]", "Broken pipe (os error 32)"),
("[BROKEN_PIPE]", "The pipe is being closed. (os error 232)"),
// Unix message for an entity was not found
("[NOT_FOUND]", "No such file or directory (os error 2)"),
// Windows message for an entity was not found
(
"[NOT_FOUND]",
"The system cannot find the file specified. (os error 2)",
),
(
"[NOT_FOUND]",
"The system cannot find the path specified. (os error 3)",
),
("[NOT_FOUND]", "Access is denied. (os error 5)"),
("[NOT_FOUND]", "program not found"),
// Unix message for exit status
("[EXIT_STATUS]", "exit status"),
// Windows message for exit status
("[EXIT_STATUS]", "exit code"),
];
static E2E_LITERAL_REDACTIONS: &[(&str, &str)] = &[
("[RUNNING]", " Running"),
("[COMPILING]", " Compiling"),
("[CHECKING]", " Checking"),
("[COMPLETED]", " Completed"),
("[CREATED]", " Created"),
("[CREATING]", " Creating"),
("[CREDENTIAL]", " Credential"),
("[DOWNGRADING]", " Downgrading"),
("[FINISHED]", " Finished"),
("[ERROR]", "error:"),
("[WARNING]", "warning:"),
("[NOTE]", "note:"),
("[HELP]", "help:"),
("[DOCUMENTING]", " Documenting"),
("[SCRAPING]", " Scraping"),
("[FRESH]", " Fresh"),
("[DIRTY]", " Dirty"),
("[LOCKING]", " Locking"),
("[UPDATING]", " Updating"),
("[UPGRADING]", " Upgrading"),
("[ADDING]", " Adding"),
("[REMOVING]", " Removing"),
("[REMOVED]", " Removed"),
("[UNCHANGED]", " Unchanged"),
("[DOCTEST]", " Doc-tests"),
("[PACKAGING]", " Packaging"),
("[PACKAGED]", " Packaged"),
("[DOWNLOADING]", " Downloading"),
("[DOWNLOADED]", " Downloaded"),
("[UPLOADING]", " Uploading"),
("[UPLOADED]", " Uploaded"),
("[VERIFYING]", " Verifying"),
("[ARCHIVING]", " Archiving"),
("[INSTALLING]", " Installing"),
("[REPLACING]", " Replacing"),
("[UNPACKING]", " Unpacking"),
("[SUMMARY]", " Summary"),
("[FIXED]", " Fixed"),
("[FIXING]", " Fixing"),
("[IGNORED]", " Ignored"),
("[INSTALLED]", " Installed"),
("[REPLACED]", " Replaced"),
("[BUILDING]", " Building"),
("[LOGIN]", " Login"),
("[LOGOUT]", " Logout"),
("[YANK]", " Yank"),
("[OWNER]", " Owner"),
("[MIGRATING]", " Migrating"),
("[EXECUTABLE]", " Executable"),
("[SKIPPING]", " Skipping"),
("[WAITING]", " Waiting"),
("[PUBLISHED]", " Published"),
("[BLOCKING]", " Blocking"),
("[GENERATED]", " Generated"),
("[OPENING]", " Opening"),
];
/// Normalizes the output so that it can be compared against the expected value.
fn normalize_actual(actual: &str, cwd: Option<&Path>) -> String {
// It's easier to read tabs in outputs if they don't show up as literal
// hidden characters
let actual = actual.replace('\t', "");
if cfg!(windows) {
// Let's not deal with \r\n vs \n on windows...
let actual = actual.replace('\r', "");
normalize_windows(&actual, cwd)
} else {
actual
}
}
/// Normalizes the expected string so that it can be compared against the actual output.
fn normalize_expected(expected: &str, cwd: Option<&Path>) -> String {
let expected = replace_dirty_msvc(expected);
let expected = substitute_macros(&expected);
if cfg!(windows) {
normalize_windows(&expected, cwd)
} else {
let expected = match cwd {
None => expected,
Some(cwd) => expected.replace("[CWD]", &cwd.display().to_string()),
};
let expected = expected.replace("[ROOT]", &paths::root().display().to_string());
expected
}
}
fn replace_dirty_msvc_impl(s: &str, is_msvc: bool) -> String {
if is_msvc {
s.replace("[DIRTY-MSVC]", "[DIRTY]")
} else {
use itertools::Itertools;
let mut new = s
.lines()
.filter(|it| !it.starts_with("[DIRTY-MSVC]"))
.join("\n");
if s.ends_with("\n") {
new.push_str("\n");
}
new
}
}
fn replace_dirty_msvc(s: &str) -> String {
replace_dirty_msvc_impl(s, cfg!(target_env = "msvc"))
}
/// Normalizes text for both actual and expected strings on Windows.
fn normalize_windows(text: &str, cwd: Option<&Path>) -> String {
// Let's not deal with / vs \ (windows...)
let text = text.replace('\\', "/");
// Weirdness for paths on Windows extends beyond `/` vs `\` apparently.
// Namely paths like `c:\` and `C:\` are equivalent and that can cause
// issues. The return value of `env::current_dir()` may return a
// lowercase drive name, but we round-trip a lot of values through `Url`
// which will auto-uppercase the drive name. To just ignore this
// distinction we try to canonicalize as much as possible, taking all
// forms of a path and canonicalizing them to one.
let replace_path = |s: &str, path: &Path, with: &str| {
let path_through_url = Url::from_file_path(path).unwrap().to_file_path().unwrap();
let path1 = path.display().to_string().replace('\\', "/");
let path2 = path_through_url.display().to_string().replace('\\', "/");
s.replace(&path1, with)
.replace(&path2, with)
.replace(with, &path1)
};
let text = match cwd {
None => text,
Some(p) => replace_path(&text, p, "[CWD]"),
};
// Similar to cwd above, perform similar treatment to the root path
// which in theory all of our paths should otherwise get rooted at.
let root = paths::root();
let text = replace_path(&text, &root, "[ROOT]");
text
}
fn substitute_macros(input: &str) -> String {
let mut result = input.to_owned();
for &(pat, subst) in MIN_LITERAL_REDACTIONS {
result = result.replace(pat, subst)
}
for &(pat, subst) in E2E_LITERAL_REDACTIONS {
result = result.replace(pat, subst)
}
result
}
/// Compares one string against another, checking that they both match.
///
/// See [Patterns](index.html#patterns) for more information on pattern matching.
///
/// - `description` explains where the output is from (usually "stdout" or "stderr").
/// - `other_output` is other output to display in the error (usually stdout or stderr).
pub(crate) fn match_exact(
expected: &str,
actual: &str,
description: &str,
other_output: &str,
cwd: Option<&Path>,
) -> Result<()> {
let expected = normalize_expected(expected, cwd);
let actual = normalize_actual(actual, cwd);
let e: Vec<_> = expected.lines().map(WildStr::new).collect();
let a: Vec<_> = actual.lines().map(WildStr::new).collect();
if e == a {
return Ok(());
}
let diff = diff::colored_diff(&e, &a);
bail!(
"{} did not match:\n\
{}\n\n\
other output:\n\
{}\n",
description,
diff,
other_output,
);
}
/// Convenience wrapper around [`match_exact`] which will panic on error.
#[track_caller]
pub(crate) fn assert_match_exact(expected: &str, actual: &str) {
if let Err(e) = match_exact(expected, actual, "", "", None) {
crate::panic_error("", e);
}
}
/// Checks that the given string contains the given lines, ignoring the order
/// of the lines.
///
/// See [Patterns](index.html#patterns) for more information on pattern matching.
pub(crate) fn match_unordered(expected: &str, actual: &str, cwd: Option<&Path>) -> Result<()> {
let expected = normalize_expected(expected, cwd);
let actual = normalize_actual(actual, cwd);
let e: Vec<_> = expected.lines().map(|line| WildStr::new(line)).collect();
let mut a: Vec<_> = actual.lines().map(|line| WildStr::new(line)).collect();
// match more-constrained lines first, although in theory we'll
// need some sort of recursive match here. This handles the case
// that you expect "a\n[..]b" and two lines are printed out,
// "ab\n"a", where technically we do match unordered but a naive
// search fails to find this. This simple sort at least gets the
// test suite to pass for now, but we may need to get more fancy
// if tests start failing again.
a.sort_by_key(|s| s.line.len());
let mut changes = Vec::new();
let mut a_index = 0;
let mut failure = false;
use crate::diff::Change;
for (e_i, e_line) in e.into_iter().enumerate() {
match a.iter().position(|a_line| e_line == *a_line) {
Some(index) => {
let a_line = a.remove(index);
changes.push(Change::Keep(e_i, index, a_line));
a_index += 1;
}
None => {
failure = true;
changes.push(Change::Remove(e_i, e_line));
}
}
}
for unmatched in a {
failure = true;
changes.push(Change::Add(a_index, unmatched));
a_index += 1;
}
if failure {
bail!(
"Expected lines did not match (ignoring order):\n{}\n",
diff::render_colored_changes(&changes)
);
} else {
Ok(())
}
}
/// Checks that the given string contains the given contiguous lines
/// somewhere.
///
/// See [Patterns](index.html#patterns) for more information on pattern matching.
pub(crate) fn match_contains(expected: &str, actual: &str, cwd: Option<&Path>) -> Result<()> {
let expected = normalize_expected(expected, cwd);
let actual = normalize_actual(actual, cwd);
let e: Vec<_> = expected.lines().map(|line| WildStr::new(line)).collect();
let a: Vec<_> = actual.lines().map(|line| WildStr::new(line)).collect();
if e.len() == 0 {
bail!("expected length must not be zero");
}
for window in a.windows(e.len()) {
if window == e {
return Ok(());
}
}
bail!(
"expected to find:\n\
{}\n\n\
did not find in output:\n\
{}",
expected,
actual
);
}
/// Checks that the given string does not contain the given contiguous lines
/// anywhere.
///
/// See [Patterns](index.html#patterns) for more information on pattern matching.
pub(crate) fn match_does_not_contain(
expected: &str,
actual: &str,
cwd: Option<&Path>,
) -> Result<()> {
if match_contains(expected, actual, cwd).is_ok() {
bail!(
"expected not to find:\n\
{}\n\n\
but found in output:\n\
{}",
expected,
actual
);
} else {
Ok(())
}
}
/// Checks that the given string contains the given contiguous lines
/// somewhere, and should be repeated `number` times.
///
/// See [Patterns](index.html#patterns) for more information on pattern matching.
pub(crate) fn match_contains_n(
expected: &str,
number: usize,
actual: &str,
cwd: Option<&Path>,
) -> Result<()> {
let expected = normalize_expected(expected, cwd);
let actual = normalize_actual(actual, cwd);
let e: Vec<_> = expected.lines().map(|line| WildStr::new(line)).collect();
let a: Vec<_> = actual.lines().map(|line| WildStr::new(line)).collect();
if e.len() == 0 {
bail!("expected length must not be zero");
}
let matches = a.windows(e.len()).filter(|window| *window == e).count();
if matches == number {
Ok(())
} else {
bail!(
"expected to find {} occurrences of:\n\
{}\n\n\
but found {} matches in the output:\n\
{}",
number,
expected,
matches,
actual
)
}
}
/// Checks that the given string has a line that contains the given patterns,
/// and that line also does not contain the `without` patterns.
///
/// See [Patterns](index.html#patterns) for more information on pattern matching.
///
/// See [`crate::Execs::with_stderr_line_without`] for an example and cautions
/// against using.
pub(crate) fn match_with_without(
actual: &str,
with: &[String],
without: &[String],
cwd: Option<&Path>,
) -> Result<()> {
let actual = normalize_actual(actual, cwd);
let norm = |s: &String| format!("[..]{}[..]", normalize_expected(s, cwd));
let with: Vec<_> = with.iter().map(norm).collect();
let without: Vec<_> = without.iter().map(norm).collect();
let with_wild: Vec<_> = with.iter().map(|w| WildStr::new(w)).collect();
let without_wild: Vec<_> = without.iter().map(|w| WildStr::new(w)).collect();
let matches: Vec<_> = actual
.lines()
.map(WildStr::new)
.filter(|line| with_wild.iter().all(|with| with == line))
.filter(|line| !without_wild.iter().any(|without| without == line))
.collect();
match matches.len() {
0 => bail!(
"Could not find expected line in output.\n\
With contents: {:?}\n\
Without contents: {:?}\n\
Actual stderr:\n\
{}\n",
with,
without,
actual
),
1 => Ok(()),
_ => bail!(
"Found multiple matching lines, but only expected one.\n\
With contents: {:?}\n\
Without contents: {:?}\n\
Matching lines:\n\
{}\n",
with,
without,
itertools::join(matches, "\n")
),
}
}
/// Checks that the given string of JSON objects match the given set of
/// expected JSON objects.
///
/// See [`crate::Execs::with_json`] for more details.
pub(crate) fn match_json(expected: &str, actual: &str, cwd: Option<&Path>) -> Result<()> {
let (exp_objs, act_objs) = collect_json_objects(expected, actual)?;
if exp_objs.len() != act_objs.len() {
bail!(
"expected {} json lines, got {}, stdout:\n{}",
exp_objs.len(),
act_objs.len(),
actual
);
}
for (exp_obj, act_obj) in exp_objs.iter().zip(act_objs) {
find_json_mismatch(exp_obj, &act_obj, cwd)?;
}
Ok(())
}
/// Checks that the given string of JSON objects match the given set of
/// expected JSON objects, ignoring their order.
///
/// See [`crate::Execs::with_json_contains_unordered`] for more details and
/// cautions when using.
pub(crate) fn match_json_contains_unordered(
expected: &str,
actual: &str,
cwd: Option<&Path>,
) -> Result<()> {
let (exp_objs, mut act_objs) = collect_json_objects(expected, actual)?;
for exp_obj in exp_objs {
match act_objs
.iter()
.position(|act_obj| find_json_mismatch(&exp_obj, act_obj, cwd).is_ok())
{
Some(index) => act_objs.remove(index),
None => {
bail!(
"Did not find expected JSON:\n\
{}\n\
Remaining available output:\n\
{}\n",
serde_json::to_string_pretty(&exp_obj).unwrap(),
itertools::join(
act_objs.iter().map(|o| serde_json::to_string(o).unwrap()),
"\n"
)
);
}
};
}
Ok(())
}
fn collect_json_objects(
expected: &str,
actual: &str,
) -> Result<(Vec, Vec)> {
let expected_objs: Vec<_> = expected
.split("\n\n")
.map(|expect| {
expect
.parse()
.with_context(|| format!("failed to parse expected JSON object:\n{}", expect))
})
.collect::>()?;
let actual_objs: Vec<_> = actual
.lines()
.filter(|line| line.starts_with('{'))
.map(|line| {
line.parse()
.with_context(|| format!("failed to parse JSON object:\n{}", line))
})
.collect::>()?;
Ok((expected_objs, actual_objs))
}
/// Compares JSON object for approximate equality.
/// You can use `[..]` wildcard in strings (useful for OS-dependent things such
/// as paths). You can use a `"{...}"` string literal as a wildcard for
/// arbitrary nested JSON (useful for parts of object emitted by other programs
/// (e.g., rustc) rather than Cargo itself).
pub(crate) fn find_json_mismatch(
expected: &Value,
actual: &Value,
cwd: Option<&Path>,
) -> Result<()> {
match find_json_mismatch_r(expected, actual, cwd) {
Some((expected_part, actual_part)) => bail!(
"JSON mismatch\nExpected:\n{}\nWas:\n{}\nExpected part:\n{}\nActual part:\n{}\n",
serde_json::to_string_pretty(expected).unwrap(),
serde_json::to_string_pretty(&actual).unwrap(),
serde_json::to_string_pretty(expected_part).unwrap(),
serde_json::to_string_pretty(actual_part).unwrap(),
),
None => Ok(()),
}
}
fn find_json_mismatch_r<'a>(
expected: &'a Value,
actual: &'a Value,
cwd: Option<&Path>,
) -> Option<(&'a Value, &'a Value)> {
use serde_json::Value::*;
match (expected, actual) {
(&Number(ref l), &Number(ref r)) if l == r => None,
(&Bool(l), &Bool(r)) if l == r => None,
(&String(ref l), _) if l == "{...}" => None,
(&String(ref l), &String(ref r)) => {
if match_exact(l, r, "", "", cwd).is_err() {
Some((expected, actual))
} else {
None
}
}
(&Array(ref l), &Array(ref r)) => {
if l.len() != r.len() {
return Some((expected, actual));
}
l.iter()
.zip(r.iter())
.filter_map(|(l, r)| find_json_mismatch_r(l, r, cwd))
.next()
}
(&Object(ref l), &Object(ref r)) => {
let mut expected_entries = l.iter();
let mut actual_entries = r.iter();
loop {
match (expected_entries.next(), actual_entries.next()) {
(None, None) => return None,
(Some((expected_key, expected_value)), Some((actual_key, actual_value)))
if expected_key == actual_key =>
{
if let mismatch @ Some(_) =
find_json_mismatch_r(expected_value, actual_value, cwd)
{
return mismatch;
}
}
_ => return Some((expected, actual)),
}
}
}
(&Null, &Null) => None,
// Magic string literal `"{...}"` acts as wildcard for any sub-JSON.
_ => Some((expected, actual)),
}
}
/// A single line string that supports `[..]` wildcard matching.
pub(crate) struct WildStr<'a> {
has_meta: bool,
line: &'a str,
}
impl<'a> WildStr<'a> {
pub fn new(line: &'a str) -> WildStr<'a> {
WildStr {
has_meta: line.contains("[..]"),
line,
}
}
}
impl<'a> PartialEq for WildStr<'a> {
fn eq(&self, other: &Self) -> bool {
match (self.has_meta, other.has_meta) {
(false, false) => self.line == other.line,
(true, false) => meta_cmp(self.line, other.line),
(false, true) => meta_cmp(other.line, self.line),
(true, true) => panic!("both lines cannot have [..]"),
}
}
}
fn meta_cmp(a: &str, mut b: &str) -> bool {
for (i, part) in a.split("[..]").enumerate() {
match b.find(part) {
Some(j) => {
if i == 0 && j != 0 {
return false;
}
b = &b[j + part.len()..];
}
None => return false,
}
}
b.is_empty() || a.ends_with("[..]")
}
impl fmt::Display for WildStr<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.line)
}
}
impl fmt::Debug for WildStr<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:?}", self.line)
}
}
#[cfg(test)]
mod test {
use snapbox::assert_data_eq;
use snapbox::prelude::*;
use snapbox::str;
use super::*;
#[test]
fn wild_str_cmp() {
for (a, b) in &[
("a b", "a b"),
("a[..]b", "a b"),
("a[..]", "a b"),
("[..]", "a b"),
("[..]b", "a b"),
] {
assert_eq!(WildStr::new(a), WildStr::new(b));
}
for (a, b) in &[("[..]b", "c"), ("b", "c"), ("b", "cb")] {
assert_ne!(WildStr::new(a), WildStr::new(b));
}
}
#[test]
fn dirty_msvc() {
let case = |expected: &str, wild: &str, msvc: bool| {
assert_eq!(expected, &replace_dirty_msvc_impl(wild, msvc));
};
// no replacements
case("aa", "aa", false);
case("aa", "aa", true);
// with replacements
case(
"\
[DIRTY] a",
"\
[DIRTY-MSVC] a",
true,
);
case(
"",
"\
[DIRTY-MSVC] a",
false,
);
case(
"\
[DIRTY] a
[COMPILING] a",
"\
[DIRTY-MSVC] a
[COMPILING] a",
true,
);
case(
"\
[COMPILING] a",
"\
[DIRTY-MSVC] a
[COMPILING] a",
false,
);
// test trailing newline behavior
case(
"\
A
B
", "\
A
B
", true,
);
case(
"\
A
B
", "\
A
B
", false,
);
case(
"\
A
B", "\
A
B", true,
);
case(
"\
A
B", "\
A
B", false,
);
case(
"\
[DIRTY] a
",
"\
[DIRTY-MSVC] a
",
true,
);
case(
"\n",
"\
[DIRTY-MSVC] a
",
false,
);
case(
"\
[DIRTY] a",
"\
[DIRTY-MSVC] a",
true,
);
case(
"",
"\
[DIRTY-MSVC] a",
false,
);
}
#[test]
fn redact_elapsed_time() {
let mut subs = snapbox::Redactions::new();
add_regex_redactions(&mut subs);
assert_data_eq!(
subs.redact("[FINISHED] `release` profile [optimized] target(s) in 5.5s"),
str!["[FINISHED] `release` profile [optimized] target(s) in [ELAPSED]s"].raw()
);
assert_data_eq!(
subs.redact("[FINISHED] `release` profile [optimized] target(s) in 1m 05s"),
str!["[FINISHED] `release` profile [optimized] target(s) in [ELAPSED]s"].raw()
);
}
}
cargo-test-support-0.3.0/src/containers.rs 0000644 0000000 0000000 00000021721 10461020230 0016713 0 ustar 0000000 0000000 //! Support for testing using Docker containers.
//!
//! The [`Container`] type is a builder for configuring a container to run.
//! After you call `launch`, you can use the [`ContainerHandle`] to interact
//! with the running container.
//!
//! Tests using containers must use `#[cargo_test(container_test)]` to disable
//! them unless the CARGO_CONTAINER_TESTS environment variable is set.
use cargo_util::ProcessBuilder;
use std::collections::HashMap;
use std::io::Read;
use std::path::PathBuf;
use std::process::Command;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Mutex;
use tar::Header;
/// A builder for configuring a container to run.
pub struct Container {
/// The host directory that forms the basis of the Docker image.
build_context: PathBuf,
/// Files to copy over to the image.
files: Vec,
}
/// A handle to a running container.
///
/// You can use this to interact with the container.
pub struct ContainerHandle {
/// The name of the container.
name: String,
/// The IP address of the container.
///
/// NOTE: This is currently unused, but may be useful so I left it in.
/// This can only be used on Linux. macOS and Windows docker doesn't allow
/// direct connection to the container.
pub ip_address: String,
/// Port mappings of container_port to host_port for ports exposed via EXPOSE.
pub port_mappings: HashMap,
}
impl Container {
pub fn new(context_dir: &str) -> Container {
assert!(std::env::var_os("CARGO_CONTAINER_TESTS").is_some());
let mut build_context = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
build_context.push("containers");
build_context.push(context_dir);
Container {
build_context,
files: Vec::new(),
}
}
/// Adds a file to be copied into the container.
pub fn file(mut self, file: MkFile) -> Self {
self.files.push(file);
self
}
/// Starts the container.
pub fn launch(mut self) -> ContainerHandle {
static NEXT_ID: AtomicUsize = AtomicUsize::new(0);
let id = NEXT_ID.fetch_add(1, Ordering::SeqCst);
let name = format!("cargo_test_{id}");
remove_if_exists(&name);
self.create_container(&name);
self.copy_files(&name);
self.start_container(&name);
let info = self.container_inspect(&name);
let ip_address = if cfg!(target_os = "linux") {
info[0]["NetworkSettings"]["IPAddress"]
.as_str()
.unwrap()
.to_string()
} else {
// macOS and Windows can't make direct connections to the
// container. It only works through exposed ports or mapped ports.
"127.0.0.1".to_string()
};
let port_mappings = self.port_mappings(&info);
self.wait_till_ready(&port_mappings);
ContainerHandle {
name,
ip_address,
port_mappings,
}
}
fn create_container(&self, name: &str) {
static BUILD_LOCK: Mutex<()> = Mutex::new(());
let image_base = self.build_context.file_name().unwrap();
let image_name = format!("cargo-test-{}", image_base.to_str().unwrap());
let _lock = BUILD_LOCK
.lock()
.map_err(|_| panic!("previous docker build failed, unable to run test"));
ProcessBuilder::new("docker")
.args(&["build", "--tag", image_name.as_str()])
.arg(&self.build_context)
.exec_with_output()
.unwrap();
ProcessBuilder::new("docker")
.args(&[
"container",
"create",
"--publish-all",
"--rm",
"--name",
name,
])
.arg(image_name)
.exec_with_output()
.unwrap();
}
fn copy_files(&mut self, name: &str) {
if self.files.is_empty() {
return;
}
let mut ar = tar::Builder::new(Vec::new());
let files = std::mem::replace(&mut self.files, Vec::new());
for mut file in files {
ar.append_data(&mut file.header, &file.path, file.contents.as_slice())
.unwrap();
}
let ar = ar.into_inner().unwrap();
ProcessBuilder::new("docker")
.args(&["cp", "-"])
.arg(format!("{name}:/"))
.stdin(ar)
.exec_with_output()
.unwrap();
}
fn start_container(&self, name: &str) {
ProcessBuilder::new("docker")
.args(&["container", "start"])
.arg(name)
.exec_with_output()
.unwrap();
}
fn container_inspect(&self, name: &str) -> serde_json::Value {
let output = ProcessBuilder::new("docker")
.args(&["inspect", name])
.exec_with_output()
.unwrap();
serde_json::from_slice(&output.stdout).unwrap()
}
/// Returns the mapping of container_port->host_port for ports that were
/// exposed with EXPOSE.
fn port_mappings(&self, info: &serde_json::Value) -> HashMap {
info[0]["NetworkSettings"]["Ports"]
.as_object()
.unwrap()
.iter()
.map(|(key, value)| {
let key = key
.strip_suffix("/tcp")
.expect("expected TCP only ports")
.parse()
.unwrap();
let values = value.as_array().unwrap();
let value = values
.iter()
.find(|value| value["HostIp"].as_str().unwrap() == "0.0.0.0")
.expect("expected localhost IP");
let host_port = value["HostPort"].as_str().unwrap().parse().unwrap();
(key, host_port)
})
.collect()
}
fn wait_till_ready(&self, port_mappings: &HashMap) {
for port in port_mappings.values() {
let mut ok = false;
for _ in 0..30 {
match std::net::TcpStream::connect(format!("127.0.0.1:{port}")) {
Ok(_) => {
ok = true;
break;
}
Err(e) => {
if e.kind() != std::io::ErrorKind::ConnectionRefused {
panic!("unexpected localhost connection error: {e:?}");
}
std::thread::sleep(std::time::Duration::new(1, 0));
}
}
}
if !ok {
panic!("no listener on localhost port {port}");
}
}
}
}
impl ContainerHandle {
/// Executes a program inside a running container.
pub fn exec(&self, args: &[&str]) -> std::process::Output {
ProcessBuilder::new("docker")
.args(&["container", "exec", &self.name])
.args(args)
.exec_with_output()
.unwrap()
}
/// Returns the contents of a file inside the container.
pub fn read_file(&self, path: &str) -> String {
let output = ProcessBuilder::new("docker")
.args(&["cp", &format!("{}:{}", self.name, path), "-"])
.exec_with_output()
.unwrap();
let mut ar = tar::Archive::new(output.stdout.as_slice());
let mut entry = ar.entries().unwrap().next().unwrap().unwrap();
let mut contents = String::new();
entry.read_to_string(&mut contents).unwrap();
contents
}
}
impl Drop for ContainerHandle {
fn drop(&mut self) {
// To help with debugging, this will keep the container alive.
if std::env::var_os("CARGO_CONTAINER_TEST_KEEP").is_some() {
return;
}
remove_if_exists(&self.name);
}
}
fn remove_if_exists(name: &str) {
if let Err(e) = Command::new("docker")
.args(&["container", "rm", "--force", name])
.output()
{
panic!("failed to run docker: {e}");
}
}
/// Builder for configuring a file to copy into a container.
pub struct MkFile {
path: String,
contents: Vec,
header: Header,
}
impl MkFile {
/// Defines a file to add to the container.
///
/// This should be passed to `Container::file`.
///
/// The path is the path inside the container to create the file.
pub fn path(path: &str) -> MkFile {
MkFile {
path: path.to_string(),
contents: Vec::new(),
header: Header::new_gnu(),
}
}
pub fn contents(mut self, contents: impl Into>) -> Self {
self.contents = contents.into();
self.header.set_size(self.contents.len() as u64);
self
}
pub fn mode(mut self, mode: u32) -> Self {
self.header.set_mode(mode);
self
}
pub fn uid(mut self, uid: u64) -> Self {
self.header.set_uid(uid);
self
}
pub fn gid(mut self, gid: u64) -> Self {
self.header.set_gid(gid);
self
}
}
cargo-test-support-0.3.0/src/cross_compile.rs 0000644 0000000 0000000 00000021424 10461020230 0017407 0 ustar 0000000 0000000 //! Support for cross-compile tests with the `--target` flag.
//!
//! Note that cross-testing is very limited. You need to install the
//! "alternate" target to the host (32-bit for 64-bit hosts or vice-versa).
//!
//! Set CFG_DISABLE_CROSS_TESTS=1 environment variable to disable these tests
//! if you are unable to use the alternate target. Unfortunately 32-bit
//! support on macOS is going away, so macOS users are out of luck.
//!
//! These tests are all disabled on rust-lang/rust's CI, but run in Cargo's CI.
use crate::{basic_manifest, main_file, project};
use cargo_util::ProcessError;
use std::env;
use std::fmt::Write;
use std::process::{Command, Output};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Once;
/// Whether or not the resulting cross binaries can run on the host.
static CAN_RUN_ON_HOST: AtomicBool = AtomicBool::new(false);
pub fn disabled() -> bool {
// First, disable if requested.
match env::var("CFG_DISABLE_CROSS_TESTS") {
Ok(ref s) if *s == "1" => return true,
_ => {}
}
// Cross tests are only tested to work on macos, linux, and MSVC windows.
if !(cfg!(target_os = "macos") || cfg!(target_os = "linux") || cfg!(target_env = "msvc")) {
return true;
}
// It's not particularly common to have a cross-compilation setup, so
// try to detect that before we fail a bunch of tests through no fault
// of the user.
static CAN_BUILD_CROSS_TESTS: AtomicBool = AtomicBool::new(false);
static CHECK: Once = Once::new();
let cross_target = alternate();
let run_cross_test = || -> anyhow::Result