Im new on golang and Im trying to _test my proxy func, the test passes correctly but when running golangci it gives me the error:
undeclared name: getProxyURL (typecheck)
if got := getProxyURL(tt.args.campaignCode, urls); got != tt.want {
^
func getProxyURL(campaignCode string, urls map[string]string) string {
if campaignURL, ok := urls[campaignCode]; ok {
return campaignURL
}
return "https://facebook.com"
}
_test
package main
import "testing"
func Test_getProxyURL(t *testing.T) {
type args struct {
campaignCode string
}
urls := make(map[string]string, 0)
urls["82383b80-056b-42e8-b192-9b0f33c4f46e"] = "https://google.com"
urls["negativeTest"] = "https://facebook.com"
tests := []struct {
name string
args args
want string
}{
{
name: "Given an invalid campaign code, we receive facebook url as result",
args: args{campaignCode: "negativeTest"},
want: "https://facebook.com",
}, {
name: "Given an valid campaign code, we receive google url as result",
args: args{campaignCode: "82383b80-056b-42e8-b192-9b0f33c4f46e"},
want: "https://google.com",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := getProxyURL(tt.args.campaignCode, urls); got != tt.want {
t.Errorf("getProxyURL() = %v, want %v", got, tt.want)
}
})
}
}
I cant find the problem
Related
I want to make an array optional in struct and use it with an if else in a func.
type TestValues struct {
Test1 string `json:"test1"`
DefaultTests []string `json:"__tests"`
//DefaultTests *array `json:"__tests,omitempty" validate:"option"`
Test2 string `json:"__Test2"`
}
func (x *Controller) createTest(context *gin.Context, uniqueId string, testBody *TestValues) (*http.Response, error) {
if testBody.DefaultTags {
postBody, err := json.Marshal(map[string]string{
"Test2": testBody.Test2,
"Test1": testBody.Test1,
"defaultTests": testBody.DefaultTests,
"uniqueId": uniqueId,
})
} else {
postBody, err := json.Marshal(map[string]string{
"Test2": testBody.Test2,
"Test1": testBody.Test1,
"uniqueId": uniqueId,
})
}
...
}
When I run the code it tells me that DefaultTests is undefined array but I don't want this error to pop because DefaultTests can existe and sometimes it won't be present in the json that's why I want to make it optional. The if else part is not working too.
It's better to use len() when checking if an array is empty here.
if len(testBody.DefaultTests) > 0 {
...
}
Check the Zero value of the DefaultTests in struct below for more clarity on this behaviour
package main
import "fmt"
type TestValues struct {
Test1 string `json:"test1"`
DefaultTests []string `json:"__tests"`
//DefaultTests *array `json:"__tests,omitempty" validate:"option"`
Test2 string `json:"__Test2"`
}
func main() {
var tv = TestValues{Test1: "test"}
if len(tv.DefaultTests) > 0 {
fmt.Printf("Default Tests: %v\n", tv.DefaultTests)
} else {
fmt.Printf("Default Tests empty value: %v\n", tv.DefaultTests)
}
}
Here's my final code with Marc's answer
func (x *Controller) createTest(context *gin.Context, uniqueId string, testBody *TestValues) (*http.Response, error) {
if len(testBody.DefaultTags) > 0 {
postBody, err := json.Marshal(testBody.DefaultTags)
} else {
postBody, err := json.Marshal(map[string]string{
"Test2": testBody.Test2,
"Test1": testBody.Test1,
"uniqueId": uniqueId,
})
}
...
}
I am trying to mock mysql, but occur error: "because: there are no expected calls of the method "Pod" for that receiver. "
I confirmed that I have generated the Pod method with the Mockgen tool,
Below is my code
func TestPodService_Create(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
mockFactory := store.NewMockFactory(ctrl)
mockPod := store.NewMockPodStore(ctrl)
pods := fake.FakePod(10)
mockPod.EXPECT().Create(gomock.Eq(context.TODO()), gomock.Eq(pods[0])).Return(nil)
type fields struct {
store store.Factory
redisCli redis.RedisCli
}
type args struct {
ctx context.Context
pod *model.Pod
}
tests := []struct {
name string
fields fields
args args
wantErr bool
}{
// TODO: Add test cases.
{
name: "test case 1",
fields: fields{store: mockFactory,},
args: args{
ctx: context.TODO(),
pod: &pods[0],
},
wantErr: false,
},
}
for _, tt := range tests {
fmt.Printf("begin to test\n")
podService := &PodService{store: tt.fields.store}
err := podService.Create(tt.args.ctx, tt.args.pod)
assert.Equal(t, tt.wantErr, err!=nil)
}
}
You need to include this line in your TestPodService_Create():
mockPod.EXPECT().Pod(gomock.Any()).AnyTimes()
Adjust the gomock.Any() and .AnyTimes() for your desired goals.
I have a case where I'm I have to support multiple versions. Each one has different data so I create 2 structs. Based on the version I will return 1 of the structs. Once I identify which struct, I then would request the data and Unmarshal into the struct. However, Since that struct satisfies an interface, I dont think the unmarshal is working correctly. I always get the zero value for the sctruct
package main
import (
"encoding/json"
"fmt"
)
// Ten300 ...
type Ten300 struct {
Map string `json:"map"`
Enabled string `json:"enabled"`
}
// Ten400 ...
type Ten400 struct {
Block1 int `json:"block_1"`
Block2 int `json:"block_2"`
}
// NET ...
type NET struct {
CMD Commands
S TenIft
}
// Commands ...
type Commands struct {
Get string
}
// TenIft ...
type TenIft interface {
Get(string) error
}
// Get ...
func (n *Ten300) Get(module string) error {
fmt.Println("Ten300", "Get()")
return nil
}
// Get ...
func (n *Ten400) Get(module string) error {
fmt.Println("Ten400", "Get()")
n.Block2 = 100
return nil
}
// TenGen easy to read fun type
type TenGen func() NET
// VersionSetup is a map of possible version
var VersionSetup = map[string]TenGen{
"3.0.0": func() NET {
return NET{
CMD: Commands{
Get: "getConfig",
},
S: &Ten300{},
}
},
"4.0.0": func() NET {
return NET{
CMD: Commands{
Get: "getSettings",
},
S: &Ten400{},
}
},
}
const input300 = `{
"map": "one",
"enabled": "two"
}`
const input400 = `{
"block_1": 1,
"block_2": 2
}`
// Setup ...
func (n *NET) Setup() error {
// This Switch is just to use hard coded data
var input string
switch n.S.(type) {
case *Ten400:
input = input400
case *Ten300:
input = input300
}
err := json.Unmarshal([]byte(input), n.S)
if err != nil {
fmt.Println("returning err:", err)
return err
}
fmt.Printf("n.s type: %T\nn.s value: %+v\n", n.S, n.S)
n.S.Get("xxx")
return nil
}
func main() {
version := "3.0.0"
if f, ok := VersionSetup[version]; ok {
net := f()
err := net.Setup()
if err != nil {
panic(err)
}
}
version = "4.0.0"
if f, ok := VersionSetup[version]; ok {
net := f()
err := net.Setup()
if err != nil {
panic(err)
}
}
}
Added go-playground ... this seems to work, but is this the best solution?
I want to mock function using interface and I was able to mock the first function callsomething
With great help from icza , Now it’s a bit more tricky . I want to test function vl1
With mock for function function1 , how it can be done.
https://play.golang.org/p/w367IOjADFV
package main
import (
"fmt"
"time"
"testing"
)
type vInterface interface {
function1() bool
}
type mStruct struct {
info string
time time.Time
}
func (s *mStruct) function1() bool {
return true
}
func callSomething(si vInterface) bool {
return si.function1()
}
func (s *mStruct) vl1() bool {
return callSomething(s)
}
var currentVt1 mStruct
func main() {
vl1 := currentVt1.vl1()
fmt.Println(vl1)
}
//——————————————————TESTS——————————————————
// This test is working as expected (as suggested by icza) for the function "callSomething"
// here we use mock interface and mock function which helps to mock function1
type mockedVInterface struct {
value bool
}
func (m mockedVInterface) fn1() bool {
return m.value
}
func Test_callSomething(t *testing.T) {
type args struct {
si vInterface
}
tests := []struct {
name string
args args
want bool
}{
{
name: "first value",
args: args{
si: mockedVInterface{value: false},
},
want: false,
},
{
name: "second value",
args: args{
si: mockedVInterface{value: true},
},
want: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := callSomething(tt.args.si); got != tt.want {
t.Errorf("callSomething() = %v, want %v", got, tt.want)
}
})
}
}
//----Here is the test which a bit tricky
//I want to call to "s.vl1()" and test it with mock for "function1"
func Test_mStruct_vl1(t *testing.T) {
type fields struct {
info string
time time.Time
}
tests := []struct {
name string
fields fields
want bool
}{
{
name: "test 2",
fields: struct {
info string
time time.Time
}{info: "myinfo", time: time.Now() },
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
s := &mStruct{
info: tt.fields.info,
time: tt.fields.time,
}
//here the test is starting
if got := s.vl1(); got != tt.want {
t.Errorf("mStruct.vl1() = %v, want %v", got, tt.want)
}
})
}
}
If you want to mock a function in Go you'll have to declare a variable that will hold the function value, have all callers of the function use the variable instead and then during tests you can switch up the function value for a mock implementation.
func callSomethingFunc(si vInterface) bool {
return si.function1()
}
var callSomething = callSomethingFunc
func (s *mStruct) vl1() bool {
return callSomething(s)
}
// ...
func Test_mStruct_vl1(t *testing.T) {
callSomething = func(si vInterface) bool { // set mock
// do mock stuff
}
defer func(){
callSomething = callSomethingFunc // set back original func at end of test
}()
// ...
Im using interface which I want to mock one method in it function1 in test and I wasn't able to figure it out how is the best to do it that for prod code it will provide 1 value and for test provide some mock value , can someone please give example ? (edited)
this is the code:
https://play.golang.org/p/w367IOjADFV
package main
import (
"fmt"
"time"
)
type vInterface interface {
function1() bool
}
type mStruct struct {
info string
time time.Time
}
func (s *mStruct) function1() bool {
return true
}
func callSomething(si vInterface) bool {
return si.function1()
}
func (s *mStruct) vl1() bool {
s.time = time.Now()
s.info = "vl1->info"
return callSomething(s)
}
var currentVt1 mStruct
func main() {
vl1 := currentVt1.vl1()
fmt.Println(vl1)
}
The test is like this
func Test_callSomething(t *testing.T) {
type args struct {
si vInterface
}
tests := []struct {
name string
args args
want bool
}{
{
name: "my tests",
args: args{
},
want: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := callSomething(tt.args.si); got != tt.want {
t.Errorf("callSomething() = %v, want %v", got, tt.want)
}
})
}
}
But not sure how to mock it right ...
update
func Test_mStruct_vl1(t *testing.T) {
type fields struct {
info string
time time.Time
}
tests := []struct {
name string
fields fields
want bool
}{
{
name: "some test",
fields: struct {
info string
time time.Time
}{info: "myinfo", time: time.Now() },
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
s := &mStruct{
info: tt.fields.info,
time: tt.fields.time,
}
if got := s.vl1(); got != tt.want {
t.Errorf("vl1() = %v, want %v", got, tt.want)
}
})
}
}
First you need a type (any type) that implements the vInterface interface. Here's a simple example:
type mockedVInterface struct {
value bool
}
func (m mockedVInterface) function1() bool {
return m.value
}
This is a simple enough implementation which we can control: we can tell what its function1() function should return by simply setting that value to its value field.
This mockedVInterface type is created solely for testing purposes, the production code does not need it. Put it in the same file where you have the test code (put it before Test_callSomething()).
And here's the testing code:
func Test_callSomething(t *testing.T) {
type args struct {
si vInterface
}
tests := []struct {
name string
args args
want bool
}{
{
name: "testing false",
args: args{
si: mockedVInterface{value: false},
},
want: false,
},
{
name: "testing true",
args: args{
si: mockedVInterface{value: true},
},
want: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := callSomething(tt.args.si); got != tt.want {
t.Errorf("callSomething() = %v, want %v", got, tt.want)
}
})
}
}
Note that in this simple case we could also use a simple non-struct type that has bool as its underlying type like this:
type mockedVInterface bool
func (m mockedVInterface) function1() bool {
return bool(m)
}
And it works and testing code is also simpler:
tests := []struct {
name string
args args
want bool
}{
{
name: "testing false",
args: args{
si: mockedVInterface(false),
},
want: false,
},
{
name: "testing true",
args: args{
si: mockedVInterface(true),
},
want: true,
},
}
But this only works if the mockable interface has a single function with a single return value. In the general case a struct is needed.