简体   繁体   中英

Go hangs when running tests

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:\n%s\n", err)
    }
  }
  f()
  go func() {
    if err := serve(testListener, nil); err != nil {
      fmt.Printf("[Fail] the server failed to start:\n%s\n", 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM