dongou5100 2013-06-29 06:37
浏览 23

运行测试时挂起

I'm writing a web application in go and it runs just fine. However, when running the tests for a package, the go test command just hangs (it does nothing, not even terminate).

I have a function for testing which starts the server:

func mkroutes(t *testing.T, f func()) {
  handlerRegistry = handlerList([]handler{})
  middlewareRegistry = []middleware{}
  if testListener == nil {
    _testListener, err := net.Listen("tcp", ":8081")
    testListener = _testListener
    if err != nil {
      fmt.Printf("[Fail] could not start tcp server:
%s
", err)
    }
  }
  f()
  go func() {
    if err := serve(testListener, nil); err != nil {
      fmt.Printf("[Fail] the server failed to start:
%s
", err)
      t.FailNow()
    }
  }()
}

If I change the port that it listens on, everything runs fine (all the tests fail though, since they can't connect to the server). This shows that the code is indeed running, but if I log something in the function, or even in the init function, while the port is correct, it again breaks.

After I force the go test command to terminate manually, it does print whatever I logged, then exit. This leads me to believe that something else is blocking on the main thread before execution reaches the log, but that's impossible since changing the port makes a difference.

The package doesn't have any init functions and the only code that runs on startup is var sessionStore = sessions.NewCookieStore([]byte("test-key")) which is using the package github.com/gorilla/sessions. When I run the program normally, this causes no problems, and I don't see anything in the package's source that would cause it to behave differently in testing.

That's the only package outside the standard library which is imported.

I can provide any other code in the package, but I have no idea what's relevant.

  • 写回答

1条回答 默认 最新

  • dpw30157 2013-07-01 07:39
    关注

    First: Note that go test will create, compile and run a test program which intercept output from each test so you will not see output from your tests until the test finishes (in this moment the output is printed).

    Two issues with your code:

    1. If you cannot start the tcp server t is not notified, you only do Printf here and continue as if everything was fine.

    2. You call t.FailNow from a different goroutine than your test runs in. You must not do this. See http://golang.org/pkg/testing/#T.FailNow

    Fixing those might at least show what else goes wrong. Also: Take a look at how package net/http does it's testing.

    评论

报告相同问题?

悬赏问题

  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c