Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix linter errors #176

Merged
merged 8 commits into from
Aug 9, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 9 additions & 14 deletions client/service_manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,27 +35,22 @@ func (s *ServiceManager) Setup() {
// addServiceMonitor watches a channel to add services into operation.
func (s *ServiceManager) addServiceMonitor() {
log.Println("[DEBUG] starting service creation monitor")
for {
select {
case p := <-s.commandCreatedChan:
if p != nil && p.Process != nil {
s.processMap.Set(p.Process.Pid, p)
}
for p := range s.commandCreatedChan {
if p != nil && p.Process != nil {
s.processMap.Set(p.Process.Pid, p)
}
}
}

// removeServiceMonitor watches a channel to remove services from operation.
func (s *ServiceManager) removeServiceMonitor() {
log.Println("[DEBUG] starting service removal monitor")
var p *exec.Cmd
for {
select {
case p = <-s.commandCompleteChan:
if p != nil && p.Process != nil {
p.Process.Signal(os.Interrupt)
s.processMap.Delete(p.Process.Pid)
for p := range s.commandCompleteChan {
if p != nil && p.Process != nil {
if err := p.Process.Signal(os.Interrupt); err != nil {
log.Println("[ERROR] service removal monitor failed to process signal:", err)
}
s.processMap.Delete(p.Process.Pid)
}
}
}
Expand Down Expand Up @@ -161,7 +156,7 @@ type processMap struct {
func (pm *processMap) Get(k int) *exec.Cmd {
pm.RLock()
defer pm.RUnlock()
v, _ := pm.processes[k]
v := pm.processes[k]
return v
}

Expand Down
25 changes: 7 additions & 18 deletions client/service_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ var channelTimeout = 50 * time.Millisecond

func createServiceManager() *ServiceManager {
cs := []string{"-test.run=TestHelperProcess", "--", os.Args[0]}
env := []string{"GO_WANT_HELPER_PROCESS=1", fmt.Sprintf("GO_WANT_HELPER_PROCESS_TO_SUCCEED=true")}
env := []string{"GO_WANT_HELPER_PROCESS=1", "GO_WANT_HELPER_PROCESS_TO_SUCCEED=true"}
mgr := &ServiceManager{
Cmd: os.Args[0],
Args: cs,
Expand All @@ -24,9 +24,7 @@ func createServiceManager() *ServiceManager {
}

func TestServiceManager(t *testing.T) {
var manager interface{}
manager = new(ServiceManager)

var manager interface{} = new(ServiceManager)
if _, ok := manager.(*ServiceManager); !ok {
t.Fatalf("Must be a ServiceManager")
}
Expand All @@ -47,7 +45,7 @@ func TestServiceManager_Setup(t *testing.T) {
func TestServiceManager_removeServiceMonitor(t *testing.T) {
mgr := createServiceManager()
cmd := fakeExecCommand("", true, "")
cmd.Start()
cmd.Start() // nolint:errcheck
mgr.processMap.processes = map[int]*exec.Cmd{
cmd.Process.Pid: cmd,
}
Expand Down Expand Up @@ -75,7 +73,7 @@ func TestServiceManager_removeServiceMonitor(t *testing.T) {
func TestServiceManager_addServiceMonitor(t *testing.T) {
mgr := createServiceManager()
cmd := fakeExecCommand("", true, "")
cmd.Start()
cmd.Start() // nolint:errcheck
mgr.commandCreatedChan <- cmd
var timeout = time.After(channelTimeout)

Expand Down Expand Up @@ -128,12 +126,12 @@ func TestServiceManager_addServiceMonitorWithDeadJob(t *testing.T) {
func TestServiceManager_Stop(t *testing.T) {
mgr := createServiceManager()
cmd := fakeExecCommand("", true, "")
cmd.Start()
cmd.Start() // nolint:errcheck
mgr.processMap.processes = map[int]*exec.Cmd{
cmd.Process.Pid: cmd,
}

mgr.Stop(cmd.Process.Pid)
mgr.Stop(cmd.Process.Pid) // nolint:errcheck
var timeout = time.After(channelTimeout)
for {
mgr.processMap.Lock()
Expand All @@ -157,7 +155,7 @@ func TestServiceManager_Stop(t *testing.T) {
func TestServiceManager_List(t *testing.T) {
mgr := createServiceManager()
cmd := fakeExecCommand("", true, "")
cmd.Start()
cmd.Start() // nolint:errcheck
processes := map[int]*exec.Cmd{
cmd.Process.Pid: cmd,
}
Expand Down Expand Up @@ -196,15 +194,6 @@ func TestServiceManager_Start(t *testing.T) {
}
}

// Adapted from http://npf.io/2015/06/testing-exec-command/
var fakeExecSuccessCommand = func() *exec.Cmd {
return fakeExecCommand("", true, "")
}

var fakeExecFailCommand = func() *exec.Cmd {
return fakeExecCommand("", false, "")
}

func fakeExecCommand(command string, success bool, args ...string) *exec.Cmd {
cs := []string{"-test.run=TestHelperProcess", "--", command}
cs = append(cs, args...)
Expand Down
4 changes: 2 additions & 2 deletions dsl/broker_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ func setupMockBroker(auth bool) *httptest.Server {

w.Header().Set("WWW-Authenticate", `Basic realm="Broker Authentication Required"`)
w.WriteHeader(401)
w.Write([]byte("401 Unauthorized\n"))
w.Write([]byte("401 Unauthorized\n")) // nolint:errcheck
})
}
} else {
Expand Down Expand Up @@ -67,7 +67,7 @@ func setupMockBroker(auth bool) *httptest.Server {
mux.Handle("/pacts/provider/broken/latest/dev", authFunc(func(w http.ResponseWriter, req *http.Request) {
log.Println("[DEBUG] broker broker response")
w.WriteHeader(500)
w.Write([]byte("500 Server Error\n"))
w.Write([]byte("500 Server Error\n")) // nolint:errcheck
}))

// Find 'bobby' consumers for tag 'dev'
Expand Down
18 changes: 11 additions & 7 deletions dsl/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -97,8 +97,11 @@ func (p *PactClient) StartServer(args []string, port int) *types.MockServer {
svc := p.pactMockSvcManager.NewService(args)
cmd := svc.Start()

waitForPort(port, p.getNetworkInterface(), p.Address, p.TimeoutDuration,
err := waitForPort(port, p.getNetworkInterface(), p.Address, p.TimeoutDuration,
fmt.Sprintf(`Timed out waiting for Mock Server to start on port %d - are you sure it's running?`, port))
if err != nil {
log.Println("[ERROR] client: failed to wait for Mock Server:", err)
}

return &types.MockServer{
Pid: cmd.Process.Pid,
Expand Down Expand Up @@ -137,7 +140,9 @@ func (p *PactClient) RemoveAllServers(server *types.MockServer) []*types.MockSer

for _, s := range p.verificationSvcManager.List() {
if s != nil {
p.pactMockSvcManager.Stop(s.Process.Pid)
if _, err := p.pactMockSvcManager.Stop(s.Process.Pid); err != nil {
log.Println("[ERROR] client: stop server failed:", err)
}
}
}
return nil
Expand Down Expand Up @@ -195,8 +200,8 @@ func (p *PactClient) VerifyProvider(request types.VerifyRequest) ([]types.Provid
// Each pact is verified by line, and the results (as JSON) sent to stdout.
// See https://github.com/pact-foundation/pact-go/issues/88#issuecomment-404686337
stdOutScanner := bufio.NewScanner(stdOutPipe)
wg.Add(1)
go func() {
wg.Add(1)
defer wg.Done()
stdOutBuf := make([]byte, bufio.MaxScanTokenSize)
stdOutScanner.Buffer(stdOutBuf, 64*1024*1024)
Expand All @@ -208,13 +213,12 @@ func (p *PactClient) VerifyProvider(request types.VerifyRequest) ([]types.Provid

// Scrape errors
stdErrScanner := bufio.NewScanner(stdErrPipe)
wg.Add(1)
go func() {
wg.Add(1)
defer wg.Done()
for stdErrScanner.Scan() {
stdErr.WriteString(fmt.Sprintf("%s\n", stdErrScanner.Text()))
}

}()

err = cmd.Start()
Expand Down Expand Up @@ -429,13 +433,13 @@ var waitForPort = func(port int, network string, address string, timeoutDuration
func sanitiseRubyResponse(response string) string {
log.Println("[TRACE] response from Ruby process pre-sanitisation:", response)

r := regexp.MustCompile("(?m)^\\s*#.*$")
r := regexp.MustCompile(`(?m)^\s*#.*$`)
s := r.ReplaceAllString(response, "")

r = regexp.MustCompile("(?m).*bundle exec rake pact:verify.*$")
s = r.ReplaceAllString(s, "")

r = regexp.MustCompile("\\n+")
r = regexp.MustCompile(`\n+`)
s = r.ReplaceAllString(s, "\n")

return s
Expand Down
9 changes: 6 additions & 3 deletions dsl/client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,10 @@ func TestClient_StartServerFail(t *testing.T) {
func TestClient_StopServer(t *testing.T) {
client, svc := createMockClient(true)

client.StopServer(&types.MockServer{})
_, err := client.StopServer(&types.MockServer{})
if err != nil {
t.Fatalf("Failed to stop server: %v", err)
}
if svc.ServiceStopCount != 1 {
t.Fatalf("Expected 1 server to have been stopped, got %d", svc.ServiceStartCount)
}
Expand Down Expand Up @@ -216,13 +219,13 @@ func createMockClient(success bool) (*PactClient, *ServiceMock) {

// Start all processes to get the Pids!
for _, s := range svc.ServiceList {
s.Start()
s.Start() // nolint:errcheck
}

// Cleanup all Processes when we finish
defer func() {
for _, s := range svc.ServiceList {
s.Process.Kill()
s.Process.Kill() // nolint:errcheck
}
}()

Expand Down
4 changes: 2 additions & 2 deletions dsl/interaction_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ func TestInteraction_WithRequest(t *testing.T) {

var expect interface{}
body, _ := json.Marshal(obj)
json.Unmarshal(body, &expect)
json.Unmarshal(body, &expect) // nolint:errcheck

if _, ok := i.Request.Body.(map[string]string); !ok {
t.Fatal("Expected response to be of type 'map[string]string', but got", reflect.TypeOf(i.Request.Body))
Expand Down Expand Up @@ -104,7 +104,7 @@ func TestInteraction_WillRespondWith(t *testing.T) {

var expect interface{}
body, _ := json.Marshal(obj)
json.Unmarshal(body, &expect)
json.Unmarshal(body, &expect) // nolint:errcheck

if _, ok := i.Response.Body.(map[string]string); !ok {
t.Fatal("Expected response to be of type 'map[string]string', but got", reflect.TypeOf(i.Response.Body))
Expand Down
1 change: 0 additions & 1 deletion dsl/matcher.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ import (
const (
hexadecimal = `[0-9a-fA-F]+`
ipAddress = `(\d{1,3}\.)+\d{1,3}`
ipv6Address = `(\A([0-9a-f]{1,4}:){1,1}(:[0-9a-f]{1,4}){1,6}\Z)|(\A([0-9a-f]{1,4}:){1,2}(:[0-9a-f]{1,4}){1,5}\Z)|(\A([0-9a-f]{1,4}:){1,3}(:[0-9a-f]{1,4}){1,4}\Z)|(\A([0-9a-f]{1,4}:){1,4}(:[0-9a-f]{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1,4}){1,5}:(25[0-5]|2[0-4]\d|[0-1]?\d?\d)(\.(25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}\Z)`
uuid = `[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}`
timestamp = `^([\+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-2])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))([T\s]((([01]\d|2[0-3])((:?)[0-5]\d)?|24\:?00)([\.,]\d+(?!:))?)?(\17[0-5]\d([\.,]\d+)?)?([zZ]|([\+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$`
date = `^([\+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-2])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))?)`
Expand Down
6 changes: 3 additions & 3 deletions dsl/matcher_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -332,16 +332,16 @@ func formatJSON(object interface{}) interface{} {
var out bytes.Buffer
switch content := object.(type) {
case string:
json.Indent(&out, []byte(content), "", "\t")
json.Indent(&out, []byte(content), "", "\t") // nolint:errcheck
default:
jsonString, err := json.Marshal(object)
if err != nil {
log.Println("[ERROR] unable to marshal json:", err)
}
json.Indent(&out, []byte(jsonString), "", "\t")
json.Indent(&out, []byte(jsonString), "", "\t") // nolint:errcheck
}

return string(out.Bytes())
return out.String()
}

// Instrument the StructMatcher type to be able to assert the
Expand Down
4 changes: 0 additions & 4 deletions dsl/message_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,6 @@ package dsl

import "testing"

type t struct {
ID int
}

func TestMessage_DSL(t *testing.T) {
m := &Message{}
m.Given("state string").
Expand Down
27 changes: 19 additions & 8 deletions dsl/pact.go
Original file line number Diff line number Diff line change
Expand Up @@ -143,11 +143,11 @@ func (p *Pact) Setup(startMockServer bool) *Pact {
}

if p.LogDir == "" {
p.LogDir = fmt.Sprintf(filepath.Join(dir, "logs"))
p.LogDir = filepath.Join(dir, "logs")
}

if p.PactDir == "" {
p.PactDir = fmt.Sprintf(filepath.Join(dir, "pacts"))
p.PactDir = filepath.Join(dir, "pacts")
}

if p.SpecificationVersion == 0 {
Expand Down Expand Up @@ -488,9 +488,13 @@ func stateHandlerMiddleware(stateHandlers types.StateHandlers) proxy.Middleware
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == providerStatesSetupPath {
var s *types.ProviderState
var s types.ProviderState
decoder := json.NewDecoder(r.Body)
decoder.Decode(&s)
if err := decoder.Decode(&s); err != nil {
log.Printf("[ERROR] failed to decode provider state: %v", err)
w.WriteHeader(http.StatusBadRequest)
return
}

// Setup any provider state
for _, state := range s.States {
Expand Down Expand Up @@ -582,12 +586,14 @@ var messageVerificationHandler = func(messageHandlers MessageHandlers, stateHand
resBody, errM := json.Marshal(wrappedResponse)
if errM != nil {
w.WriteHeader(http.StatusServiceUnavailable)
log.Println("[ERROR] error marshalling objcet:", errM)
log.Println("[ERROR] error marshalling object:", errM)
return
}

w.WriteHeader(http.StatusOK)
w.Write(resBody)
if _, err := w.Write(resBody); err != nil {
log.Println("[ERROR] error writing response:", err)
}
}
}

Expand Down Expand Up @@ -693,7 +699,12 @@ func (p *Pact) VerifyMessageProviderRaw(request VerifyMessageRequest) ([]types.P
defer ln.Close()

log.Printf("[DEBUG] API handler starting: port %d (%s)", port, ln.Addr())
go http.Serve(ln, mux)
go func() {
if err := http.Serve(ln, mux); err != nil {
// NOTE: calling Fatalf causing test failures due to "accept tcp [::]:<port>: use of closed network connection"
log.Printf("[ERROR] API handler start failed: %v", err)
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@mefellows I'm not sure what behaviour is expected in this case.

}
}()

portErr := waitForPort(port, "tcp", "localhost", p.ClientTimeout,
fmt.Sprintf(`Timed out waiting for pact proxy on port %d - check for errors`, port))
Expand All @@ -715,7 +726,7 @@ func (p *Pact) VerifyMessageProviderRaw(request VerifyMessageRequest) ([]types.P
// It is the receiver of an interaction, and needs to be able to handle whatever
// request was provided.
func (p *Pact) VerifyMessageConsumerRaw(message *Message, handler MessageConsumer) error {
log.Printf("[DEBUG] verify message")
log.Println("[DEBUG] verify message")
p.Setup(false)

// Reify the message back to its "example/generated" form
Expand Down
Loading