在GoLand IDE中运行测试时捕获SIGINT信号。

huangapple go评论91阅读模式
英文:

Capture SIGINT when running tests in GoLand IDE

问题

当从命令行运行测试时,捕获SIGINT信号是有效的。但是,当从GoLand IDE运行测试时,有没有办法将SIGINT信号传递给代码呢?

当从命令行运行时:
go test -v -run TestSth,然后调用<kbd>Ctrl + C</kbd>,它可以正常捕获。

示例代码:

编辑:看起来我的示例代码现在可以按预期捕获SIGINT信号(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!!!") // 当从IDE运行测试时,希望能到达这里
	}()
	exitCode := m.Run()
	os.Exit(exitCode)
}

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

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 <kbd>Ctrl + C</kbd> it captures fine.

Example code:

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

package main

import (
	&quot;fmt&quot;
	&quot;os&quot;
	&quot;os/signal&quot;
	&quot;syscall&quot;
	&quot;testing&quot;
	&quot;time&quot;
)

func TestMain(m *testing.M) {
	terminate := make(chan os.Signal)
	signal.Notify(terminate, syscall.SIGINT)
	go func() {
		&lt;-terminate
		fmt.Println()
		fmt.Println(&quot;CAPTURED!!!&quot;) // 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)
}

答案1

得分: 1

通过调用FindProcess函数获取当前进程的信息,并使用Process.Signal向其发送中断信号。

func TestSth(t *testing.T) {
     go func() {
         // 为了演示目的添加了Sleep,可以删除
         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)
}
英文:

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)
}

huangapple
  • 本文由 发表于 2022年1月28日 18:17:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/70892061.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定