File: remote.go

package info (click to toggle)
golang-github-dylanmei-winrmtest 0.0~git20151226.0256178-2
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, sid
  • size: 80 kB
  • ctags: 27
  • sloc: makefile: 5
file content (79 lines) | stat: -rw-r--r-- 1,672 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package winrmtest

import (
	"io"
	"net/http"
	"net/http/httptest"
	"net/url"
	"regexp"
	"strconv"
	"strings"
)

// Remote respresents a WinRM server
type Remote struct {
	Host    string
	Port    int
	server  *httptest.Server
	service *wsman
}

// NewRemote returns a new initialized Remote
func NewRemote() *Remote {
	mux := http.NewServeMux()
	srv := httptest.NewServer(mux)

	host, port, _ := splitAddr(srv.URL)
	remote := Remote{
		Host:    host,
		Port:    port,
		server:  srv,
		service: &wsman{},
	}

	mux.Handle("/wsman", remote.service)
	return &remote
}

// Close closes the WinRM server
func (r *Remote) Close() {
	r.server.Close()
}

// MatcherFunc respresents a function used to match WinRM commands
type MatcherFunc func(candidate string) bool

// MatchText return a new MatcherFunc based on text matching
func MatchText(text string) MatcherFunc {
	return func(candidate string) bool {
		return text == candidate
	}
}

// MatchPattern return a new MatcherFunc based on pattern matching
func MatchPattern(pattern string) MatcherFunc {
	r := regexp.MustCompile(pattern)
	return func(candidate string) bool {
		return r.MatchString(candidate)
	}
}

// CommandFunc respresents a function used to mock WinRM commands
type CommandFunc func(out, err io.Writer) (exitCode int)

// CommandFunc adds a WinRM command mock function to the WinRM server
func (r *Remote) CommandFunc(m MatcherFunc, f CommandFunc) {
	r.service.HandleCommand(m, f)
}

func splitAddr(addr string) (host string, port int, err error) {
	u, err := url.Parse(addr)
	if err != nil {
		return
	}

	split := strings.Split(u.Host, ":")
	host = split[0]
	port, err = strconv.Atoi(split[1])
	return
}