Search⌘ K
AI Features

Testing the Port Scanning Functionality

Explore how to write tests for port scanning functions in Go CLI applications using the Cobra framework. Learn to create reproducible tests simulating open and closed TCP ports on localhost, handle host existence checks, and validate port states to ensure robust network scanning capabilities.

Creating the scanHosts_test.go file

We create a file scanHosts_test.go for the tests. We define the package package scan_test so it only tests the exposed API, as we did with the hosts tests:

Go (1.6.2)
package scan_test

Then, we add the import section.

For these tests, we’ll use:

  • The net package to create a local TCP server.
  • The package strconv to convert strings to integer numbers.
  • The testing package for the testing function.
  • The scan package that we’re testing.
Go (1.6.2)
import (
"net"
"strconv"
"testing"
"pScan/scan"
)
The import list

Adding the TestStateString() function

Now, we add our first test function TestStateString() to test the String() method of the state type. We want to ensure it returns open or closed:

Go (1.6.2)
func TestStateString(t *testing.T) {
ps := scan.PortState{}
if ps.Open.String() != "closed" {
t.Errorf("Expected %q, got %q instead\n", "closed", ps.Open.String())
}
ps.Open = true
if ps.Open.String() != "open" {
t.Errorf("Expected %q, got %q instead\n", "open", ps.Open.String())
}
}
Adding the function TestStateString()

For this test, we’re defining an instance of the type scan.PortState. By default, the ...