How can I pass data from controller to form in go lang? - api

I have a handler / controller that takes in an http request.
func UpdateHandler(request *http.Request) {
ID := mux.Vars(request)["ID"]
UpdateForm.Save(ID,db)
}
Then I have a form that I want to process the data and eventually update it.
type UpdateForm struct {
ID string `json:"type"`
}
func (UpdateForm) Save(db mongo.Database) {
id := ID
repository.Update(Id)
}
Go will print out undefined ID
How can I make sure that the form gets the value from the controller?

You can populate your form using data from the request. If your request contains a JSON encoded body than you could decode it into your form object like this:
package main
import (
"encoding/json"
"net/http"
"strings"
"fmt"
)
type UpdateForm struct {
ID string `json:"type"`
}
func main() {
req, _ := http.NewRequest(
"POST",
"http://example.com",
strings.NewReader(`{"type": "foo"}`),
)
var form *UpdateForm
json.NewDecoder(req.Body).Decode(&form)
fmt.Println(form.ID) // Output: foo
}
Or you can instantiate it directly like this:
func UpdateHandler(request *http.Request) {
ID := mux.Vars(request)["ID"]
form := &UpdateForm{ID: ID}
form.Save()
}

I think it has nothing to do with the handler, but your code isn't consistent. This line
UpdateForm.Save(ID,db)
The method Save() takes two arguments, while the original method signature takes only a single mongo.Database type argument.
Here is what I assume was your intention:
type UpdateForm struct {
ID string `json:"type"`
}
func (u UpdateForm) Save(db mongo.Database) {
id := u.ID
repository.Update(id)
}
// UpdateForm instance somewhere
var u = UpdateForm{}
func UpdateHandler(request *http.Request) {
u.ID := mux.Vars(request)["ID"]
u.Save(db)
}

Related

Mocking function in Golang without using a function type or passing mock function as parameter

I want to test LoadPage and GetData function. While testing LoadPage, I want to mock GetData function, how to do that?
Don't want to use something like this type PageGetter func(url string) string and pass mock func as parameter
package main
import (
"net/http"
"os"
"fmt"
"io/ioutil"
)
func GetData(url string) (*http.Response,error){
return http.Get(url)
}
func LoadPage(url string) {
resp,err := GetData(url)
if err != nil {
os.Exit(0)
}
data,err :=ioutil.ReadAll(resp.Body)
fmt.Println(string(data))
}
func main() {
var url string
fmt.Scanf("%s", &url)
LoadPage(url)
}

can we pass extra parameter to a beego router

type MainController struct {
beego.Controller
}
func (this *MainController) Post() {
var datapoint User
req := this.Ctx.Input.RequestBody
json.Unmarshal([]byte(req), &datapoint)
this.Ctx.WriteString("hello world")
// result := this.Input()
fmt.Println("input value is", datapoint.UserId)
}
this is normal beego router which executes on url occurrence. I want something like
type MainController struct {
beego.Controller
}
func (this *MainController,db *sql.DB) Post() {
fmt.Println("input value is", datapoint.UserId)
}
in order to use database connection pointer. is this possible to achieve this using go...if not please suggest
You can't do this in golang
type MainController struct {
beego.Controller }
func (this *MainController,db *sql.DB) Post() {
fmt.Println("input value is", datapoint.UserId)
}
the declaration in the form
function (c *MainController)Post()
means that Post is a method for the MainController struct you can pass variable into it.
My suggestion is you declare the db pointer as a global variable in your package like below then you will be able to use it inside the Post function
type MainController struct {
beego.Controller
}
var db *sql.DB
func (this *MainController) Post() {
//you can now use the variable db inside here
fmt.Println("input value is", datapoint.UserId)
}
but considering this is Beego which uses the MVC pattern you can do all this from within the model. I suggest you take a look at their awesome documentation here

How to test Go function containing log.Fatal()

Say, I had the following code that prints some log messages. How would I go about testing that the correct messages have been logged? As log.Fatal calls os.Exit(1) the tests fail.
package main
import (
"log"
)
func hello() {
log.Print("Hello!")
}
func goodbye() {
log.Fatal("Goodbye!")
}
func init() {
log.SetFlags(0)
}
func main() {
hello()
goodbye()
}
Here are the hypothetical tests:
package main
import (
"bytes"
"log"
"testing"
)
func TestHello(t *testing.T) {
var buf bytes.Buffer
log.SetOutput(&buf)
hello()
wantMsg := "Hello!\n"
msg := buf.String()
if msg != wantMsg {
t.Errorf("%#v, wanted %#v", msg, wantMsg)
}
}
func TestGoodby(t *testing.T) {
var buf bytes.Buffer
log.SetOutput(&buf)
goodbye()
wantMsg := "Goodbye!\n"
msg := buf.String()
if msg != wantMsg {
t.Errorf("%#v, wanted %#v", msg, wantMsg)
}
}
This is similar to "How to test os.Exit() scenarios in Go": you need to implement your own logger, which by default redirect to log.xxx(), but gives you the opportunity, when testing, to replace a function like log.Fatalf() with your own (which does not call os.Exit(1))
I did the same for testing os.Exit() calls in exit/exit.go:
exiter = New(func(int) {})
exiter.Exit(3)
So(exiter.Status(), ShouldEqual, 3)
(here, my "exit" function is an empty one which does nothing)
While it's possible to test code that contains log.Fatal, it is not recommended. In particular you cannot test that code in a way that is supported by the -cover flag on go test.
Instead it is recommended that you change your code to return an error instead of calling log.Fatal. In a sequential function you can add an additional return value, and in a goroutine you can pass an error on a channel of type chan error (or some struct type containing a field of type error).
Once that change is made your code will be much easier to read, much easier to test, and it will be more portable (now you can use it in a server program in addition to command line tools).
If you have log.Println calls I also recommend passing a custom logger as a field on a receiver. That way you can log to the custom logger, which you can set to stderr or stdout for a server, and a noop logger for tests (so you don't get a bunch of unnecessary output in your tests). The log package supports custom loggers, so there's no need to write your own or import a third party package for this.
If you're using logrus, there's now an option to define your exit function from v1.3.0 introduced in this commit. So your test may look something like:
func Test_X(t *testing.T) {
cases := []struct{
param string
expectFatal bool
}{
{
param: "valid",
expectFatal: false,
},
{
param: "invalid",
expectFatal: true,
},
}
defer func() { log.StandardLogger().ExitFunc = nil }()
var fatal bool
log.StandardLogger().ExitFunc = func(int){ fatal = true }
for _, c := range cases {
fatal = false
X(c.param)
assert.Equal(t, c.expectFatal, fatal)
}
}
I have using the following code to test my function. In xxx.go:
var logFatalf = log.Fatalf
if err != nil {
logFatalf("failed to init launcher, err:%v", err)
}
And in xxx_test.go:
// TestFatal is used to do tests which are supposed to be fatal
func TestFatal(t *testing.T) {
origLogFatalf := logFatalf
// After this test, replace the original fatal function
defer func() { logFatalf = origLogFatalf } ()
errors := []string{}
logFatalf = func(format string, args ...interface{}) {
if len(args) > 0 {
errors = append(errors, fmt.Sprintf(format, args))
} else {
errors = append(errors, format)
}
}
if len(errors) != 1 {
t.Errorf("excepted one error, actual %v", len(errors))
}
}
I'd use the supremely handy bouk/monkey package (here along with stretchr/testify).
func TestGoodby(t *testing.T) {
wantMsg := "Goodbye!"
fakeLogFatal := func(msg ...interface{}) {
assert.Equal(t, wantMsg, msg[0])
panic("log.Fatal called")
}
patch := monkey.Patch(log.Fatal, fakeLogFatal)
defer patch.Unpatch()
assert.PanicsWithValue(t, "log.Fatal called", goodbye, "log.Fatal was not called")
}
I advise reading the caveats to using bouk/monkey before going this route.
There used to be an answer here that I referred to, looks like it got deleted. It was the only one I've seen where you could have passing tests without modifying dependencies or otherwise touching the code that should Fatal.
I agree with other answers that this is usually an inappropriate test. Usually you should rewrite the code under test to return an error, test the error is returned as expected, and Fatal at a higher level scope after observing the non-nil error.
To OP's question of testing that the that the correct messages have been logged, you would inspect inner process's cmd.Stdout.
https://play.golang.org/p/J8aiO9_NoYS
func TestFooFatals(t *testing.T) {
fmt.Println("TestFooFatals")
outer := os.Getenv("FATAL_TESTING") == ""
if outer {
fmt.Println("Outer process: Spawning inner `go test` process, looking for failure from fatal")
cmd := exec.Command(os.Args[0], "-test.run=TestFooFatals")
cmd.Env = append(os.Environ(), "FATAL_TESTING=1")
// cmd.Stdout, cmd.Stderr = os.Stdout, os.Stderr
err := cmd.Run()
fmt.Printf("Outer process: Inner process returned %v\n", err)
if e, ok := err.(*exec.ExitError); ok && !e.Success() {
// fmt.Println("Success: inner process returned 1, passing test")
return
}
t.Fatalf("Failure: inner function returned %v, want exit status 1", err)
} else {
// We're in the spawned process.
// Do something that should fatal so this test fails.
foo()
}
}
// should fatal every time
func foo() {
log.Printf("oh my goodness, i see %q\n", os.Getenv("FATAL_TESTING"))
// log.Fatal("oh my gosh")
}
I've combined answers from different sources to produce this:
import (
"bufio"
"bytes"
"errors"
"fmt"
"io/ioutil"
"log"
"os"
"os/exec"
"os/user"
"strings"
"testing"
"bou.ke/monkey"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
"github.com/stretchr/testify/require"
)
func TestCommandThatErrors(t *testing.T) {
fakeExit := func(int) {
panic("os.Exit called")
}
patch := monkey.Patch(os.Exit, fakeExit)
defer patch.Unpatch()
var buf bytes.Buffer
log.SetOutput(&buf)
for _, tc := range []struct {
cliArgs []string
expectedError string
}{
{
cliArgs: []string{"dev", "api", "--dockerless"},
expectedError: "Some services don't have dockerless variants implemented yet.",
},
} {
t.Run(strings.Join(tc.cliArgs, " "), func(t *testing.T) {
harness := createTestApp()
for _, cmd := range commands {
cmd(harness.app)
}
assert.Panics(t, func() { harness.app.run(tc.cliArgs) })
assert.Contains(t, buf.String(), tc.expectedError)
buf.Reset()
})
}
}
Works great :)
You cannot and you should not.
This "you must 'test' each and every line"-attitude is strange, especially for terminal conditions and that's what log.Fatal is for.
(Or just test it from the outside.)

How to separate models from controllers in testing?

So I wanted to isolate controllers from models in testing so that I could easily figure out stuff if troubles arise. Before, I just hit the endpoints with mock data but it was difficult to troubleshoot because the test runs from the router all the way to the datastore. So I'm thinking maybe I'll just create two versions(MockController vs Controller) for each controller(and model) and use one depending on the value of the mode variable. In a nutshell, this is how I plan to implement it.
const mode string = "test"
// UserModelInterface is the Interface for UserModel
type UserModelInterface interface {
Get()
}
// UserControllerInterface is the Interface for UserController
type UserControllerInterface interface {
Login()
}
// NewUserModel returns a new instance of user model
func NewUserModel() UserModelInterface {
if mode == "test" {
return &MockUserModel{}
} else {
return &UserModel{}
}
}
// NewUserController returns a new instance of user controller
func NewUserController(um UserModelInterface) UserControllerInterface {
if mode == "test" {
return &MockUserController{}
} else {
return &UserController{}
}
}
type (
UserController struct {um UserModelInterface}
UserModel struct {}
// Mocks
MockUserController struct {um UserModelInterface}
MockUserModel struct {}
)
func (uc *UserController) Login() {}
func (um *UserModel) Get() {}
func (uc *MockUserController) Login() {}
func (um *MockUserModel) Get() {}
func main() {
um := NewUserModel()
uc := NewUserController(um)
}
This way I could just skip sql query in the MockUserController.Login() and only validate the payload and return a valid response.
What do you think of this design? Do you have a better implementation in mind?
I would let the code that calls NewUserController() and NewUserModel() decide whether to create a mock or real implementation. If you use that pattern of dependency injection all the way up to the top your code will become clearer and less tightly coupled. E.g. if the user controller is used by a server, it would look something like along the lines of:
Real:
u := NewUserController()
s := NewServer(u)
In tests:
u := NewMockUserController()
s := NewServer(u)
I would try a more slim variant spread over a models and a controllers package, like this:
// inside package controllers
type UserModel interface {
Get() // the methods you need from the user model
}
type User struct {
UserModel
}
// inside package models
type User struct {
// here the User Model
}
// inside package main
import ".....controllers"
import ".....models"
func main() {
c := &controllers.User{&models.User{}}
}
// inside main_test.go
import ".....controllers"
type MockUser struct {
}
func TestX(t *testing.T) {
c := &controllers.User{&MockUser{}}
}
For controller testing consider the ResponseRecorder of httptest package

How to test os.exit scenarios in Go

Given this code
func doomed() {
os.Exit(1)
}
How do I properly test that calling this function will result in an exit using go test? This needs to occur within a suite of tests, in other words the os.Exit() call cannot impact the other tests and should be trapped.
There's a presentation by Andrew Gerrand (one of the core members of the Go team) where he shows how to do it.
Given a function (in main.go)
package main
import (
"fmt"
"os"
)
func Crasher() {
fmt.Println("Going down in flames!")
os.Exit(1)
}
here's how you would test it (through main_test.go):
package main
import (
"os"
"os/exec"
"testing"
)
func TestCrasher(t *testing.T) {
if os.Getenv("BE_CRASHER") == "1" {
Crasher()
return
}
cmd := exec.Command(os.Args[0], "-test.run=TestCrasher")
cmd.Env = append(os.Environ(), "BE_CRASHER=1")
err := cmd.Run()
if e, ok := err.(*exec.ExitError); ok && !e.Success() {
return
}
t.Fatalf("process ran with err %v, want exit status 1", err)
}
What the code does is invoke go test again in a separate process through exec.Command, limiting execution to the TestCrasher test (via the -test.run=TestCrasher switch). It also passes in a flag via an environment variable (BE_CRASHER=1) which the second invocation checks for and, if set, calls the system-under-test, returning immediately afterwards to prevent running into an infinite loop. Thus, we are being dropped back into our original call site and may now validate the actual exit code.
Source: Slide 23 of Andrew's presentation. The second slide contains a link to the presentation's video as well.
He talks about subprocess tests at 47:09
I do this by using bouk/monkey:
func TestDoomed(t *testing.T) {
fakeExit := func(int) {
panic("os.Exit called")
}
patch := monkey.Patch(os.Exit, fakeExit)
defer patch.Unpatch()
assert.PanicsWithValue(t, "os.Exit called", doomed, "os.Exit was not called")
}
monkey is super-powerful when it comes to this sort of work, and for fault injection and other difficult tasks. It does come with some caveats.
I don't think you can test the actual os.Exit without simulating testing from the outside (using exec.Command) process.
That said, you might be able to accomplish your goal by creating an interface or function type and then use a noop implementation in your tests:
Go Playground
package main
import "os"
import "fmt"
type exiter func (code int)
func main() {
doExit(func(code int){})
fmt.Println("got here")
doExit(func(code int){ os.Exit(code)})
}
func doExit(exit exiter) {
exit(1)
}
You can't, you would have to use exec.Command and test the returned value.
Code for testing:
package main
import "os"
var my_private_exit_function func(code int) = os.Exit
func main() {
MyAbstractFunctionAndExit(1)
}
func MyAbstractFunctionAndExit(exit int) {
my_private_exit_function(exit)
}
Testing code:
package main
import (
"os"
"testing"
)
func TestMyAbstractFunctionAndExit(t *testing.T) {
var ok bool = false // The default value can be omitted :)
// Prepare testing
my_private_exit_function = func(c int) {
ok = true
}
// Run function
MyAbstractFunctionAndExit(1)
// Check
if ok == false {
t.Errorf("Error in AbstractFunction()")
}
// Restore if need
my_private_exit_function = os.Exit
}
To test the os.Exit like scenarios we can use the https://github.com/undefinedlabs/go-mpatch along with the below code. This ensures that your code remains clean as well as readable and maintainable.
type PatchedOSExit struct {
Called bool
CalledWith int
patchFunc *mpatch.Patch
}
func PatchOSExit(t *testing.T, mockOSExitImpl func(int)) *PatchedOSExit {
patchedExit := &PatchedOSExit{Called: false}
patchFunc, err := mpatch.PatchMethod(os.Exit, func(code int) {
patchedExit.Called = true
patchedExit.CalledWith = code
mockOSExitImpl(code)
})
if err != nil {
t.Errorf("Failed to patch os.Exit due to an error: %v", err)
return nil
}
patchedExit.patchFunc = patchFunc
return patchedExit
}
func (p *PatchedOSExit) Unpatch() {
_ = p.patchFunc.Unpatch()
}
You can consume the above code as follows:
func NewSampleApplication() {
os.Exit(101)
}
func Test_NewSampleApplication_OSExit(t *testing.T) {
// Prepare mock setup
fakeExit := func(int) {}
p := PatchOSExit(t, fakeExit)
defer p.Unpatch()
// Call the application code
NewSampleApplication()
// Assert that os.Exit gets called
if p.Called == false {
t.Errorf("Expected os.Exit to be called but it was not called")
return
}
// Also, Assert that os.Exit gets called with the correct code
expectedCalledWith := 101
if p.CalledWith != expectedCalledWith {
t.Errorf("Expected os.Exit to be called with %d but it was called with %d", expectedCalledWith, p.CalledWith)
return
}
}
I've also added a link to Playground: https://go.dev/play/p/FA0dcwVDOm7