Skip to content
Open
Show file tree
Hide file tree
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
1 change: 1 addition & 0 deletions pyrefly/lib/alt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ pub mod nn_module_specials;
pub mod operators;
pub mod overload;
pub mod polars_specials;
pub mod pytest;
pub mod regex;
pub mod regular_nested_list;
pub mod shape_declarations;
Expand Down
20 changes: 17 additions & 3 deletions pyrefly/lib/alt/function.rs
Original file line number Diff line number Diff line change
Expand Up @@ -590,6 +590,7 @@ impl<'ctx, 'answer, Ans: LookupAnswer> AnswersSolver<'ctx, 'answer, Ans> {
calls_super_method,
..Default::default()
};
let pytest_param_hints = self.pytest_parametrize_parameter_types(decorators, errors);
let mut found_class_property = false;
let decorators =
Box::from_iter(decorators.iter().enumerate().filter_map(|(position, k)| {
Expand Down Expand Up @@ -826,6 +827,7 @@ impl<'ctx, 'answer, Ans: LookupAnswer> AnswersSolver<'ctx, 'answer, Ans> {
flags.facts().is_stub(),
&mut self_type,
&mut decorator_param_hints,
&pytest_param_hints,
&mut parent_param_hints,
errors,
);
Expand Down Expand Up @@ -1688,6 +1690,7 @@ impl<'ctx, 'answer, Ans: LookupAnswer> AnswersSolver<'ctx, 'answer, Ans> {
is_stub: bool,
self_type: &mut Option<Type>,
decorator_param_hints: &mut Option<DecoratorParamHints>,
pytest_param_hints: &SmallMap<Name, Type>,
parent_param_hints: &mut Option<ParentParamHints>,
errors: &ErrorCollector,
) -> FunctionParamsResult {
Expand Down Expand Up @@ -1715,7 +1718,11 @@ impl<'ctx, 'answer, Ans: LookupAnswer> AnswersSolver<'ctx, 'answer, Ans> {
x.default.as_deref(),
is_stub,
self_type,
decorator_hint.or(parent_hint),
pytest_param_hints
.get(&x.parameter.name.id)
.cloned()
.or(decorator_hint)
.or(parent_hint),
errors,
);
if is_unannotated {
Expand Down Expand Up @@ -1749,7 +1756,11 @@ impl<'ctx, 'answer, Ans: LookupAnswer> AnswersSolver<'ctx, 'answer, Ans> {
x.default.as_deref(),
is_stub,
self_type,
decorator_hint.or(parent_hint),
pytest_param_hints
.get(&x.parameter.name.id)
.cloned()
.or(decorator_hint)
.or(parent_hint),
errors,
);
if is_unannotated {
Expand Down Expand Up @@ -1830,7 +1841,10 @@ impl<'ctx, 'answer, Ans: LookupAnswer> AnswersSolver<'ctx, 'answer, Ans> {
x.default.as_deref(),
is_stub,
self_type,
parent_hint,
pytest_param_hints
.get(&x.parameter.name.id)
.cloned()
.or(parent_hint),
errors,
);
if is_unannotated {
Expand Down
60 changes: 60 additions & 0 deletions pyrefly/lib/alt/pytest.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

use dupe::Dupe;
use pyrefly_graph::index::Idx;
use ruff_python_ast::name::Name;
use starlark_map::small_map::SmallMap;

use crate::alt::answers::LookupAnswer;
use crate::alt::answers_solver::AnswersSolver;
use crate::binding::binding::KeyDecorator;
use crate::binding::pytest::PytestParametrization;
use crate::error::collector::ErrorCollector;
use crate::types::types::Type;

impl<'ctx, 'answer, Ans: LookupAnswer> AnswersSolver<'ctx, 'answer, Ans> {
/// Infer parameter types only from rows that supply values directly.
pub(super) fn pytest_parametrize_parameter_types(
&self,
decorators: &[Idx<KeyDecorator>],
errors: &ErrorCollector,
) -> SmallMap<Name, Type> {
let mut columns: SmallMap<Name, Vec<Type>> = SmallMap::new();
if let Some(pytest_info) = self.bindings().pytest_info() {
let aliases = pytest_info.aliases();
let hint_errors = ErrorCollector::new(errors.module().dupe(), errors.style());
for key in decorators {
let binding = self.bindings().get::<KeyDecorator>(*key);
let Some(parametrization) = PytestParametrization::parse(&binding.expr, aliases)
else {
continue;
};
if parametrization.direct_parameters().next().is_none() {
continue;
}
let Some(rows) = parametrization.rows(aliases) else {
continue;
};
if rows.is_empty() {
continue;
}
for (index, name) in parametrization.direct_parameters() {
let column = columns.entry(name.clone()).or_default();
column.extend(rows.iter().map(|row| {
self.expr_infer(&row[index], &hint_errors)
.promote(self.stdlib)
}));
}
}
}
columns
.into_iter()
.map(|(name, types)| (name, self.unions(types)))
.collect()
}
}
129 changes: 127 additions & 2 deletions pyrefly/lib/binding/pytest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
* LICENSE file in the root directory of this source tree.
*/

use std::slice;

use pyrefly_graph::index::Idx;
use pyrefly_python::short_identifier::ShortIdentifier;
use ruff_python_ast::Expr;
Expand All @@ -23,6 +25,7 @@ pub struct PytestAliases {
pytest_module_aliases: Vec<String>,
fixture_aliases: Vec<String>,
mark_aliases: Vec<String>,
param_aliases: Vec<String>,
}

impl PytestAliases {
Expand Down Expand Up @@ -62,6 +65,9 @@ impl PytestAliases {
} else if module.id == "pytest" && alias.name.id == "mark" {
let local_name = alias.asname.as_ref().unwrap_or(&alias.name);
aliases.mark_aliases.push(local_name.id.to_string());
} else if module.id == "pytest" && alias.name.id == "param" {
let local_name = alias.asname.as_ref().unwrap_or(&alias.name);
aliases.param_aliases.push(local_name.id.to_string());
}
}
}
Expand All @@ -72,7 +78,10 @@ impl PytestAliases {
}

pub fn is_empty(&self) -> bool {
self.pytest_module_aliases.is_empty() && self.fixture_aliases.is_empty()
self.pytest_module_aliases.is_empty()
&& self.fixture_aliases.is_empty()
&& self.mark_aliases.is_empty()
&& self.param_aliases.is_empty()
}

fn is_pytest_module_alias(&self, name: &Name) -> bool {
Expand All @@ -88,7 +97,7 @@ impl PytestAliases {
}

/// Recognize parametrization through pytest module and mark aliases.
pub(crate) fn is_parametrize(&self, expr: &Expr) -> bool {
fn is_parametrize(&self, expr: &Expr) -> bool {
let Expr::Attribute(attr) = expr else {
return false;
};
Expand All @@ -104,6 +113,122 @@ impl PytestAliases {
_ => false,
}
}

fn is_param(&self, expr: &Expr) -> bool {
match expr {
Expr::Name(name) => self
.param_aliases
.iter()
.any(|alias| alias == name.id.as_str()),
Expr::Attribute(attr) if attr.attr.id == "param" => {
matches!(attr.value.as_ref(), Expr::Name(name) if self.is_pytest_module_alias(name.id()))
}
_ => false,
}
}
}

/// A parsed parametrization separates direct values from fixture inputs.
pub(crate) struct PytestParametrization<'a> {
names: Vec<Name>,
indirect: Vec<Name>,
values: &'a Expr,
single_value: bool,
}

impl<'a> PytestParametrization<'a> {
pub(crate) fn parse(expr: &'a Expr, aliases: &PytestAliases) -> Option<Self> {
let Expr::Call(call) = expr else {
return None;
};
if !aliases.is_parametrize(&call.func)
|| call
.arguments
.args
.iter()
.any(|arg| matches!(arg, Expr::Starred(_)))
|| call.arguments.keywords.iter().any(|kw| kw.arg.is_none())
{
return None;
}
let argnames = call.arguments.find_argument_value("argnames", 0)?;
let names = parametrize_names(argnames)?;
let values = call.arguments.find_argument_value("argvalues", 1)?;
let indirect = match call.arguments.find_argument_value("indirect", 2) {
None => Vec::new(),
Some(Expr::BooleanLiteral(value)) if !value.value => Vec::new(),
Some(Expr::BooleanLiteral(_)) => names.clone(),
Some(expr @ (Expr::List(_) | Expr::Tuple(_))) => parametrize_names(expr)?,
_ => return None,
};
let single_value = matches!(argnames, Expr::StringLiteral(_)) && names.len() == 1;
Some(Self {
names,
indirect,
values,
single_value,
})
}

pub(crate) fn direct_parameters(&self) -> impl Iterator<Item = (usize, &Name)> {
self.names
.iter()
.enumerate()
.filter(|(_, name)| !self.indirect.contains(name))
}

/// Return complete rows, or skip inference when a row cannot be interpreted safely.
pub(crate) fn rows(&self, aliases: &PytestAliases) -> Option<Vec<&'a [Expr]>> {
let rows = match self.values {
Expr::List(list) => &list.elts,
Expr::Tuple(tuple) => &tuple.elts,
_ => return None,
};
rows.iter()
.map(|row| {
let values = match row {
Expr::Call(call) if aliases.is_param(&call.func) => {
call.arguments.args.as_ref()
}
Expr::Starred(_) => return None,
_ if self.single_value => slice::from_ref(row),
Expr::Tuple(tuple) => &tuple.elts,
Expr::List(list) => &list.elts,
_ => return None,
};
(values.len() == self.names.len()
&& !values.iter().any(|value| matches!(value, Expr::Starred(_))))
.then_some(values)
})
.collect()
}
}

fn parametrize_names(expr: &Expr) -> Option<Vec<Name>> {
let elts = match expr {
Expr::StringLiteral(lit) => {
let names = lit
.value
.to_str()
.split(',')
.map(str::trim)
.filter(|name| !name.is_empty())
.map(Name::new)
.collect::<Vec<_>>();
return (!names.is_empty()).then_some(names);
}
Expr::Tuple(tuple) => &tuple.elts,
Expr::List(list) => &list.elts,
_ => return None,
};
elts.iter()
.map(|elt| match elt {
Expr::StringLiteral(lit) if !lit.value.to_str().is_empty() => {
Some(Name::new(lit.value.to_str()))
}
_ => None,
})
.collect()
}

#[derive(Clone, Debug)]
Expand Down
42 changes: 8 additions & 34 deletions pyrefly/lib/state/pytest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ use crate::binding::binding::KeyClass;
use crate::binding::bindings::Bindings;
use crate::binding::pytest::PytestAliases;
use crate::binding::pytest::PytestBindingInfo;
use crate::binding::pytest::PytestParametrization;
use crate::binding::pytest::is_pytest_fixture_decorator;

#[derive(Clone, Debug)]
Expand Down Expand Up @@ -345,24 +346,6 @@ pub(crate) fn collect_pytest_fixture_definitions(stmts: &[Stmt]) -> Vec<PytestFi
.collect()
}

fn parametrize_names_contain(expr: &Expr, name: &Name) -> bool {
let values = match expr {
Expr::StringLiteral(value) => {
return value
.value
.to_str()
.split(',')
.any(|part| part.trim() == name.as_str());
}
Expr::List(list) => &list.elts,
Expr::Tuple(tuple) => &tuple.elts,
_ => return false,
};
values.iter().any(|value| {
matches!(value, Expr::StringLiteral(value) if value.value.to_str() == name.as_str())
})
}

/// Direct parametrization supplies values instead of requesting a fixture.
pub(crate) fn is_directly_parametrized(
module: &ModModule,
Expand All @@ -383,22 +366,13 @@ pub(crate) fn is_directly_parametrized(
}
let aliases = PytestAliases::from_module(module);
decorators.any(|decorator| {
let Expr::Call(call) = &decorator.expression else {
return false;
};
if !aliases.is_parametrize(&call.func) {
return false;
}
let argnames = call.arguments.find_argument_value("argnames", 0);
if !argnames.is_some_and(|argnames| parametrize_names_contain(argnames, name)) {
return false;
}
match call.arguments.find_argument_value("indirect", 2) {
None => true,
Some(Expr::BooleanLiteral(value)) => !value.value,
Some(expr @ (Expr::List(_) | Expr::Tuple(_))) => !parametrize_names_contain(expr, name),
_ => false,
}
PytestParametrization::parse(&decorator.expression, &aliases).is_some_and(
|parametrization| {
parametrization
.direct_parameters()
.any(|(_, parameter)| parameter == name)
},
)
})
}

Expand Down
Loading
Loading