Skip to content
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

Weird error when trying to mock an external function #25

Open
keltia opened this issue May 17, 2022 · 0 comments
Open

Weird error when trying to mock an external function #25

keltia opened this issue May 17, 2022 · 0 comments

Comments

@keltia
Copy link

keltia commented May 17, 2022

Rust: stable/1.60 on macOS 14.6 in a Mac Mini.

Hello, I'm trying to mock a function named lookup_addr which belongs to an external crape (dns-lookup) in order to avoid DNS resolution timeouts during tests, etc.

Trying the Trait approach, I get this:

    trait Lookup {
        fn lookup_addr(&self, ip: &IpAddr) -> Result<String, ()>;
    }

    fn lookup_addr(ip: &IpAddr) -> Result<String, ()> {
        let ip = ip.to_string();
        println!("BEEP");
        match ip.as_str() {
            "1.1.1.1" => Ok("one.one.one.one".into()),
            "2606:4700:4700::1111" => Ok("one.one.one.one".into()),
            "192.0.2.1" => Ok("some.host.invalid".into()),
            _ => Ok("blah".into()),
        }
    }

    mock_trait_no_default!(
        MockLookup,
        lookup_addr(&'static IpAddr) -> Result<String, ()>
    );

    impl Lookup for MockLookup {
        mock_method!(lookup_addr(&self, ip: &IpAddr) -> Result<String, ()>);
    }

    #[rstest]
    #[case("1.1.1.1", "one.one.one.one")]
    #[case("2606:4700:4700::1111", "one.one.one.one")]
    #[case("192.0.2.1", "some.host.invalid")]
    fn test_ip_solve(#[case] s: &str, #[case] p: &str) {
        let mock = MockLookup::new(Ok("foo.bar".to_owned()));

        let ptr = Ip::new(s).solve();
        assert_eq!(s.parse::<IpAddr>().unwrap(), ptr.ip);
        assert_eq!(p.to_string(), ptr.name);
    }

and it always barf with this error message:

error[E0308]: mismatched types
   --> src/ip.rs:175:9
    |
175 |         mock_method!(lookup_addr(&self, ip: &IpAddr) -> Result<String, ()>);
    |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected `&std::net::IpAddr`, found enum `std::net::IpAddr`
    |
    = note: this error originates in the macro `mock_method` (in Nightly builds, run with -Z macro-backtrace for more info)

Any idea on what I'm doing wrong?

I also tried with mock_func_no_default!() but my custom function was never called.

Also, if I remove the &'static from the macro call abose, it complains that it expects a named lifetime.

Thx.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant