3

I have created a component that creates a std::net::TcpStream and over its lifetime of course reads from it and writes to it. Now I would like to write tests for it; does it connect to the right address? Does it send the correct data? Can it handle receiving invalid data? However, as I have only started using Rust, like, three days ago, I am unsure as to how to proceed. In Java (which I have been doing substantially longer than Rust) I would have at least the following possibilities:

  1. Create a test TCP server to collect data sent to it and to control what is being sent back.
  2. Extract the I/O operations into a trait, implement that trait for TcpStream and a TestTcpStream, and use the TestTcpStream during tests.

Does Rust offer something else that I don’t yet know about?

(To clarify a bit: I’m not looking for how to do any of these things, I can probably figure that out, I was asking for more possibilities than the two I have listed.)

Bombe
  • 81,643
  • 20
  • 123
  • 127
  • 1
    For the first one you might want to check `std::net::TcpListener` which provides you a `TcpStream` for each connection. For the second one, `TcpStream` already [implements](https://doc.rust-lang.org/std/net/struct.TcpStream.html#implementations) `std::io::Write` and `std::io::Read` traits, you may expect these traits instead of concrete `TcpStream` for your IO logic. – Ömer Erden Apr 16 '20 at 10:29
  • _"Does Rust offer something else that I don’t yet know about?"_ Not out of the usual box, other than traits for specifying common behavior. Since `TcpStream` [implements `Read` and `Write`](https://doc.rust-lang.org/stable/std/net/struct.TcpStream.html#implementations), just follow the advice given in [this question](https://stackoverflow.com/questions/28370126/how-can-i-test-stdin-and-stdout). – E_net4 Apr 16 '20 at 10:32
  • Okay, `Read` and `Write` certainly seem viable options but that would still leave me with the necessity to create the `TcpStream`. Normally I would throw a factory at that, is that considered idiomatic in Rust as well? :) – Bombe Apr 16 '20 at 11:13
  • No, you would make your logic depend on something that implements `Read` and `Write`. From there, you can "mock" the TCP stream by giving it something else that provides the two byte channels. – E_net4 Apr 16 '20 at 11:41
  • Yes, I’m aware of that part but the library I’m writing should be responsible for creating the TCP stream as well so I would somehow need to make that part accessible to tests, too. – Bombe Apr 16 '20 at 11:51
  • You can spawn a thread to run your code and in your main thread you listen for a connection and check that all is correct. – TheGr8_Nik Apr 16 '20 at 20:50

0 Answers0