我可以为无效的生命周期编写测试吗? [英] Can I write tests for invalid lifetimes?

查看:66
本文介绍了我可以为无效的生命周期编写测试吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一些操作原始指针的 Rust 代码.这些原始指针然后通过使用 ContravariantLifetime 将结构的生命周期到我的对象.

I'm writing some Rust code that manipulates raw pointers. These raw pointers are then exposed to users through structures that use ContravariantLifetime to tie the lifetime of the struct to my object.

我希望能够编写测试来验证面向用户的结构不能比我的对象寿命更长.我有如下代码:

I'd like to be able to write tests that validate that the user-facing structures cannot live longer than my object. I have code like the following:

fn element_cannot_outlive_parts() {
    let mut z = {
         let p = Package::new();
         p.create() // returns an object that cannot live longer than p
    };
 }

这无法编译,这正是我想要的.但是,即使在我对代码进行任何重构之后,我也希望自动检查这种行为是否正确.

This fails to compile, which is exactly what I want. However, I'd like to have some automated check that this behavior is true even after whatever refactoring I do to the code.

我目前最好的想法是用这段代码编写一次性的 Rust 文件并装配 bash 脚本来尝试编译它们并查找特定的错误消息,这一切都感觉很hacky.

My best idea at the moment is to write one-off Rust files with this code and rig up bash scripts to attempt to compile them and look for specific error messages, which all feels pretty hacky.

推荐答案

Rust 项目有一组特殊的测试,称为编译失败"测试,它们完全符合您的要求.

The Rust project has a special set of tests called "compile-fail" tests that do exactly what you want.

compiletest crate 是这个想法的提取,它允许其他库做同样的事情:

The compiletest crate is an extraction of this idea that allows other libraries to do the same thing:

fn main() {
    let x: (u64, bool) = (true, 42u64);
    //~^ ERROR mismatched types
    //~^^ ERROR mismatched types
}

<小时>

半途而废的一个想法是使用 Cargo 的功能".


One idea that gets halfway there is to use Cargo's "features".

使用功能标志指定测试:

Specify tests with a feature flag:

#[test]
#[cfg(feature = "compile_failure")]
fn bogus_test() {}

将此添加到 Cargo.toml:

Add this to Cargo.toml:

[features]

compile_failure = []

并运行测试

cargo test --features compile_failure

明显缺少的是自动检查它是否是正确的失败".如果不出意外,这允许我在我的代码库中进行半实时测试.

The obvious thing missing from this is the automatic checking of "was it the right failure". If nothing else, this allows me to have tests that are semi-living in my codebase.

这篇关于我可以为无效的生命周期编写测试吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆