scanner_test.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package kyoketsu
  2. import (
  3. "fmt"
  4. "log"
  5. "net"
  6. "sync"
  7. "testing"
  8. )
  9. func startTestSever(port int, t *testing.T) {
  10. listen, err := net.Listen("tcp", fmt.Sprintf("localhost:%v", port))
  11. if err != nil {
  12. log.Fatal(err)
  13. }
  14. defer listen.Close()
  15. for {
  16. conn, err := listen.Accept()
  17. if err != nil {
  18. log.Fatal(err)
  19. }
  20. t.Logf("Recieved dial from PortWalk of port: %v from host: %s\n", port, conn.RemoteAddr().String())
  21. conn.Close()
  22. }
  23. }
  24. func TestPortWalk(t *testing.T) {
  25. type TestCase struct {
  26. Name string
  27. ScanPort map[int]string
  28. ListenPort map[int]string
  29. ShouldFail bool
  30. }
  31. tc := []TestCase{
  32. TestCase{
  33. Name: "Passing test, listening on 8080/27017 and scanned on 8080/27017.",
  34. ScanPort: map[int]string{8080: "unknown", 27017: "mongo"},
  35. ListenPort: map[int]string{8080: "unknown", 27017: "mongo"},
  36. ShouldFail: false,
  37. },
  38. TestCase{
  39. Name: "Failing test, listening on 8081 scanned on 6439",
  40. ScanPort: map[int]string{6439: "random_service"},
  41. ListenPort: map[int]string{8081: "unknown"},
  42. ShouldFail: true,
  43. },
  44. }
  45. wg := &sync.WaitGroup{}
  46. for i := range tc {
  47. for port, _ := range tc[i].ListenPort {
  48. wg.Add(1)
  49. go startTestSever(port, t)
  50. }
  51. got := PortWalk("localhost", tc[i].ScanPort)
  52. for k, _ := range tc[i].ListenPort {
  53. wg.Done()
  54. _, ok := got.ListeningPorts[k]
  55. if !ok {
  56. if !tc[i].ShouldFail {
  57. t.Errorf("Test '%s' failed! PortWalk didnt detect the test server was listening on: %+v\n", tc[i].Name, tc[i].ListenPort)
  58. }
  59. }
  60. t.Logf("Test '%s' passed! Scanned port: '%v'", tc[i].Name, k)
  61. }
  62. }
  63. }