Levi
Levi

Reputation: 151

Capture SIGINT when running tests in GoLand IDE

When running tests from command line, capturing SIGINT works fine. However, is there a way to pass SIGINT signal to code when running tests from GoLand IDE?

When running from command line: go test -v -run TestSth and then calling Ctrl + C it captures fine.

Example code:

EDIT: it seems my example code now captures SIGINT as intended (Goland 2022.3.2)

package main

import (
    "fmt"
    "os"
    "os/signal"
    "syscall"
    "testing"
    "time"
)

func TestMain(m *testing.M) {
    terminate := make(chan os.Signal)
    signal.Notify(terminate, syscall.SIGINT)
    go func() {
        <-terminate
        fmt.Println()
        fmt.Println("CAPTURED!!!") // want to get here when running tests from IDE
    }()
    exitCode := m.Run()
    os.Exit(exitCode)
}

func TestSth(t *testing.T) {
    time.Sleep(time.Second * 5)
}

Upvotes: 2

Views: 867

Answers (1)

Inian
Inian

Reputation: 85663

Get the current process information by calling FindProcess on the current PID and signal the interrupt to it using Process.Signal

func TestSth(t *testing.T) {
     go func() {
         // Sleep added for demonstrative purposes, can be removed
         time.Sleep(time.Second * 1)
         p, err := os.FindProcess(os.Getpid())
         if err != nil {
             panic(err)
         }
         p.Signal(syscall.SIGINT)

     }()
     time.Sleep(time.Second * 5)
}

Upvotes: 1

Related Questions