Approach to Integration Testing in D

Vijay Nayar madric at gmail.com
Sun Feb 6 17:36:05 UTC 2022


On Friday, 4 February 2022 at 17:39:00 UTC, H. S. Teoh wrote:
> On Fri, Feb 04, 2022 at 12:38:08PM +0000, Vijay Nayar via 
> Digitalmars-d-learn wrote: [...]

I am still in the process of experimenting, but the advice on 
this thread has all been very helpful. Right now I'm 
experimenting by creating a separate "integration" `dub` 
configuration which uses `std.process : spawnProcess` to run my 
vibe.d-based web server and try out requests on it.

However, in any kind of large organization using a build server, 
even when there are multiple services/builds running in the same 
environment, it can be very inconvenient use a fixed port on 
which to run this server. Another running service, another 
person's build, or a test that ran and died without closing its 
sockets can lead to conflicts during development.

In order to solve that problem of port conflicts during 
integration testing, I converted a utility class from the Java 
Spring Framework into D and wanted to share it here: 
https://gist.github.com/vnayar/04c6172d9f9991062974585bb3ccc8a4

The usage is very simple, and can be used by integration tests to 
pick random free ports on which to run their tests. Here is one 
of the available methods:

```d
/**
  * Find an available TCP port randomly selected from the range
  * \[ [PORT_RANGE_MIN], [PORT_RANGE_MAX] \].
  * Returns: an available TCP port number
  * Throws: Exception if no available port could be found
  */
ushort findAvailableTcpPort() {
   return findAvailableTcpPort(PORT_RANGE_MIN);
}

unittest {
   foreach (ushort i; 0..10) {
     ushort port = findAvailableTcpPort();
     assert(port >= PORT_RANGE_MIN && port <= PORT_RANGE_MAX);
   }
}
```


More information about the Digitalmars-d-learn mailing list