github.com/gogf/gf@v1.16.9/net/ghttp/ghttp_unit_client_test.go (about)

     1  // Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
     2  //
     3  // This Source Code Form is subject to the terms of the MIT License.
     4  // If a copy of the MIT was not distributed with this file,
     5  // You can obtain one at https://github.com/gogf/gf.
     6  
     7  package ghttp_test
     8  
     9  import (
    10  	"bytes"
    11  	"context"
    12  	"fmt"
    13  	"io/ioutil"
    14  	"net/http"
    15  	"testing"
    16  	"time"
    17  
    18  	"github.com/gogf/gf/debug/gdebug"
    19  	"github.com/gogf/gf/errors/gerror"
    20  	"github.com/gogf/gf/os/gfile"
    21  	"github.com/gogf/gf/util/guid"
    22  
    23  	"github.com/gogf/gf/frame/g"
    24  	"github.com/gogf/gf/net/ghttp"
    25  	"github.com/gogf/gf/test/gtest"
    26  )
    27  
    28  func Test_Client_Basic(t *testing.T) {
    29  	p, _ := ports.PopRand()
    30  	s := g.Server(p)
    31  	s.BindHandler("/hello", func(r *ghttp.Request) {
    32  		r.Response.Write("hello")
    33  	})
    34  	s.SetPort(p)
    35  	s.SetDumpRouterMap(false)
    36  	s.Start()
    37  	defer s.Shutdown()
    38  
    39  	time.Sleep(100 * time.Millisecond)
    40  	gtest.C(t, func(t *gtest.T) {
    41  		url := fmt.Sprintf("http://127.0.0.1:%d", p)
    42  		client := g.Client()
    43  		client.SetPrefix(url)
    44  
    45  		t.Assert(ghttp.GetContent(""), ``)
    46  		t.Assert(client.GetContent("/hello"), `hello`)
    47  
    48  		_, err := ghttp.Post("")
    49  		t.AssertNE(err, nil)
    50  	})
    51  }
    52  
    53  func Test_Client_BasicAuth(t *testing.T) {
    54  	p, _ := ports.PopRand()
    55  	s := g.Server(p)
    56  	s.BindHandler("/auth", func(r *ghttp.Request) {
    57  		if r.BasicAuth("admin", "admin") {
    58  			r.Response.Write("1")
    59  		} else {
    60  			r.Response.Write("0")
    61  		}
    62  	})
    63  	s.SetPort(p)
    64  	s.SetDumpRouterMap(false)
    65  	s.Start()
    66  	defer s.Shutdown()
    67  
    68  	time.Sleep(100 * time.Millisecond)
    69  	gtest.C(t, func(t *gtest.T) {
    70  		c := g.Client()
    71  		c.SetPrefix(fmt.Sprintf("http://127.0.0.1:%d", p))
    72  		t.Assert(c.BasicAuth("admin", "123").GetContent("/auth"), "0")
    73  		t.Assert(c.BasicAuth("admin", "admin").GetContent("/auth"), "1")
    74  	})
    75  }
    76  
    77  func Test_Client_Cookie(t *testing.T) {
    78  	p, _ := ports.PopRand()
    79  	s := g.Server(p)
    80  	s.BindHandler("/cookie", func(r *ghttp.Request) {
    81  		r.Response.Write(r.Cookie.Get("test"))
    82  	})
    83  	s.SetPort(p)
    84  	s.SetDumpRouterMap(false)
    85  	s.Start()
    86  	defer s.Shutdown()
    87  
    88  	time.Sleep(100 * time.Millisecond)
    89  	gtest.C(t, func(t *gtest.T) {
    90  		c := g.Client()
    91  		c.SetPrefix(fmt.Sprintf("http://127.0.0.1:%d", p))
    92  
    93  		c.SetCookie("test", "0123456789")
    94  		t.Assert(c.PostContent("/cookie"), "0123456789")
    95  	})
    96  }
    97  
    98  func Test_Client_MapParam(t *testing.T) {
    99  	p, _ := ports.PopRand()
   100  	s := g.Server(p)
   101  	s.BindHandler("/map", func(r *ghttp.Request) {
   102  		r.Response.Write(r.Get("test"))
   103  	})
   104  	s.SetPort(p)
   105  	s.SetDumpRouterMap(false)
   106  	s.Start()
   107  	defer s.Shutdown()
   108  
   109  	time.Sleep(100 * time.Millisecond)
   110  	gtest.C(t, func(t *gtest.T) {
   111  		c := g.Client()
   112  		c.SetPrefix(fmt.Sprintf("http://127.0.0.1:%d", p))
   113  
   114  		t.Assert(c.GetContent("/map", g.Map{"test": "1234567890"}), "1234567890")
   115  	})
   116  }
   117  
   118  func Test_Client_Cookies(t *testing.T) {
   119  	p, _ := ports.PopRand()
   120  	s := g.Server(p)
   121  	s.BindHandler("/cookie", func(r *ghttp.Request) {
   122  		r.Cookie.Set("test1", "1")
   123  		r.Cookie.Set("test2", "2")
   124  		r.Response.Write("ok")
   125  	})
   126  	s.SetPort(p)
   127  	s.SetDumpRouterMap(false)
   128  	s.Start()
   129  	defer s.Shutdown()
   130  
   131  	time.Sleep(100 * time.Millisecond)
   132  	gtest.C(t, func(t *gtest.T) {
   133  		c := g.Client()
   134  		c.SetPrefix(fmt.Sprintf("http://127.0.0.1:%d", p))
   135  
   136  		resp, err := c.Get("/cookie")
   137  		t.Assert(err, nil)
   138  		defer resp.Close()
   139  
   140  		t.AssertNE(resp.Header.Get("Set-Cookie"), "")
   141  
   142  		m := resp.GetCookieMap()
   143  		t.Assert(len(m), 2)
   144  		t.Assert(m["test1"], 1)
   145  		t.Assert(m["test2"], 2)
   146  		t.Assert(resp.GetCookie("test1"), 1)
   147  		t.Assert(resp.GetCookie("test2"), 2)
   148  	})
   149  }
   150  
   151  func Test_Client_Chain_Header(t *testing.T) {
   152  	p, _ := ports.PopRand()
   153  	s := g.Server(p)
   154  	s.BindHandler("/header1", func(r *ghttp.Request) {
   155  		r.Response.Write(r.Header.Get("test1"))
   156  	})
   157  	s.BindHandler("/header2", func(r *ghttp.Request) {
   158  		r.Response.Write(r.Header.Get("test2"))
   159  	})
   160  	s.SetPort(p)
   161  	s.SetDumpRouterMap(false)
   162  	s.Start()
   163  	defer s.Shutdown()
   164  
   165  	time.Sleep(100 * time.Millisecond)
   166  	gtest.C(t, func(t *gtest.T) {
   167  		c := g.Client()
   168  		c.SetPrefix(fmt.Sprintf("http://127.0.0.1:%d", p))
   169  
   170  		t.Assert(c.Header(g.MapStrStr{"test1": "1234567890"}).GetContent("/header1"), "1234567890")
   171  		t.Assert(c.HeaderRaw("test1: 1234567890\ntest2: abcdefg").GetContent("/header1"), "1234567890")
   172  		t.Assert(c.HeaderRaw("test1: 1234567890\ntest2: abcdefg").GetContent("/header2"), "abcdefg")
   173  	})
   174  }
   175  
   176  func Test_Client_Chain_Context(t *testing.T) {
   177  	p, _ := ports.PopRand()
   178  	s := g.Server(p)
   179  	s.BindHandler("/context", func(r *ghttp.Request) {
   180  		time.Sleep(1 * time.Second)
   181  		r.Response.Write("ok")
   182  	})
   183  	s.SetPort(p)
   184  	s.SetDumpRouterMap(false)
   185  	s.Start()
   186  	defer s.Shutdown()
   187  
   188  	time.Sleep(100 * time.Millisecond)
   189  	gtest.C(t, func(t *gtest.T) {
   190  		c := g.Client()
   191  		c.SetPrefix(fmt.Sprintf("http://127.0.0.1:%d", p))
   192  
   193  		ctx, _ := context.WithTimeout(context.Background(), 100*time.Millisecond)
   194  		t.Assert(c.Ctx(ctx).GetContent("/context"), "")
   195  
   196  		ctx, _ = context.WithTimeout(context.Background(), 2000*time.Millisecond)
   197  		t.Assert(c.Ctx(ctx).GetContent("/context"), "ok")
   198  	})
   199  }
   200  
   201  func Test_Client_Chain_Timeout(t *testing.T) {
   202  	p, _ := ports.PopRand()
   203  	s := g.Server(p)
   204  	s.BindHandler("/timeout", func(r *ghttp.Request) {
   205  		time.Sleep(1 * time.Second)
   206  		r.Response.Write("ok")
   207  	})
   208  	s.SetPort(p)
   209  	s.SetDumpRouterMap(false)
   210  	s.Start()
   211  	defer s.Shutdown()
   212  
   213  	time.Sleep(100 * time.Millisecond)
   214  	gtest.C(t, func(t *gtest.T) {
   215  		c := g.Client()
   216  		c.SetPrefix(fmt.Sprintf("http://127.0.0.1:%d", p))
   217  		t.Assert(c.Timeout(100*time.Millisecond).GetContent("/timeout"), "")
   218  		t.Assert(c.Timeout(2000*time.Millisecond).GetContent("/timeout"), "ok")
   219  	})
   220  }
   221  
   222  func Test_Client_Chain_ContentJson(t *testing.T) {
   223  	p, _ := ports.PopRand()
   224  	s := g.Server(p)
   225  	s.BindHandler("/json", func(r *ghttp.Request) {
   226  		r.Response.Write(r.Get("name"), r.Get("score"))
   227  	})
   228  	s.SetPort(p)
   229  	s.SetDumpRouterMap(false)
   230  	s.Start()
   231  	defer s.Shutdown()
   232  
   233  	time.Sleep(100 * time.Millisecond)
   234  	gtest.C(t, func(t *gtest.T) {
   235  		c := g.Client()
   236  		c.SetPrefix(fmt.Sprintf("http://127.0.0.1:%d", p))
   237  		t.Assert(c.ContentJson().PostContent("/json", g.Map{
   238  			"name":  "john",
   239  			"score": 100,
   240  		}), "john100")
   241  		t.Assert(c.ContentJson().PostContent("/json", `{"name":"john", "score":100}`), "john100")
   242  
   243  		type User struct {
   244  			Name  string `json:"name"`
   245  			Score int    `json:"score"`
   246  		}
   247  		t.Assert(c.ContentJson().PostContent("/json", User{"john", 100}), "john100")
   248  	})
   249  }
   250  
   251  func Test_Client_Chain_ContentXml(t *testing.T) {
   252  	p, _ := ports.PopRand()
   253  	s := g.Server(p)
   254  	s.BindHandler("/xml", func(r *ghttp.Request) {
   255  		r.Response.Write(r.Get("name"), r.Get("score"))
   256  	})
   257  	s.SetPort(p)
   258  	s.SetDumpRouterMap(false)
   259  	s.Start()
   260  	defer s.Shutdown()
   261  
   262  	time.Sleep(100 * time.Millisecond)
   263  	gtest.C(t, func(t *gtest.T) {
   264  		c := g.Client()
   265  		c.SetPrefix(fmt.Sprintf("http://127.0.0.1:%d", p))
   266  		t.Assert(c.ContentXml().PostContent("/xml", g.Map{
   267  			"name":  "john",
   268  			"score": 100,
   269  		}), "john100")
   270  		t.Assert(c.ContentXml().PostContent("/xml", `{"name":"john", "score":100}`), "john100")
   271  
   272  		type User struct {
   273  			Name  string `json:"name"`
   274  			Score int    `json:"score"`
   275  		}
   276  		t.Assert(c.ContentXml().PostContent("/xml", User{"john", 100}), "john100")
   277  	})
   278  }
   279  
   280  func Test_Client_Param_Containing_Special_Char(t *testing.T) {
   281  	p, _ := ports.PopRand()
   282  	s := g.Server(p)
   283  	s.BindHandler("/", func(r *ghttp.Request) {
   284  		r.Response.Write("k1=", r.Get("k1"), "&k2=", r.Get("k2"))
   285  	})
   286  	s.SetPort(p)
   287  	s.SetDumpRouterMap(false)
   288  	s.Start()
   289  	defer s.Shutdown()
   290  
   291  	time.Sleep(100 * time.Millisecond)
   292  	gtest.C(t, func(t *gtest.T) {
   293  		c := g.Client()
   294  		c.SetPrefix(fmt.Sprintf("http://127.0.0.1:%d", p))
   295  		t.Assert(c.PostContent("/", "k1=MTIxMg==&k2=100"), "k1=MTIxMg==&k2=100")
   296  		t.Assert(c.PostContent("/", g.Map{
   297  			"k1": "MTIxMg==",
   298  			"k2": 100,
   299  		}), "k1=MTIxMg==&k2=100")
   300  	})
   301  }
   302  
   303  // It posts data along with file uploading.
   304  // It does not url-encodes the parameters.
   305  func Test_Client_File_And_Param(t *testing.T) {
   306  	p, _ := ports.PopRand()
   307  	s := g.Server(p)
   308  	s.BindHandler("/", func(r *ghttp.Request) {
   309  		tmpPath := gfile.TempDir(guid.S())
   310  		err := gfile.Mkdir(tmpPath)
   311  		gtest.Assert(err, nil)
   312  		defer gfile.Remove(tmpPath)
   313  
   314  		file := r.GetUploadFile("file")
   315  		_, err = file.Save(tmpPath)
   316  		gtest.Assert(err, nil)
   317  		r.Response.Write(
   318  			r.Get("json"),
   319  			gfile.GetContents(gfile.Join(tmpPath, gfile.Basename(file.Filename))),
   320  		)
   321  	})
   322  	s.SetPort(p)
   323  	s.SetDumpRouterMap(false)
   324  	s.Start()
   325  	defer s.Shutdown()
   326  
   327  	time.Sleep(100 * time.Millisecond)
   328  
   329  	gtest.C(t, func(t *gtest.T) {
   330  		path := gdebug.TestDataPath("upload", "file1.txt")
   331  		data := g.Map{
   332  			"file": "@file:" + path,
   333  			"json": `{"uuid": "luijquiopm", "isRelative": false, "fileName": "test111.xls"}`,
   334  		}
   335  		c := g.Client()
   336  		c.SetPrefix(fmt.Sprintf("http://127.0.0.1:%d", p))
   337  		t.Assert(c.PostContent("/", data), data["json"].(string)+gfile.GetContents(path))
   338  	})
   339  }
   340  
   341  func Test_Client_Middleware(t *testing.T) {
   342  	p, _ := ports.PopRand()
   343  	s := g.Server(p)
   344  	isServerHandler := false
   345  	s.BindHandler("/", func(r *ghttp.Request) {
   346  		isServerHandler = true
   347  	})
   348  	s.SetPort(p)
   349  	s.SetDumpRouterMap(false)
   350  	s.Start()
   351  	defer s.Shutdown()
   352  
   353  	time.Sleep(100 * time.Millisecond)
   354  
   355  	gtest.C(t, func(t *gtest.T) {
   356  		var (
   357  			str1 = ""
   358  			str2 = "resp body"
   359  		)
   360  		c := g.Client().SetPrefix(fmt.Sprintf("http://127.0.0.1:%d", p))
   361  		c.Use(func(c *ghttp.Client, r *http.Request) (resp *ghttp.ClientResponse, err error) {
   362  			str1 += "a"
   363  			resp, err = c.Next(r)
   364  			if err != nil {
   365  				return nil, err
   366  			}
   367  			str1 += "b"
   368  			return
   369  		})
   370  		c.Use(func(c *ghttp.Client, r *http.Request) (resp *ghttp.ClientResponse, err error) {
   371  			str1 += "c"
   372  			resp, err = c.Next(r)
   373  			if err != nil {
   374  				return nil, err
   375  			}
   376  			str1 += "d"
   377  			return
   378  		})
   379  		c.Use(func(c *ghttp.Client, r *http.Request) (resp *ghttp.ClientResponse, err error) {
   380  			str1 += "e"
   381  			resp, err = c.Next(r)
   382  			if err != nil {
   383  				return nil, err
   384  			}
   385  			resp.Response.Body = ioutil.NopCloser(bytes.NewBufferString(str2))
   386  			str1 += "f"
   387  			return
   388  		})
   389  		resp, err := c.Get("/")
   390  		t.Assert(str1, "acefdb")
   391  		t.Assert(err, nil)
   392  		t.Assert(resp.ReadAllString(), str2)
   393  		t.Assert(isServerHandler, true)
   394  
   395  		// test abort, abort will not send
   396  		var (
   397  			str3     = ""
   398  			abortStr = "abort request"
   399  		)
   400  
   401  		c = g.Client().SetPrefix(fmt.Sprintf("http://127.0.0.1:%d", p))
   402  		c.Use(func(c *ghttp.Client, r *http.Request) (resp *ghttp.ClientResponse, err error) {
   403  			str3 += "a"
   404  			resp, err = c.Next(r)
   405  			str3 += "b"
   406  			return
   407  		})
   408  		c.Use(func(c *ghttp.Client, r *http.Request) (*ghttp.ClientResponse, error) {
   409  			str3 += "c"
   410  			return nil, gerror.New(abortStr)
   411  		})
   412  		c.Use(func(c *ghttp.Client, r *http.Request) (resp *ghttp.ClientResponse, err error) {
   413  			str3 += "f"
   414  			resp, err = c.Next(r)
   415  			str3 += "g"
   416  			return
   417  		})
   418  		resp, err = c.Get("/")
   419  		t.Assert(err, abortStr)
   420  		t.Assert(str3, "acb")
   421  		t.Assert(resp, nil)
   422  	})
   423  }
   424  
   425  func Test_Client_Agent(t *testing.T) {
   426  	p, _ := ports.PopRand()
   427  	s := g.Server(p)
   428  	s.BindHandler("/", func(r *ghttp.Request) {
   429  		r.Response.Write(r.UserAgent())
   430  	})
   431  	s.SetPort(p)
   432  	s.SetDumpRouterMap(false)
   433  	s.Start()
   434  	defer s.Shutdown()
   435  
   436  	time.Sleep(100 * time.Millisecond)
   437  
   438  	gtest.C(t, func(t *gtest.T) {
   439  		c := g.Client().SetPrefix(fmt.Sprintf("http://127.0.0.1:%d", p))
   440  		c.SetAgent("test")
   441  		t.Assert(c.GetContent("/"), "test")
   442  	})
   443  }