132 questions
0
votes
2
answers
248
views
Unable to test internal functions in Golang [closed]
I'm using Go 1.24.3, installed via Homebrew on an Apple M1, running Sequoia 15.5.
I have a main:
//main.go
package main
import "fmt"
func main() {
fmt.Println("Hello, world!")
}...
0
votes
0
answers
117
views
go test takes long time to start running on Google Cloud Build
Context
I have a very simple, bare bones cloudbuild.yaml that:
sets up GOPRIVATE variable so that the CI environment is able to download dependencies
Runs go build
Runs go test:
steps:
- id: "...
0
votes
1
answer
140
views
Context Deadline is not cancelling a go routine fuction unless I reduce deadline
I modified a function from a book I was reading, the function writes "ping" to a writer at a predefined interval. The program runs in a go routine so I appended a context so the function can ...
0
votes
0
answers
56
views
Intercepting test failures to provide additional context
TL;DR: Is there any known hack to capture and/or print additional context when a Golang test fails? (using standard library testing)
Example:
func TestSomething(t *testing.T) {
...
...
if ... {
...
1
vote
2
answers
293
views
Let web service response fail on io.ReadAll in unit test
I have a program that calls a web service and I want to write a unit test that checks the correct failure handling (nothing fancy). I use net/http/httptest to simulate the web service (backend). But I ...
2
votes
2
answers
240
views
How to write unit test case for gocql
package main
import "github.com/gocql/gocql"
var CassandraSession *gocql.Session
func getSelectQuery(ClientId, UID, UUID, tableName, selectColumns string, sess *gocql.Session) (*gocql....
-1
votes
1
answer
69
views
Achieving partial build for broken Go codebase
I have a generator which generates me code in Go, for example:
foo.go
bar.go
...
After generation, I need to test if my generator is doing good job. For every generated file, I have a test ...
2
votes
2
answers
314
views
Go coverage profile gives a mix of module url and local path
I recently started playing with go build -cover -o to collect the code coverage for integration test in Go 1.20. I used the textfmt to get the coverage, but looking at the text file, it has a local ...
-3
votes
1
answer
348
views
In `go test`, is it possible to pass custom flags?
As far as I tested, go test -- <custom flag(s)> works but I couldn't find any documentation for it.
I have this test code:
package main
import (
"os"
"testing"
)
...
2
votes
1
answer
327
views
golang.org/x/oauth2 oauth2.Config.Endpoint.TokenURL mock: missing access_token
I want to test my oauth2 client and use a mock for TokenURL endpoint. The mock responds with access_token but there is always an error with missing access_token.
I am using golang.org/x/oauth2 and ...
1
vote
0
answers
149
views
How do I prevent testify command line args from leaking into my Cobra application?
This is my test:
// A test of TestSuite
func (ts *TestSuite) TestMyThing() {
cmd := RootCmd()
b := bytes.NewBufferString("")
cmd.SetOut(b)
cmd.SetErr(b)
err := cmd....
0
votes
1
answer
1k
views
Go test coverage, if statement not covered
I have a go function called setupConfig() and I have a Test_setupconfig that tests it and tests it just fine. But when I do a cover test on it and look at the HTML report, it shows my handling of ...
4
votes
1
answer
5k
views
How to avoid timeout in go test after 10m
I'm currently running a suite of tests in Go using the go test ./... command. This suite contains multiple test functions, and the execution time exceeds 10 minutes. Unfortunately, the go test command ...
0
votes
1
answer
491
views
Issue with executing tests for main function in Go
I wrote this test a few months back and it was running successfully without any error and never went through init() function as I have only invoked handler function from test but now it's failing with ...
2
votes
1
answer
41
views
Form variables not available in testing
I am a Go newbie. I have written an API server built on the Echo server, using the DeepMap OpenAPI generator and Postgres using pgxpool. It is working well enough and has been in use for a year, but ...
1
vote
0
answers
66
views
How to create Unit test cases for “GetListOfUsers()” function of “UserService.go“ file. Facing issue in creating dummy aerospike.Recordset object
How to create Unit test cases for “GetListOfUsers()” function of “UserService.go“ file. Facing issue in creating dummy aerospike.Recordset object
this is the test file
Sample testfile
func (suite *...
2
votes
0
answers
611
views
Is the go test coverage.out file able to show how many tests were run?
I have a project in go lang, I can run tests and sonar can identify the total percentage of test coverage. But I want to know if I can generate any metrics in this coverage.out file that can show how ...
2
votes
2
answers
815
views
How to correctly cover all golang packages with all tests?
Assume that some code defined under package pkg/somepkg1.
And there are some tests in this package and some tests are in package tests/integration.
If i call
go test -cover -coverprofile=cover.out ./.....
-1
votes
1
answer
156
views
hex-arc golang - overcome import cycling error when testing
I am having trouble testing foo_handler in my Go project. My project has the following structure:
├── Makefile
├── cmd
│ └── main.go
├── go.mod
├── go.sum
└── internal
├── api
│ ├── router....
1
vote
1
answer
157
views
How to run `go test` in the parent directory of multiple go modules and return non-zero in case of error
Take a look at this directory structure:
/root
/hoge
go.mod
go.sum
main.go
/test
main_test.go
/unit
sub_test.go
/fuga
...
1
vote
1
answer
542
views
Go test "-run -" flag executed tests much faster
I was looking at some benchmark tests from https://github.com/RoaringBitmap/roaring
When running a specific benchmark using -run - (as mentioned in there comments):
go test -bench BenchmarkNexts -...
1
vote
1
answer
1k
views
How to use gomock to make a mocked function return different results on subsequent calls?
I am using gomock to mock an http function that is called within the function under test. While it works great for one call it seems to call the first function again when I want to return a different ...
0
votes
1
answer
1k
views
How to write unit test when a member function is calling another member function of the same object in golang?
In golang, I often see a member function calling another member function of the same object. For example check following golang code:
type Obj struct{}
func (o Obj) First() {
// do something
...
1
vote
1
answer
2k
views
How to write unit test when using db transaction?
I'm using mysql transaction in my project, I want to know how to write unit test when using db transaction? for example:
func SomeFunc() error {
return db.Transaction(func(tx *gorm.DB) {
// my ...
1
vote
0
answers
65
views
`gopls` disagrees with `go test` on interface implementation
Consider the following code:
package ifaces
import (
"fmt"
"testing"
)
type IFace1 interface {
Do1()
}
type IFace2 interface {
...
0
votes
1
answer
1k
views
How to tell gazelle that a go file is meant for go_default_test and not go_default_library?
I have a file, embed_testdata.go, meant to be used in tests but does not itself have tests (so I don't want to suffix it with _test.go). How do I tell gazelle that it's really test source and not prod ...
5
votes
1
answer
1k
views
How do you test filepath.Abs failure in your Golang code?
In my Go code, I have to use filepath.Abs() several times, which may lead to different errors that my method returns.
func (s *service) myFunc(path string) error {
dir := s.Component().Dir()
...
2
votes
1
answer
202
views
Where is the discoveryfake defined in k8s discovery interface?
While I'm reading how to test on k8s with the fake client on this link, I noticed this function, which, IIUC, assigns a faked server version to the faked k8s cluster.
k8s.clientset.Discovery().(*...
2
votes
0
answers
564
views
Testing gRPC server with golang and mockery fails with a timeout when mock fails
I am trying to test a gRPC service locally.
Here is the sample code
type TestGrpcServer struct {
t *testing.T
Server *grpc.Server
Lis *bufconn.Listener
Conn *grpc.ClientConn
}...
2
votes
3
answers
215
views
How test functions are called in Go?
I'm studying Go language and I have a question now.
I was just testing buffered and unbuffered channels.
While writing the test code for it, a situation occurred that I couldn't understand the result.
...
-1
votes
1
answer
3k
views
How to run a compiled Go test binary?
I compiled a Go test library by running go test -c ./model. According to Go docs it can be run using go run -exec xprog command, however, I keep getting errors while trying to run my generated model....
3
votes
1
answer
2k
views
Why do I get "second argument to errors.As should not be *error" build error in test only?
Consider the following test:
import (
"errors"
"fmt"
"testing"
)
func TestError(t *testing.T) {
err := &MyError{}
var target error
fmt....
0
votes
2
answers
2k
views
Golang how to test function that return channel type?
I try to test function StartP,
Expect that Start() should be called 1 times, Done() should be called 1 times
but I have trouble that test will block when run this step <-ps.Done()
I expect <-ps....
1
vote
0
answers
365
views
How to measure test coverage difference in Go
Is there a way to get the difference in coverage percentage? My goal is to fail a build when the coverage has decreased.
I can easily get the current coverage percentage and compare it to a threshold ...
1
vote
0
answers
188
views
Go test coverage for test files in separate module [duplicate]
I'm running gotestsum --junitfile-testcase-classname=short --junitfile-testsuite-name=relative \ -- -coverprofile=coverage.out ./serviceName/...
The structure looks like this:
serviceName
...
1
vote
1
answer
2k
views
Test for handler with file upload
I'm trying to write a test for a handler which receives a file. As part of such I'm trying to configure my context so the handler can use it.
My intention is to create a file and use multipart....
5
votes
0
answers
474
views
Do all tests have to pass to get code coverage in Go?
I am using the -cover to collect coverage in my Go project. However, it seems that the tests have to be 100% success rate in order to get the coverage report. Is there any way I can get the coverage ...
1
vote
1
answer
126
views
handler.ServeHTTP(w,req) and handler(w,req) difference in tests
I'm trying to understand the difference between handler.ServeHTTP(w,req) and handler(w,req) in Go testing. When should I use each of them? Are they exactly the same?
Docs say simply: ServeHTTP calls f(...
1
vote
1
answer
90
views
Running all tests for a multi-binary project
Consider a multi binary project with the following structure.
.
├── bin1
│ ├── config
│ │ ├── config.go
│ │ └── config_test.go
│ └── utils
│ ├── utils.go
│ └── utils_test.go
├──...
1
vote
0
answers
68
views
Checking external private errors
I have a package which does some error checking for specific error types. One of the errors is from an external package, its fields are all unexported as well as the relevant creation func, so I cant ...
1
vote
1
answer
705
views
How to collect k8s pods logs in parallel using golang only for a duration of time
I am new to golang, I have a task to collect the application logs, application is running as deployment in k8s cluster, there are 4 pods in total.
As part of test automation, I need to collect the ...
7
votes
2
answers
5k
views
How to calculate total code coverage for tests
I need to calculate code coverage for golang project where source of tests will be integration tests written in Java language . This requires go build to be instrumented first and then run on server ...
1
vote
1
answer
181
views
Temporary filesystem only visible to the process in Go
I am writing e2e tests for a command line app where I have to do file manipulation (such as cp, mv, rm, touch, and mkdir). The tests can execute just fine in my local environment. The problem occurs ...
0
votes
0
answers
262
views
Permission denied when running Go shell script in Github Actions
I have a Go project which creates an endpoint, to consume system information like CPU temps and clock speed etc. (For debian based distros)
I am able to build and test the project successfully in my ...
1
vote
0
answers
360
views
Go build constraints to run if none set
I have many classes of test, which are marked with build constraints, e.g.:
//go:build all || (!foo && !bar && !baz && quux)
for the test class quux. This is okay, as far as ...
0
votes
0
answers
516
views
go tests error "Request validation failed"
I'm getting a request validation failed when running a test in golang but not when running the code:
{"error":"Request validation failed","validation":[{"keyword&...
1
vote
1
answer
3k
views
Function like assert.Contains by stretchr/testify but ignore case and whitespace
For example, I have this test here
assert.Contains(t, "HELLO WORLD", "hello world)
and I want this to return true. Obviously, I can clean up the string with strings.TrimSpace(), ...
0
votes
0
answers
117
views
Same file needed for multiple packages in GoLang
I am using this method here to collect the code coverage for my system tests. The overall idea is that I need a dummy test so that I can generate an executable that calls the main() in the package. As ...
7
votes
1
answer
7k
views
Why does -count=1 ignores caching in Go tests?
I understand that in order to avoid cached results in Go tests you can use the -count=1 flag in the go test command, but why?
This is from the docs:
The idiomatic way to disable test caching ...
4
votes
0
answers
526
views
VS Code - Go: Prevent removal of test coverage markings after save
I'm using VS Code for a Go project. I have it configured to show the code coverage with gutter markings after I run the tests.
The issue I'm having is that if I make any changes to a file in the ...