Best Go-testdeep code snippet using tdhttp.With
api_create_test.go
Source:api_create_test.go
...16}17func (suite *createSuite) BeforeTest(suiteName, testName string) {18 TestContext.BeforeTest()19}20func (suite *createSuite) TestCreateWithNewShortUrlReturns201() {21 t := suite.T()22 testServer := TestContext.server23 testAPI := tdhttp.NewTestAPI(t, testServer)24 testAPI.PostJSON("/api/v1/shorturls", gin.H{"long_url": "https://www.cloudflare.com"}).25 CmpStatus(http.StatusCreated).26 CmpJSONBody(27 td.JSON(28 `{29 "short_url": "$shortUrl",30 "slug": "$slug",31 "long_url": "$longUrl",32 "expires_on": "$expiresOn",33 "created_at": "$createdAt"34 }`,35 td.Tag("shortUrl", td.Re("http:\\/\\/example\\.com\\/([A-Za-z0-9]{8})")),36 td.Tag("slug", td.Re("[A-Za-z0-9]{8}")),37 td.Tag("longUrl", "https://www.cloudflare.com"),38 td.Tag("expiresOn", td.Nil()),39 td.Tag("createdAt", td.Smuggle(parseDateTime, td.Between(testAPI.SentAt(), time.Now()))),40 ),41 )42}43func (suite *createSuite) TestCreateWithInvalidLongUrlReturns400() {44 t := suite.T()45 testServer := TestContext.server46 testAPI := tdhttp.NewTestAPI(t, testServer)47 testAPI.PostJSON("/api/v1/shorturls", gin.H{"long_url": "invalid"}).48 CmpStatus(http.StatusBadRequest).49 CmpJSONBody(50 td.JSON(51 `{52 "errors": [53 {54 "field": "LongUrl",55 "reason": "url"56 }57 ],58 }`,59 ),60 )61}62func (suite *createSuite) TestCreateWithInvalidSchemeReturns400() {63 t := suite.T()64 testServer := TestContext.server65 testAPI := tdhttp.NewTestAPI(t, testServer)66 testAPI.PostJSON("/api/v1/shorturls", gin.H{"long_url": "javascript:alert('hi')"}).67 CmpStatus(http.StatusBadRequest).68 CmpJSONBody(69 td.JSON(70 `{71 "errors": [72 {73 "field": "LongUrl",74 "reason": "only http and https are supported"75 }76 ],77 }`,78 ),79 )80}81func (suite *createSuite) TestCreateWithExpirationDateReturns201() {82 t := suite.T()83 testServer := TestContext.server84 testAPI := tdhttp.NewTestAPI(t, testServer)85 expirationDateTime := time.Date(2023, 1, 1, 0, 0, 0, 0, time.UTC)86 testAPI.PostJSON(87 "/api/v1/shorturls",88 gin.H{89 "long_url": "https://www.cloudflare.com",90 "expires_on": expirationDateTime.Format(time.RFC3339),91 },92 ).93 CmpStatus(http.StatusCreated).94 CmpJSONBody(95 td.JSON(96 `{97 "short_url": "$shortUrl",98 "slug": "$slug",99 "long_url": "$longUrl",100 "expires_on": "$expiresOn",101 "created_at": "$createdAt"102 }`,103 td.Tag("shortUrl", td.Re("http:\\/\\/example\\.com\\/([A-Za-z0-9]{8})")),104 td.Tag("slug", td.Re("[A-Za-z0-9]{8}")),105 td.Tag("longUrl", "https://www.cloudflare.com"),106 td.Tag("expiresOn", td.Smuggle(parseDateTime, expirationDateTime)),107 td.Tag("createdAt", td.Smuggle(parseDateTime, td.Between(testAPI.SentAt(), time.Now()))),108 ),109 )110}111func (suite *createSuite) TestCreateWithExistingLongUrlReturns200() {112 t := suite.T()113 testServer := TestContext.server114 testAPI := tdhttp.NewTestAPI(t, testServer)115 var slug string116 var shortUrl string117 var longUrl string118 var createdAt time.Time119 // Initial POST should return a 201 CREATED120 testAPI.PostJSON("/api/v1/shorturls", gin.H{"long_url": "https://www.cloudflare.com"}).121 CmpStatus(http.StatusCreated).122 CmpJSONBody(123 td.JSON(124 `{125 "short_url": "$shortUrl",126 "slug": "$slug",127 "long_url": "$longUrl",128 "expires_on": "$expiresOn",129 "created_at": "$createdAt"130 }`,131 td.Tag("slug", td.Catch(&slug, td.Re("[A-Za-z0-9]{8}"))),132 td.Tag("shortUrl", td.Catch(&shortUrl, td.Ignore())),133 td.Tag("longUrl", td.Catch(&longUrl, "https://www.cloudflare.com")),134 td.Tag("expiresOn", td.Nil()),135 td.Tag("createdAt", td.Smuggle(parseDateTime, td.Catch(&createdAt, td.Ignore()))),136 ),137 )138 // Second POST should return a 200 OK with information about existing long URL139 testAPI.PostJSON("/api/v1/shorturls", gin.H{"long_url": "https://www.cloudflare.com"}).140 CmpStatus(http.StatusOK).141 CmpJSONBody(142 td.JSON(143 `{144 "short_url": "$shortUrl",145 "slug": "$slug",146 "long_url": "$longUrl",147 "expires_on": "$expiresOn",148 "created_at": "$createdAt"149 }`,150 td.Tag("shortUrl", shortUrl),151 td.Tag("slug", slug),152 td.Tag("longUrl", longUrl),153 td.Tag("expiresOn", td.Nil()),154 td.Tag("createdAt", td.Smuggle(parseDateTime, createdAt)),155 ),156 )157}158func (suite *createSuite) TestCreateWithExistingSlugReturns409() {159 t := suite.T()160 testServer := TestContext.server161 testAPI := tdhttp.NewTestAPI(t, testServer)162 slug := "cf"163 testAPI.PostJSON(164 "/api/v1/shorturls",165 gin.H{166 "slug": slug,167 "long_url": "https://www.cloudflare.com",168 },169 ).170 CmpStatus(http.StatusCreated).171 CmpJSONBody(172 td.SuperJSONOf(`{"slug": "$slug"}`, td.Tag("slug", slug)),173 )174 testAPI.PostJSON(175 "/api/v1/shorturls",176 gin.H{177 "long_url": "https://www.stackoverflow.com",178 "slug": slug,179 },180 ).181 CmpStatus(http.StatusConflict).182 CmpJSONBody(183 td.JSON(184 `{185 "errors": [186 {187 "field": "Slug",188 "reason": "must be unique"189 }190 ],191 }`,192 ),193 )194}195func (suite *createSuite) TestCreateWithInvalidJSONReturns400() {196 t := suite.T()197 testServer := TestContext.server198 testAPI := tdhttp.NewTestAPI(t, testServer)199 testAPI.PostJSON("/api/v1/shorturls", gin.H{"foo": "bar"}).200 CmpStatus(http.StatusBadRequest).201 CmpJSONBody(202 td.JSON(203 `{204 "errors": [205 {206 "field": "LongUrl",207 "reason": "required",208 }209 ]...
fizzbuzz_test.go
Source:fizzbuzz_test.go
1package handlers_test2import (3 "fmt"4 "math"5 "net/http"6 "net/url"7 "testing"8 "github.com/c-roussel/fizzbuzz-api/internal/handlers"9 "github.com/c-roussel/fizzbuzz-api/internal/server"10 "github.com/maxatome/go-testdeep/helpers/tdhttp"11 "github.com/maxatome/go-testdeep/td"12)13func TestFizzBuzz(t *testing.T) {14 testAPI := tdhttp.NewTestAPI(t, server.New())15 testCases := []struct {16 name string17 url string18 expectedStatus int19 expectedJSON string20 }{21 {22 name: "valid call with parameters",23 url: "/fizzbuzz?str1=le&str2=boncoin&limit=10&int1=2&int2=3",24 expectedStatus: http.StatusOK,25 expectedJSON: `{"result": ["1", "le", "boncoin", "le", "5", "leboncoin", "7", "le", "boncoin", "le"]}`,26 }, {27 name: "valid call without parameters",28 url: "/fizzbuzz",29 expectedStatus: http.StatusOK,30 expectedJSON: `{"result": [31 "1","2","fizz","4","buzz","fizz","7","8","fizz","buzz","11","fizz","13","14","fizzbuzz","16","17","fizz","19",32 "buzz","fizz","22","23","fizz","buzz","26","fizz","28","29","fizzbuzz","31","32","fizz","34","buzz","fizz","37",33 "38","fizz","buzz","41","fizz","43","44","fizzbuzz","46","47","fizz","49","buzz","fizz","52","53","fizz","buzz",34 "56","fizz","58","59","fizzbuzz","61","62","fizz","64","buzz","fizz","67","68","fizz","buzz","71","fizz","73",35 "74","fizzbuzz","76","77","fizz","79","buzz","fizz","82","83","fizz","buzz","86","fizz","88","89","fizzbuzz",36 "91","92","fizz","94","buzz","fizz","97","98","fizz","buzz"37 ]}`,38 },39 }40 for _, tc := range testCases {41 testAPI.Run(tc.name, func(ta *tdhttp.TestAPI) {42 ta.Get(tc.url).43 CmpStatus(tc.expectedStatus).44 CmpJSONBody(td.JSON(tc.expectedJSON))45 })46 }47}48func TestFizzBuzzInvalidQuery(t *testing.T) {49 testAPI := tdhttp.NewTestAPI(t, server.New())50 testCases := []struct {51 name string52 url string53 expectedStatus int54 expectedJSON string55 }{56 {57 name: "invalid int1 query param",58 url: "/fizzbuzz?str1=toto&str2=tata&limit=10&int1=-1&int2=3",59 expectedStatus: http.StatusBadRequest,60 expectedJSON: `{"message": "Key: 'FizzBuzzInput.Int1' Error:Field validation for 'Int1' failed on the 'min' tag"}`,61 },62 {63 name: "invalid int2 query param",64 url: "/fizzbuzz?str1=toto&str2=tata&limit=10&int1=1&int2=-3",65 expectedStatus: http.StatusBadRequest,66 expectedJSON: `{"message": "Key: 'FizzBuzzInput.Int2' Error:Field validation for 'Int2' failed on the 'min' tag"}`,67 },68 {69 name: "invalid limit query param",70 url: "/fizzbuzz?str1=toto&str2=tata&limit=-10&int1=1&int2=3",71 expectedStatus: http.StatusBadRequest,72 expectedJSON: `{"message": "Key: 'FizzBuzzInput.Limit' Error:Field validation for 'Limit' failed on the 'min' tag"}`,73 },74 {75 name: "invalid limit query param - should be integer",76 url: "/fizzbuzz?str1=toto&str2=tata&limit=string&int1=1&int2=3",77 expectedStatus: http.StatusBadRequest,78 expectedJSON: `{"message": "strconv.ParseInt: parsing \"string\": invalid syntax"}`,79 },80 {81 name: "invalid limit query param - should be lower than threshold",82 url: "/fizzbuzz?str1=toto&str2=tata&limit=100000000&int1=1&int2=3",83 expectedStatus: http.StatusBadRequest,84 expectedJSON: `{"message": "limit should be lower than 10000"}`,85 },86 }87 for _, tc := range testCases {88 testAPI.Run(tc.name, func(ta *tdhttp.TestAPI) {89 ta.Get(tc.url).90 CmpStatus(tc.expectedStatus).91 CmpJSONBody(td.JSON(tc.expectedJSON))92 })93 }94}95func BenchmarkFizzBuzz(b *testing.B) {96 defer func(old int) { handlers.FizzBuzzMaxLimit = old }(handlers.FizzBuzzMaxLimit)97 handlers.FizzBuzzMaxLimit = math.MaxInt98 testAPI := tdhttp.NewTestAPI(b, server.New())99 b.ResetTimer()100 testAPI.Name("benchmark", b.N).101 Get(fmt.Sprintf("/fizzbuzz?str1=le&str2=boncoin&limit=%d&int1=7&int2=31", b.N)).102 CmpStatus(http.StatusOK)103 b.StopTimer()104}105func FuzzFizzBuzz(f *testing.F) {106 f.Add(1, 2, 3, "str1", "str2")107 f.Fuzz(func(t *testing.T, int1, int2, limit int, str1, str2 string) {108 expectedStatus := http.StatusOK109 if int1 < 1 || int2 < 1 || limit < 0 {110 expectedStatus = http.StatusBadRequest111 }112 testAPI := tdhttp.NewTestAPI(t, server.New())113 testAPI.Get(114 "/fizzbuzz",115 tdhttp.Q{116 "str1": url.QueryEscape(str1),117 "str2": url.QueryEscape(str2),118 "int1": int1,119 "int2": int2,120 "limit": limit,121 }).122 CmpStatus(expectedStatus)123 })124}...
router_test.go
Source:router_test.go
1package mock_test2import (3 "io/fs"4 "net/http"5 "testing"6 "github.com/maxatome/go-testdeep/helpers/tdhttp"7 "github.com/maxatome/go-testdeep/td"8 "gitlab.com/inetmock/inetmock/pkg/logging"9 "gitlab.com/inetmock/inetmock/protocols/http/mock"10)11func TestRouter_ServeHTTP(t *testing.T) {12 t.Parallel()13 type fields struct {14 rules []string15 fakeFileFS fs.FS16 }17 type args struct {18 req *http.Request19 }20 tests := []struct {21 name string22 fields fields23 args args24 wantErr bool25 wantStatus interface{}26 want string27 }{28 {29 name: "GET /index.html",30 fields: fields{31 rules: []string{32 `PathPattern("\\.(?i)(htm|html)$") => File("default.html")`,33 },34 fakeFileFS: defaultFakeFileFS,35 },36 args: args{37 req: tdhttp.NewRequest(http.MethodGet, "https://google.com/index.html", nil),38 },39 want: defaultHTMLContent,40 wantStatus: td.Between(200, 299),41 },42 {43 name: "GET /profile.htm",44 fields: fields{45 rules: []string{46 `PathPattern("\\.(?i)(htm|html)$") => File("default.html")`,47 },48 fakeFileFS: defaultFakeFileFS,49 },50 args: args{51 req: tdhttp.NewRequest(http.MethodGet, "https://gitlab.com/profile.htm", nil),52 },53 want: defaultHTMLContent,54 wantStatus: td.Between(200, 299),55 },56 {57 name: "GET with Accept: text/html",58 fields: fields{59 rules: []string{60 `PathPattern("\\.(?i)(htm|html)$") => File("default.html")`,61 `Header("Accept", "text/html") => File("default.html")`,62 },63 fakeFileFS: defaultFakeFileFS,64 },65 args: args{66 req: tdhttp.NewRequest(67 http.MethodGet,68 "https://gitlab.com/profile",69 nil,70 http.Header{71 "Accept": []string{"text/html"},72 },73 ),74 },75 want: defaultHTMLContent,76 wantStatus: td.Between(200, 299),77 },78 {79 name: "POST",80 fields: fields{81 rules: []string{82 `METHOD("POST") => Status(204)`,83 },84 },85 args: args{86 req: tdhttp.NewRequest(87 http.MethodPost,88 "https://gitlab.com/profile",89 nil,90 http.Header{91 "Accept": []string{"text/html"},92 },93 ),94 },95 want: "",96 wantStatus: 204,97 },98 }99 for _, tc := range tests {100 tt := tc101 t.Run(tt.name, func(t *testing.T) {102 t.Parallel()103 logger := logging.CreateTestLogger(t)104 router := &mock.Router{105 HandlerName: t.Name(),106 Logger: logger,107 FakeFileFS: tt.fields.fakeFileFS,108 }109 for _, rule := range tt.fields.rules {110 if err := router.RegisterRule(rule); !td.CmpNoError(t, err) {111 return112 }113 }114 tdhttp.NewTestAPI(t, router).115 Request(tt.args.req).116 CmpStatus(tt.wantStatus).117 CmpBody(tt.want)118 })119 }120}...
With
Using AI Code Generation
1import (2func main() {3 m := minify.New()4 m.AddFunc("text/css", css.Minify)5 m.AddFunc("text/html", html.Minify)6 m.AddFunc("text/javascript", js.Minify)7 m.AddFunc("image/svg+xml", svg.Minify)8 m.AddFuncRegexp(regexp.MustCompile("[/+]json$"), json.Minify)9 m.AddFuncRegexp(regexp.MustCompile("[/+]xml$"), xml.Minify)10 h := tdhttp.New()11 h.With(m.Minify).ServeFiles("static", http.Dir("static"))12 h.With(m.Minify).ServeString("text/html", "<html> <head> <title>Test</title> </head> <body> <h1>Test</h1> </body> </html>")13 h.With(m.Minify).ServeBytes("text/html", []byte("<html> <head> <title>Test</title> </head> <body> <h1>Test</h1> </body> </html>"))14 h.With(m.Minify).ServeReader("text/html", strings.NewReader("<html> <head> <title>Test</title> </head> <body> <h1>Test</h1> </body> </html>"))15 h.With(m.Minify).ServeWriter("text/html", os.Stdout)16 h.With(m.Minify).ServeHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {17 fmt.Fprintf(w, "<html> <head> <
With
Using AI Code Generation
1import (2func main() {3 m := minify.New()4 m.AddFunc("text/css", css.Minify)5 m.AddFunc("text/html", html.Minify)6 m.AddFunc("text/javascript", js.Minify)7 m.AddFunc("application/json", json.Minify)8 m.AddFunc("image/svg+xml", svg.Minify)9 m.AddFuncRegexp(regexp.MustCompile("[/+]xml$
With
Using AI Code Generation
1import (2func main() {3 m := minify.New()4 m.AddFunc("text/css", css.Minify)5 m.AddFunc("text/javascript", js.Minify)6 m.AddFunc("application/json", json.Minify)7 m.AddFuncRegexp(regexp.MustCompile("[/+]html$"), html.Minify)8 m.AddFunc("image/svg+xml", svg.Minify)9 m.AddFuncRegexp(regexp.MustCompile("[/+]xml$"), xml.Minify)10 minified, err := m.String("text/css", "body { color: red; }")11 if err != nil {12 panic(err)13 }14 fmt.Println(minified)15}16import (
With
Using AI Code Generation
1import (2func main() {3 m := minify.New()4 m.AddFunc("text/css", css.Minify)5 m.AddFunc("text/html", html.Minify)6 m.AddFunc("text/javascript", js.Minify)7 m.AddFunc("application/json", json.Minify)8 m.AddFunc("image/svg+xml", svg.Minify)9 m.AddFuncRegexp(regexp.MustCompile("[/+]xml$"), xml.Minify)10 m.Add("text/css", &css.Minifier{11 })12 m.Add("text/html", &html.Minifier{13 })14 m.Add("text/javascript", &js.Minifier{15 })16 m.Add("application/json", &json.Minifier{17 })18 m.Add("image/svg+xml", &svg.Minifier{19 })20 m.AddRegexp(regexp.MustCompile("[/+]xml$"), &xml.Minifier{21 })22 m.Add("text/css", &css.Minifier{23 })24 m.Add("text/html", &html.Minifier{25 })26 m.Add("text/javascript", &js.Minifier{27 })28 m.Add("application/json", &json.Minifier{29 })30 m.Add("image/svg+xml", &svg.Minifier{31 })32 m.AddRegexp(regexp.MustCompile("[/+]xml$"), &xml.Minifier{33 })34 m.Add("text/css", &css.Minifier{35 })36 m.Add("text/html", &html.Minifier{
With
Using AI Code Generation
1import (2type tdhttp struct {3}4func main() {5 t := new(tdhttp)6 t.With("User-Agent", "tdhttp/1.0")7}8func (t *tdhttp) With(name, value string) *tdhttp {9 http.Header.Add(&http.Request.Header, name, value)10}11import (12type tdhttp struct {13}14func main() {15 t := new(tdhttp)16 t.With("User-Agent", "tdhttp/1.0")17}18func (t *tdhttp) With(name, value string) *tdhttp {19 http.Header.Add(&http.Request.Header, name, value)20}21import (22type tdhttp struct {23}24func main() {25 t := new(tdhttp)26 t.With("User-Agent", "tdhttp/1.0")27}28func (t *tdhttp) With(name, value string) *tdhttp {29 http.Header.Add(&http.Request.Header, name, value)30}31import (
With
Using AI Code Generation
1import (2func main() {3 response, err := client.Get("/")4 if err != nil {5 }6 defer response.Body.Close()7 fmt.Println(response.StatusCode)8 })9}10import (11func main() {12 response, err := client.Get("/")13 if err != nil {14 }15 defer response.Body.Close()16 fmt.Println(response.StatusCode)17 })18}19import (20func main() {21 response, err := client.Get("/")22 if err != nil {23 }24 defer response.Body.Close()25 fmt.Println(response.StatusCode)26 })27}28import (29func main() {30 response, err := client.Get("/")31 if err != nil {32 }33 defer response.Body.Close()34 fmt.Println(response.StatusCode)35 })36}37import (38func main() {39 response, err := client.Get("/")40 if err != nil {41 }42 defer response.Body.Close()43 fmt.Println(response.StatusCode)44 })45}
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!