Go: how to run tests for multiple packages?

后端 未结 4 1986
别那么骄傲
别那么骄傲 2020-12-31 07:33

I have multiple packages under a subdirectory under src/, running the tests for each package with go test is working fine.

When trying to run all tests

4条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-31 08:05

    Update: As pointed out by @Gal Ben-Haim, adding the (undocumented) go test -p 1 flag builds and tests all packages in serial. As put by the testflag usage message in the Go source code:

    -p=n: build and test up to n packages in parallel

    Old answer:

    When running go test ./..., the tests of the different packages are in fact run in parallel, even if you set parallel=1 (only tests within a specific package are guaranteed to be run one at a time). If it is important that the packages be tested in sequence, like when there is database setup/teardown involved, it seems like the only way right now is to use the shell to emulate the behavior of go test ./..., and forcing the packages to be tested one by one.

    Something like this, for example, works in Bash:

    find . -name '*.go' -printf '%h\n' | sort -u | xargs -n1 -P1 go test
    

    The command first lists all the subdirectories containing *.go files. Then it uses sort -u to list each subdirectory only once (removing duplicates). Finally all the subdirectories containing go files get fed to go test via xargs. The -P1 indicates that at most one command is to be run at a time.

    Unfortunately, this is a lot uglier than just running go test ./..., but it might be acceptable if it is put into a shell script or aliased into a function that's more memorable:

    function gotest(){   find $1 -name '*.go' -printf '%h\n' | sort -u | xargs -n1 -P1 go test; }
    

    Now all tests can be run in the current directory by calling:

    gotest .
    

提交回复
热议问题