tests/inst: Fix lots of `cargo clippy` warnings

Prep for doing this in CI.
This commit is contained in:
Colin Walters 2021-03-17 17:13:52 +00:00
parent d522f261db
commit d11dd7a37b
3 changed files with 30 additions and 37 deletions

View File

@ -33,10 +33,10 @@ use strum_macros::EnumIter;
use crate::test::*; use crate::test::*;
const ORIGREF: &'static str = "orig-booted"; const ORIGREF: &str = "orig-booted";
const TESTREF: &'static str = "testcontent"; const TESTREF: &str = "testcontent";
const TDATAPATH: &'static str = "/var/tmp/ostree-test-transaction-data.json"; const TDATAPATH: &str = "/var/tmp/ostree-test-transaction-data.json";
const SRVREPO: &'static str = "/var/tmp/ostree-test-srv"; const SRVREPO: &str = "/var/tmp/ostree-test-srv";
// Percentage of ELF files to change per update // Percentage of ELF files to change per update
const TREEGEN_PERCENTAGE: u32 = 15; const TREEGEN_PERCENTAGE: u32 = 15;
/// Total number of reboots /// Total number of reboots
@ -111,21 +111,18 @@ impl RebootMark {
InterruptStrategy::Polite(t) => self InterruptStrategy::Polite(t) => self
.polite .polite
.entry(t.clone()) .entry(t.clone())
.or_insert_with(|| BTreeMap::new()), .or_insert_with(BTreeMap::new),
InterruptStrategy::Force(t) => self InterruptStrategy::Force(t) => self
.force .force
.entry(t.clone()) .entry(t.clone())
.or_insert_with(|| BTreeMap::new()), .or_insert_with(BTreeMap::new),
} }
} }
} }
impl InterruptStrategy { impl InterruptStrategy {
pub(crate) fn is_noop(&self) -> bool { pub(crate) fn is_noop(&self) -> bool {
match self { matches!(self, InterruptStrategy::Polite(PoliteInterruptStrategy::None))
InterruptStrategy::Polite(PoliteInterruptStrategy::None) => true,
_ => false,
}
} }
} }
@ -324,18 +321,16 @@ fn validate_live_interrupted_upgrade(commitstates: &CommitStates) -> Result<Upda
assert!(!firstdeploy.booted); assert!(!firstdeploy.booted);
validate_pending_commit(pending_commit, &commitstates)?; validate_pending_commit(pending_commit, &commitstates)?;
UpdateResult::Staged UpdateResult::Staged
} else if pending_commit == commitstates.booted {
UpdateResult::NotCompleted
} else if pending_commit == commitstates.target {
UpdateResult::Completed
} else { } else {
if pending_commit == commitstates.booted { anyhow::bail!(
UpdateResult::NotCompleted "Unexpected pending commit: {} ({:?})",
} else if pending_commit == commitstates.target { pending_commit,
UpdateResult::Completed commitstates.describe(pending_commit)
} else { );
anyhow::bail!(
"Unexpected pending commit: {} ({:?})",
pending_commit,
commitstates.describe(pending_commit)
);
}
}; };
Ok(res) Ok(res)
} }
@ -504,7 +499,7 @@ fn impl_transaction_test<M: AsRef<str>>(
live_strategy = Some(strategy); live_strategy = Some(strategy);
} }
InterruptStrategy::Force(ForceInterruptStrategy::Reboot) => { InterruptStrategy::Force(ForceInterruptStrategy::Reboot) => {
mark.reboot_strategy = Some(strategy.clone()); mark.reboot_strategy = Some(strategy);
prepare_reboot(serde_json::to_string(&mark)?)?; prepare_reboot(serde_json::to_string(&mark)?)?;
// This is a forced reboot - no syncing of the filesystem. // This is a forced reboot - no syncing of the filesystem.
bash!("reboot -ff")?; bash!("reboot -ff")?;
@ -516,8 +511,8 @@ fn impl_transaction_test<M: AsRef<str>>(
anyhow::bail!("Failed to wait for uninterrupted upgrade"); anyhow::bail!("Failed to wait for uninterrupted upgrade");
} }
InterruptStrategy::Polite(PoliteInterruptStrategy::Reboot) => { InterruptStrategy::Polite(PoliteInterruptStrategy::Reboot) => {
mark.reboot_strategy = Some(strategy.clone()); mark.reboot_strategy = Some(strategy);
Err(reboot(serde_json::to_string(&mark)?))?; return Err(reboot(serde_json::to_string(&mark)?).into());
// We either rebooted, or failed to reboot // We either rebooted, or failed to reboot
} }
InterruptStrategy::Polite(PoliteInterruptStrategy::Stop) => { InterruptStrategy::Polite(PoliteInterruptStrategy::Stop) => {
@ -545,7 +540,7 @@ fn transactionality() -> Result<()> {
// We need this static across reboots // We need this static across reboots
let srvrepo = Path::new(SRVREPO); let srvrepo = Path::new(SRVREPO);
let firstrun = !srvrepo.exists(); let firstrun = !srvrepo.exists();
if let Some(_) = mark.as_ref() { if mark.as_ref().is_some() {
if firstrun { if firstrun {
anyhow::bail!("Missing {:?}", srvrepo); anyhow::bail!("Missing {:?}", srvrepo);
} }
@ -604,7 +599,7 @@ fn transactionality() -> Result<()> {
let end = time::Instant::now(); let end = time::Instant::now();
let cycle_time = end.duration_since(start); let cycle_time = end.duration_since(start);
let tdata = TransactionalTestInfo { let tdata = TransactionalTestInfo {
cycle_time: cycle_time, cycle_time,
}; };
let mut f = std::io::BufWriter::new(std::fs::File::create(&TDATAPATH)?); let mut f = std::io::BufWriter::new(std::fs::File::create(&TDATAPATH)?);
serde_json::to_writer(&mut f, &tdata)?; serde_json::to_writer(&mut f, &tdata)?;

View File

@ -8,10 +8,11 @@ mod test;
mod treegen; mod treegen;
// Written by Ignition // Written by Ignition
const DESTRUCTIVE_TEST_STAMP: &'static str = "/etc/ostree-destructive-test-ok"; const DESTRUCTIVE_TEST_STAMP: &str = "/etc/ostree-destructive-test-ok";
#[derive(Debug, StructOpt)] #[derive(Debug, StructOpt)]
#[structopt(rename_all = "kebab-case")] #[structopt(rename_all = "kebab-case")]
#[allow(clippy::enum_variant_names)]
/// Main options struct /// Main options struct
enum Opt { enum Opt {
/// List the destructive tests /// List the destructive tests
@ -74,13 +75,11 @@ fn main() -> Result<()> {
for t in test::DESTRUCTIVE_TESTS.iter() { for t in test::DESTRUCTIVE_TESTS.iter() {
println!("{}", t.name); println!("{}", t.name);
} }
return Ok(()); Ok(())
} }
Opt::NonDestructive(subopt) => { Opt::NonDestructive(subopt) => {
// FIXME add method to parse subargs // FIXME add method to parse subargs
let iter = match subopt { let NonDestructiveOpts::Args(iter) = subopt;
NonDestructiveOpts::Args(subargs) => subargs,
};
let libtestargs = libtest_mimic::Arguments::from_iter(iter); let libtestargs = libtest_mimic::Arguments::from_iter(iter);
let tests: Vec<_> = test::NONDESTRUCTIVE_TESTS let tests: Vec<_> = test::NONDESTRUCTIVE_TESTS
.iter() .iter()

View File

@ -41,7 +41,7 @@ pub(crate) fn cmd_fails_with<C: BorrowMut<Command>>(mut c: C, pat: &str) -> Resu
if o.status.success() { if o.status.success() {
bail!("Command {:?} unexpectedly succeeded", c); bail!("Command {:?} unexpectedly succeeded", c);
} }
if !twoway::find_bytes(&o.stderr, pat.as_bytes()).is_some() { if twoway::find_bytes(&o.stderr, pat.as_bytes()).is_none() {
dbg!(String::from_utf8_lossy(&o.stdout)); dbg!(String::from_utf8_lossy(&o.stdout));
dbg!(String::from_utf8_lossy(&o.stderr)); dbg!(String::from_utf8_lossy(&o.stderr));
bail!("Command {:?} stderr did not match: {}", c, pat); bail!("Command {:?} stderr did not match: {}", c, pat);
@ -56,7 +56,7 @@ pub(crate) fn cmd_has_output<C: BorrowMut<Command>>(mut c: C, pat: &str) -> Resu
if !o.status.success() { if !o.status.success() {
bail!("Command {:?} failed", c); bail!("Command {:?} failed", c);
} }
if !twoway::find_bytes(&o.stdout, pat.as_bytes()).is_some() { if twoway::find_bytes(&o.stdout, pat.as_bytes()).is_none() {
dbg!(String::from_utf8_lossy(&o.stdout)); dbg!(String::from_utf8_lossy(&o.stdout));
bail!("Command {:?} stdout did not match: {}", c, pat); bail!("Command {:?} stdout did not match: {}", c, pat);
} }
@ -77,12 +77,12 @@ pub(crate) struct TestHttpServerOpts {
pub(crate) random_delay: Option<time::Duration>, pub(crate) random_delay: Option<time::Duration>,
} }
pub(crate) const TEST_HTTP_BASIC_AUTH: &'static str = "foouser:barpw"; pub(crate) const TEST_HTTP_BASIC_AUTH: &str = "foouser:barpw";
fn validate_authz(value: &[u8]) -> Result<bool> { fn validate_authz(value: &[u8]) -> Result<bool> {
let buf = std::str::from_utf8(&value)?; let buf = std::str::from_utf8(&value)?;
if let Some(o) = buf.find("Basic ") { if let Some(o) = buf.find("Basic ") {
let (_, buf) = buf.split_at(o + "Basic ".len()); let (_, buf) = buf.split_at(o + "Basic ".len());
let buf = base64::decode(buf).context("decoding")?; let buf = base64::decode(buf).context("decoding")?;
let buf = std::str::from_utf8(&buf)?; let buf = std::str::from_utf8(&buf)?;
Ok(buf == TEST_HTTP_BASIC_AUTH) Ok(buf == TEST_HTTP_BASIC_AUTH)
@ -136,7 +136,6 @@ pub(crate) async fn http_server<P: AsRef<Path>>(
let make_service = make_service_fn(move |_| { let make_service = make_service_fn(move |_| {
let sv = sv.clone(); let sv = sv.clone();
let opts = opts.clone();
future::ok::<_, hyper::Error>(service_fn(move |req| handle_request(req, sv.clone(), opts))) future::ok::<_, hyper::Error>(service_fn(move |req| handle_request(req, sv.clone(), opts)))
}); });
let server: hyper::Server<_, _, _> = hyper::Server::bind(&addr).serve(make_service); let server: hyper::Server<_, _, _> = hyper::Server::bind(&addr).serve(make_service);
@ -161,7 +160,7 @@ where
let path = path.as_ref(); let path = path.as_ref();
let mut rt = Runtime::new()?; let mut rt = Runtime::new()?;
rt.block_on(async move { rt.block_on(async move {
let addr = http_server(path, opts.clone()).await?; let addr = http_server(path, *opts).await?;
tokio::task::spawn_blocking(move || f(&addr)).await? tokio::task::spawn_blocking(move || f(&addr)).await?
})?; })?;
Ok(()) Ok(())