AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • 主页
  • 系统&网络
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • 主页
  • 系统&网络
    • 最新
    • 热门
    • 标签
  • Ubuntu
    • 最新
    • 热门
    • 标签
  • Unix
    • 最新
    • 标签
  • DBA
    • 最新
    • 标签
  • Computer
    • 最新
    • 标签
  • Coding
    • 最新
    • 标签
主页 / coding / 问题 / 79014832
Accepted
Skru
Skru
Asked: 2024-09-23 21:30:47 +0800 CST2024-09-23 21:30:47 +0800 CST 2024-09-23 21:30:47 +0800 CST

如何在 Rust 测试期间模拟其他模块的私有结构

  • 772

我有一个包含多个域的应用程序,这些域具有不同的职责。我在下面添加了一个简化的工作示例。

该User结构由域拥有auth。其字段和new()构造函数是该域私有的。其他域只能使用域服务作为接口来获取用户。

域函数blog需要User作为输入参数(get_posts_by_user()在示例中),或者它们需要调用域函数auth(get_posts_by_user_id()在示例中)。为了测试这些函数,我需要创建实例,User而不使用需要数据库的实际AuthService实现。相反,我想模拟并让模拟返回我需要测试AuthService的任何边缘情况。User

User 和 Blog 只是示例。实际上,我可能会遇到数十个这样的域私有类型的案例。我正在为所有这些案例寻找类似的解决方案。

我想到了几种解决这个问题的方法,但没有一种能让我信服:

  • 使所有字段User公开,或使构造函数new()公开。
    • 缺点:所有其他域都能够创建经过身份验证的用户,这些用户可能会(意外)被滥用,并可能在以后产生安全问题
  • 在身份验证域中创建一个公共模拟,为用户实现自己的构造函数
    • User缺点:这意味着构造函数的代码部分重复。维护成本更高,因为每次更改时模拟构造函数也需要更新
  • 复制结构以#[cfg(test)]使字段仅在测试期间公开
    • 缺点:代码重复,普通模式和测试模式有不同的行为
    • 这是我在下面的片段中使用的替代方案。
    • 也许可以通过宏自动化
  • 使用一些库
    • 缺点:我还没有找到适合这种情况的有用的库

是否有一些最佳实践来模拟和测试这种情况?

Rust 游乐场

// Authentication domain
pub mod auth {
    // The User struct is constructed by this domain when a user is successfully
    // authenticated
    // private fields, used in production
    #[cfg(not(test))]
    #[derive(Clone, Debug)]
    pub struct User {
        user_id: i32,
        username: String,
    }

    // all fields public, used only in tests
    #[cfg(test)]
    #[derive(Clone, Debug)]
    pub struct User {
        pub user_id: i32,
        pub username: String,
    }

    impl User {
        // new() is private because no other domain should be able to construct a User.
        fn new(user_id: i32, username: String) -> User {
            User { user_id, username }
        }

        // Public read-only access to user id
        pub fn user_id(&self) -> i32 {
            self.user_id
        }

        // Public read-only access to username
        pub fn username(&self) -> &str {
            &self.username
        }
    }

    // Abstraction via trait to decouple services and to allow creation of mocks
    // for easier unit testing
    pub trait AuthService {
        fn get_user(&self, user_id: i32) -> User;
    }

    #[derive(Clone, Debug)]
    pub struct AuthImpl;

    // Implementation of AuthService
    impl AuthService for AuthImpl {
        fn get_user(&self, user_id: i32) -> User {
            // DB access and complex calculations to authenticae user
            std::thread::sleep(std::time::Duration::from_millis(2000));
            User::new(
                user_id,
                vec!["Alice", "Bob", "Claire", "Daniel"]
                    .get(user_id as usize % 4)
                    .unwrap()
                    .to_string(),
            )
        }
    }

    #[cfg(test)]
    mod tests {
        // omitted
    }
}

// Blog domain
pub mod blog {
    use crate::auth::{AuthService, User};

    // Trait for blog service that needs access to the user or to the auth domain
    pub trait BlogService {
        fn get_posts_by_user(&self, user: &User) -> Vec<String>;
        fn get_posts_by_user_id(&self, auth: impl AuthService, user_id: i32) -> Vec<String>;
    }

    #[derive(Clone, Debug)]
    pub struct BlogImpl;

    impl BlogService for BlogImpl {
        // The User from the auth domain is needed as input here.
        // During testing this should be moked
        fn get_posts_by_user(&self, user: &User) -> Vec<String> {
            // this would be some call to the data storage
            vec![format!(
                "Hi, my name is {} (id: {})",
                user.username(),
                user.user_id()
            )]
        }

        // A call to AuthService is needed here to authenticate the user.
        // During testing this should be mocked
        fn get_posts_by_user_id(&self, auth: impl AuthService, user_id: i32) -> Vec<String> {
            let user = auth.get_user(user_id);
            // this would be some call to the data storage
            vec![format!(
                "Hi, my name is {} (id: {})",
                user.username(),
                user.user_id()
            )]
        }
    }

    // Unittest the service
    #[cfg(test)]
    mod tests {
        use crate::auth::{AuthService, User};

        use super::*;

        // Mock of AuthService to test BlogService
        #[derive(Clone, Debug)]
        struct AuthMock {
            // Mocked value for User. But user is private in auth domain. How to mock it here?
            pub user: User,
        }

        impl AuthService for AuthMock {
            fn get_user(&self, _user_id: i32) -> User {
                self.user.clone()
            }
        }

        #[test]
        fn test_get_posts_by_user() {
            let blog = BlogImpl;
            // User is private in auth domain. What is the best way to mock it here?
            let user = User {
                user_id: 42,
                username: "Dummy".to_string(),
            };
            let posts = blog.get_posts_by_user(&user);
            assert_eq!(posts, vec!["Hi, my name is Dummy (id: 42)"]);
        }

        #[test]
        fn test_get_posts_by_user_id() {
            let blog = BlogImpl;
            let auth_mock = AuthMock {
                // User is private in auth domain. What is the best way to mock it here?
                user: User {
                    user_id: 1337,
                    username: "Admin".to_string(),
                },
            };
            let posts = blog.get_posts_by_user_id(auth_mock, 1);
            assert_eq!(posts, vec!["Hi, my name is Admin (id: 1337)"]);
        }
    }
}

use crate::auth::{AuthImpl, AuthService};
use crate::blog::{BlogImpl, BlogService};

fn main() {
    let auth = AuthImpl;
    let blog = BlogImpl;

    let now = std::time::SystemTime::now();
    println!("{} ms", now.elapsed().unwrap().as_millis());

    // get user form auth domain
    println!("User: {:?}", auth.get_user(123));
    println!("{} ms", now.elapsed().unwrap().as_millis());

    println!("Posts by user: {:?}", blog.get_posts_by_user(&auth.get_user(1234)));
    println!("{} ms", now.elapsed().unwrap().as_millis());

    println!("Posts by user id: {:?}", blog.get_posts_by_user_id(auth, 12345));
    println!("{} ms", now.elapsed().unwrap().as_millis());
}
unit-testing
  • 1 1 个回答
  • 34 Views

1 个回答

  • Voted
  1. Best Answer
    啊鹿Dizzyi
    2024-09-24T00:06:52+08:002024-09-24T00:06:52+08:00

    如果你在测试环境中暴露一个test_new包裹函数的函数会怎么样new

    这样你就不需要重新定义结构,不需要重新定义new()

    /// crate::auth
    impl User {
        fn new(user_id: i32, username: String) -> User {
            User { user_id, username }
        }
    
        #[cfg(test)]
        pub fn test_new(user_id: i32, username: String) -> User {
            User::new(user_id, username)
        }
    }
    
    /// crate::blog::test
    #[test]
    fn test_get_posts_by_user() {
        let blog = BlogImpl;
        let user = User::test_new(
            42,
            "Dummy".to_string()
        );
        let posts = blog.get_posts_by_user(&user);
        assert_eq!(posts, vec!["Hi, my name is Dummy (id: 42)"]);
    }
    

    编辑

    宏

    对于更通用的方法,使用 proc-macro 来根据它是否是测试环境来改变可见性。

    像这样:

    #[cfg(not(test))]
    fn a(){}
    #[cfg(test)]
    pub fn a(){}
    
    extern crate proc_macro;
    use proc_macro::TokenStream;
    use quote::quote;
    use syn::{parse_macro_input, ItemFn};
    
    #[proc_macro_attribute]
    pub fn pub_on_test(_attr: TokenStream, item: TokenStream) -> TokenStream {
        let ItemFn {
            sig,
            vis,
            block,
            attrs,
        } = parse_macro_input!(item as ItemFn);
    
        quote!(
            #(#attrs)*
            #[cfg(not(test))]
            #vis #sig #block
            #(#attrs)*
            #[cfg(test)]
            pub #sig #block
        )
        .into()
    }
    

    用法

    pub mod auth {
        use my_macros::pub_on_test;
    
        //... 
        impl User {
            #[pub_on_test]
            fn new(user_id: i32, username: String) -> User {
                User { user_id, username }
            }
    
        // ...
        }
    }
    

    扩展

    cargo expand
    
    mod auth{
        // ...
        impl User {
            #[cfg(not(test))]
            fn new(user_id: i32, username: String) -> User {
                User { user_id, username }
            }
            // ...
        }
    }
    
    cargo expand --tests
    
    mod auth{
        // ...
        impl User{
            #[cfg(test)]
            pub fn new(user_id: i32, username: String) -> User {
                User { user_id, username }
            }
        // ...
        }
    }
    
    • 1

相关问题

  • 如何对 multipart.Form 进行单元测试

  • 为什么测试日期在 localhost 中通过但在 Azure 管道中失败?

  • Test2::Mock 发出“原型不匹配”警告

  • jest.spyOn 似乎没有正确模拟默认导出函数

  • 如何比较 kdb/Q 中的两个值并根据通过/失败输出消息?

Sidebar

Stats

  • 问题 205573
  • 回答 270741
  • 最佳答案 135370
  • 用户 68524
  • 热门
  • 回答
  • Marko Smith

    Vue 3:创建时出错“预期标识符但发现‘导入’”[重复]

    • 1 个回答
  • Marko Smith

    为什么这个简单而小的 Java 代码在所有 Graal JVM 上的运行速度都快 30 倍,但在任何 Oracle JVM 上却不行?

    • 1 个回答
  • Marko Smith

    具有指定基础类型但没有枚举器的“枚举类”的用途是什么?

    • 1 个回答
  • Marko Smith

    如何修复未手动导入的模块的 MODULE_NOT_FOUND 错误?

    • 6 个回答
  • Marko Smith

    `(表达式,左值) = 右值` 在 C 或 C++ 中是有效的赋值吗?为什么有些编译器会接受/拒绝它?

    • 3 个回答
  • Marko Smith

    何时应使用 std::inplace_vector 而不是 std::vector?

    • 3 个回答
  • Marko Smith

    在 C++ 中,一个不执行任何操作的空程序需要 204KB 的堆,但在 C 中则不需要

    • 1 个回答
  • Marko Smith

    PowerBI 目前与 BigQuery 不兼容:Simba 驱动程序与 Windows 更新有关

    • 2 个回答
  • Marko Smith

    AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String”

    • 1 个回答
  • Marko Smith

    我正在尝试仅使用海龟随机和数学模块来制作吃豆人游戏

    • 1 个回答
  • Martin Hope
    Aleksandr Dubinsky 为什么 InetAddress 上的 switch 模式匹配会失败,并出现“未涵盖所有可能的输入值”? 2024-12-23 06:56:21 +0800 CST
  • Martin Hope
    Phillip Borge 为什么这个简单而小的 Java 代码在所有 Graal JVM 上的运行速度都快 30 倍,但在任何 Oracle JVM 上却不行? 2024-12-12 20:46:46 +0800 CST
  • Martin Hope
    Oodini 具有指定基础类型但没有枚举器的“枚举类”的用途是什么? 2024-12-12 06:27:11 +0800 CST
  • Martin Hope
    sleeptightAnsiC `(表达式,左值) = 右值` 在 C 或 C++ 中是有效的赋值吗?为什么有些编译器会接受/拒绝它? 2024-11-09 07:18:53 +0800 CST
  • Martin Hope
    The Mad Gamer 何时应使用 std::inplace_vector 而不是 std::vector? 2024-10-29 23:01:00 +0800 CST
  • Martin Hope
    Chad Feller 在 5.2 版中,bash 条件语句中的 [[ .. ]] 中的分号现在是可选的吗? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench 为什么双破折号 (--) 会导致此 MariaDB 子句评估为 true? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng 为什么 `dict(id=1, **{'id': 2})` 有时会引发 `KeyError: 'id'` 而不是 TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String” 2024-03-20 03:12:31 +0800 CST
  • Martin Hope
    MarkB 为什么 GCC 生成有条件执行 SIMD 实现的代码? 2024-02-17 06:17:14 +0800 CST

热门标签

python javascript c++ c# java typescript sql reactjs html

Explore

  • 主页
  • 问题
    • 最新
    • 热门
  • 标签
  • 帮助

Footer

AskOverflow.Dev

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve