123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104 |
- package kyoketsu
- import (
- "fmt"
- "log"
- "net"
- "sync"
- "testing"
- )
- func Equal(a, b []int) bool {
- if len(a) != len(b) {
- return false
- }
- for i, v := range a {
- if v != b[i] {
- return false
- }
- }
- return true
- }
- func startTestSever(port int, t *testing.T) {
- listen, err := net.Listen("tcp", fmt.Sprintf("localhost:%v", port))
- if err != nil {
- log.Fatal(err)
- }
- defer listen.Close()
- for {
- conn, err := listen.Accept()
- if err != nil {
- log.Fatal(err)
- }
- t.Logf("Recieved dial from PortWalk of port: %v from host: %s\n", port, conn.RemoteAddr().String())
- conn.Close()
- }
- }
- func TestPortWalk(t *testing.T) {
- type TestCase struct {
- Name string
- ScanPort []int
- ListenPort []int
- ShouldFail bool
- }
- tc := []TestCase{
- TestCase{
- Name: "Passing test, listening on 8080/27017 and scanned on 8080/27017.",
- ScanPort: []int{8080, 27017},
- ListenPort: []int{8080, 27017},
- ShouldFail: false,
- },
- TestCase{
- Name: "Failing test, listening on 8081 scanned on 6439",
- ScanPort: []int{6439},
- ListenPort: []int{8081},
- ShouldFail: true,
- },
- }
- wg := &sync.WaitGroup{}
- for i := range tc {
- for x := range tc[i].ListenPort {
- wg.Add(1)
- go startTestSever(tc[i].ListenPort[x], t)
- }
- got := PortWalk("localhost", tc[i].ScanPort)
- for k := range tc[i].ListenPort {
- wg.Done()
- if !Equal(got, tc[i].ListenPort) {
- if !tc[i].ShouldFail {
- t.Errorf("Test '%s' failed! PortWalk didnt detect the test server was listening on: %+v\n", tc[i].Name, tc[i].ListenPort)
- }
- }
- t.Logf("Test '%s' passed! Scanned port: '%v'", tc[i].Name, tc[i].ListenPort[k])
- }
- }
- }
|