github.com/keysonzzz/kmg@v0.0.0-20151121023212-05317bfd7d39/kmgControllerRunner/kmgControllerTest/MockKmgController_test.go (about)

     1  package kmgControllerTest
     2  
     3  import (
     4  	"io/ioutil"
     5  	"os"
     6  	"strconv"
     7  	"testing"
     8  
     9  	"github.com/bronze1man/kmg/kmgControllerRunner"
    10  	"github.com/bronze1man/kmg/kmgNet/kmgHttp"
    11  	. "github.com/bronze1man/kmg/kmgTest"
    12  )
    13  
    14  var i int = 1
    15  
    16  func TestMockCallApi(t *testing.T) {
    17  	c := kmgHttp.NewTestContext().
    18  		SetPost().
    19  		SetInStr("a", "1")
    20  	TestObj{}.TestFunc(c)
    21  	Equal(c.GetResponseString(), "2")
    22  }
    23  
    24  func TestCallApiGet(t *testing.T) {
    25  	kmgControllerRunner.RegisterController(TestObj{})
    26  	out := CallApiByHttp(
    27  		"/?n=github.com.bronze1man.kmg.kmgControllerRunner.kmgControllerTest.TestObj.TestFunc&a=10",
    28  		kmgHttp.NewTestContext(),
    29  	)
    30  	Equal(out, "11")
    31  }
    32  
    33  func TestCallApiPost(t *testing.T) {
    34  	kmgControllerRunner.RegisterController(TestObj{})
    35  	out := CallApiByHttp(
    36  		"/?n=github.com.bronze1man.kmg.kmgControllerRunner.kmgControllerTest.TestObj.TestFunc",
    37  		kmgHttp.NewTestContext().
    38  			SetPost().
    39  			SetInStr("a", "1"))
    40  	Equal(out, "2")
    41  }
    42  
    43  func TestUploadFile(t *testing.T) {
    44  	testFileRealPath := "/tmp/UFile.md"
    45  	file, err := os.Create(testFileRealPath)
    46  	defer file.Close()
    47  	if err != nil {
    48  		panic(err)
    49  	}
    50  	file.WriteString("hello")
    51  	file.Close()
    52  	kmgControllerRunner.RegisterController(TestObj{})
    53  	out := CallApiByHttpWithUploadFile("/?n=github.com.bronze1man.kmg.kmgControllerRunner.kmgControllerTest.TestObj.TestHandleUploadFile",
    54  		kmgHttp.NewTestContext().
    55  			SetPost().
    56  			SetInStr("a", "10"),
    57  		map[string]string{
    58  			"UFile": "/tmp/UFile.md",
    59  		},
    60  	)
    61  	Equal(out, "UFile.md 10 hello")
    62  }
    63  
    64  type TestObj struct{}
    65  
    66  func (t TestObj) TestFunc(ctx *kmgHttp.Context) {
    67  	a := ctx.InNum("a")
    68  	ctx.WriteString(strconv.Itoa(a + i))
    69  }
    70  
    71  func (t TestObj) TestHandleUploadFile(ctx *kmgHttp.Context) {
    72  	fileInfo := ctx.MustInFile("UFile")
    73  	file, err := fileInfo.Open()
    74  	if err != nil {
    75  		panic(err)
    76  	}
    77  	defer file.Close()
    78  	content, err := ioutil.ReadAll(file)
    79  	if err != nil {
    80  		panic(err)
    81  	}
    82  	a := ctx.InStr("a")
    83  	ctx.WriteString(fileInfo.Filename)
    84  	ctx.WriteString(" ")
    85  	ctx.WriteString(a)
    86  	ctx.WriteString(" ")
    87  	ctx.WriteString(string(content))
    88  }