sfackler / rust-postgres

Native PostgreSQL driver for the Rust programming language
Apache License 2.0
3.46k stars 439 forks source link

Looking for a way to mock tokio_postgres::Client ? #1119

Open capveg-netdebug opened 6 months ago

capveg-netdebug commented 6 months ago

Hi - thanks for the great project.

Per the title, I'm trying to create a Mock Client so I can test my code without having to setup a real DB. How have other people done this?

Looking at the code, it seems like implementing GenericClient would be a great path, but it extends private::Sealed explicitly preventing that. Another avenue would be to implement an InnerClient and pass that to a new client, but both the InnerClient trait and the Client::new() functions are not accessible outside of the crate.

If there aren't any easy paths for this, could I offer to create a Mock function that looks like:

impl Client {

#[cfg(test)]
pub fn make_mock(sender: mpsc::UnboundedSender<Request>) -> Client {
      Client::new(sender, SSLMode::..., 0, 0)
   } 
}

https://docs.rs/tokio-postgres/latest/src/tokio_postgres/client.rs.html#189

Let me know and thank you in advance!

sfackler commented 6 months ago

You could make your own trait and implement it for Client.

capveg-netdebug commented 6 months ago

Thanks for the reply. You're right that I could duplicate all of the code in GenericClient and thus have my own trait that was the same without the private::Sealed, but I guess I don't understand why the private::Sealed is there.

[edit for clarification] It seems like you've intentionally/explicitly made this code hard to test; why is that? Would you be open to a PR to remove that private::Sealed dependency?

Thanks in advance.