dqsk4643 2019-04-03 02:57
浏览 31

如何在TestMain中为测试套件执行延迟功能?

I've updated the question to avoid being accused of posting an XY question.

Previously the question was:

how can I tell when runtime.Goexit has been called on the main goroutine?

I'm trying to write a method that finishes all deferred functions on the main goroutine by calling runtime.Goexit() and then calls os.Exit() from a goroutine a spawned before calling this exit method. The problem I have is that I don't know when runtime.Goexit() has completed. Is there any way I can know when the main goroutine has finished?

UPDATED: Let me elaborate on my use case. Consider this pattern for TestMain:

func TestMain(m *testing.M) {
    db.Create()
    defer db.Drop()
    os.Exit(m.Run())
}

In this case, the database is never dropped because os.Exit stops the program. My goal was to come up with an alternate exit function that executes all the deferred functions in TestMain. Now, I could move everything into another function like this:

func realTestMain(m *testing.M) int {
    db.Create()
    defer db.Drop()
    return m.Run()
}

func TestMain(m *testing.M) {
    os.Exit(realTestMain(m))
}

However, this pattern would have to be enforced across our test suite and is ugly and difficult to remember. I was exploring whether I could have a helper that makes it possible to write my setup/teardown as follows:

func TestMain(m *testing.M) {
    db.Create()
    defer db.Drop()
    helpers.SafeExit(m.Run())
}

With a helper like this, I could write a simple check to ensure that os.Exit never appears in our test suites.

  • 写回答

3条回答 默认 最新

  • dongtuo4723 2019-04-03 03:36
    关注

    Is there any way I can know when the main goroutine has finished?

    Yes: When your program has stopped.

    Once the main goroutine stops your program terminates including any other goroutine. So you will have to redesign as nothing ever executes after the main goroutine exits.

    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度