Skip to content

Add tests for license expression validation #4292

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Dec 18, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 28 additions & 11 deletions src/models/version.rs
Original file line number Diff line number Diff line change
Expand Up @@ -177,16 +177,7 @@ impl NewVersion {

fn validate_license(&mut self, license_file: Option<&str>) -> AppResult<()> {
if let Some(ref license) = self.license {
for part in license.split('/') {
license_exprs::validate_license_expr(part).map_err(|e| {
cargo_err(&format_args!(
"{}; see http://opensource.org/licenses \
for options, and http://spdx.org/licenses/ \
for their identifiers",
e
))
})?;
}
validate_license_expr(license)?;
} else if license_file.is_some() {
// If no license is given, but a license file is given, flag this
// crate as having a nonstandard license. Note that we don't
Expand All @@ -197,9 +188,19 @@ impl NewVersion {
}
}

fn validate_license_expr(s: &str) -> AppResult<()> {
for part in s.split('/') {
license_exprs::validate_license_expr(part).map_err(|e| {
cargo_err(&format_args!("{}; see http://opensource.org/licenses for options, and http://spdx.org/licenses/ for their identifiers", e))
})?;
}

Ok(())
}

#[cfg(test)]
mod tests {
use super::TopVersions;
use super::{validate_license_expr, TopVersions};
use chrono::NaiveDateTime;

#[track_caller]
Expand Down Expand Up @@ -269,4 +270,20 @@ mod tests {
}
);
}

#[test]
fn licenses() {
assert_ok!(validate_license_expr("MIT"));
assert_ok!(validate_license_expr("MIT OR Apache-2.0"));
assert_ok!(validate_license_expr("MIT/Apache-2.0"));
assert_ok!(validate_license_expr("MIT AND Apache-2.0"));

let error = assert_err!(validate_license_expr("apache 2.0"));
let error = format!("{}", error);
assert!(error.starts_with("unknown license or other term: apache; see http"));

let error = assert_err!(validate_license_expr("MIT OR (Apache-2.0 AND MIT)"));
let error = format!("{}", error);
assert!(error.starts_with("unknown license or other term: (Apache-2.0; see http"));
}
}