Home > Article > Backend Development > Why Do Tests Fail When Running Across Multiple Packages in Go Despite Using `-parallel 1`?
When working with multiple packages stored under a subdirectory within the src/ directory, executing tests for each package individually using go test is typically successful. However, when attempting to run all tests collectively using go test ./..., issues arise.
The tests execute, but ultimately fail when operating against local database servers due to contention between tests. Despite setting -parallel 1 to prevent database contention, the tests still fail. This suggests a problem with test sequencing.
Each test file contains two global variables:
<code class="go">var session *mgo.Session var db *mgo.Database</code>
Additionally, it employs the following setup and teardown functions:
<code class="go">func setUp() { s, err := cfg.GetDBSession() if err != nil { panic(err) } session = s db = cfg.GetDB(session) db.DropDatabase() } func tearDown() { db.DropDatabase() session.Close() }</code>
Each test begins with setUp() and ends with tearDown(). cfg is defined as follows:
<code class="go">package cfg import ( "labix.org/v2/mgo" ) func GetDBSession() (*mgo.Session, error) { session, err := mgo.Dial("localhost") return session, err } func GetDB(session *mgo.Session) *mgo.Database { return session.DB("test_db") }</code>
Upon modifying cfg to use a random database, the tests passed successfully. This observation implies that tests from multiple packages run somewhat concurrently.
Possible Solution:
Option 1 (Undocumented):
Option 2 (Shell-Based):
Bash Command:
<code class="bash">find . -name '*.go' -printf '%h\n' | sort -u | xargs -n1 -P1 go test</code>
Function Alias (gotest):
<code class="bash">function gotest(){ find -name '*.go' -printf '%h\n' | sort -u | xargs -n1 -P1 go test; }</code>
By invoking gotest ., all tests in the current directory can be run sequentially.
The above is the detailed content of Why Do Tests Fail When Running Across Multiple Packages in Go Despite Using `-parallel 1`?. For more information, please follow other related articles on the PHP Chinese website!