[red-knot] Add a test to ensure that KnownClass::try_from_file_and_name() is kept up to date (#16326)

This commit is contained in:
Alex Waygood 2025-02-24 12:14:20 +00:00 committed by GitHub
parent 320a3c68ae
commit 5bac4f6bd4
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
6 changed files with 145 additions and 64 deletions

View file

@ -1,4 +1,5 @@
use std::fmt::Formatter;
use std::str::FromStr;
use std::sync::Arc;
use ruff_db::files::File;
@ -98,10 +99,13 @@ impl ModuleKind {
}
/// Enumeration of various core stdlib modules in which important types are located
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, strum_macros::EnumString)]
#[cfg_attr(test, derive(strum_macros::EnumIter))]
#[strum(serialize_all = "snake_case")]
pub enum KnownModule {
Builtins,
Types,
#[strum(serialize = "_typeshed")]
Typeshed,
TypingExtensions,
Typing,
@ -139,21 +143,10 @@ impl KnownModule {
search_path: &SearchPath,
name: &ModuleName,
) -> Option<Self> {
if !search_path.is_standard_library() {
return None;
}
match name.as_str() {
"builtins" => Some(Self::Builtins),
"types" => Some(Self::Types),
"typing" => Some(Self::Typing),
"_typeshed" => Some(Self::Typeshed),
"typing_extensions" => Some(Self::TypingExtensions),
"sys" => Some(Self::Sys),
"abc" => Some(Self::Abc),
"collections" => Some(Self::Collections),
"inspect" => Some(Self::Inspect),
"knot_extensions" => Some(Self::KnotExtensions),
_ => None,
if search_path.is_standard_library() {
Self::from_str(name.as_str()).ok()
} else {
None
}
}
@ -168,4 +161,29 @@ impl KnownModule {
pub const fn is_knot_extensions(self) -> bool {
matches!(self, Self::KnotExtensions)
}
pub const fn is_inspect(self) -> bool {
matches!(self, Self::Inspect)
}
}
#[cfg(test)]
mod tests {
use super::*;
use strum::IntoEnumIterator;
#[test]
fn known_module_roundtrip_from_str() {
let stdlib_search_path = SearchPath::vendored_stdlib();
for module in KnownModule::iter() {
let module_name = module.name();
assert_eq!(
KnownModule::try_from_search_path_and_name(&stdlib_search_path, &module_name),
Some(module),
"The strum `EnumString` implementation appears to be incorrect for `{module_name}`"
);
}
}
}