Skip to content

Weird error when trying to mock an external function #25

@keltia

Description

@keltia

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions