Best Go-testdeep code snippet using td.newContext
product_test.go
Source:product_test.go
1package controller2import (3 "fmt"4 "github.com/golang/mock/gomock"5 "github.com/labstack/echo/v4"6 "github.com/labstack/gommon/random"7 "github.com/stretchr/testify/assert"8 "github.com/stretchr/testify/require"9 "math/rand"10 "net/http"11 "net/http/httptest"12 "product-api/mocks"13 "product-api/model"14 "testing"15 "time"16)17var productCont *productController18var mockProductRepo *mocks.MockProductRepo19func setup(t *testing.T) func() {20 ctrl := gomock.NewController(t)21 defer ctrl.Finish()22 mockProductRepo = mocks.NewMockProductRepo(ctrl)23 productCont = NewProductController(mockProductRepo)24 return func() {25 productCont = nil26 defer ctrl.Finish()27 }28}29func TestGetProducts_Success(t *testing.T) {30 td := setup(t)31 defer td()32 e := echo.New()33 e.GET("/products", productCont.GetProducts)34 var FakeDataForTest = []model.Product{35 {123, "007", "123", "123", 123, "123", 123, time.Now(), time.Now()},36 {321, "001", "123", "123", 123, "123", 123, time.Now(), time.Now()},37 {4213, "790", "123", "123", 123, "123", 123, time.Now(), time.Now()},38 }39 mockProductRepo.EXPECT().GetRepoProducts().Return(FakeDataForTest, nil)40 request := httptest.NewRequest("GET", "/products", nil)41 rec := httptest.NewRecorder()42 c := e.NewContext(request, rec)43 // Assertions44 if assert.NoError(t, productCont.GetProducts(c)) {45 assert.Equal(t, http.StatusOK, rec.Code)46 //assert.Equal(t, userJSON, rec.Body.String())47 }48}49func TestGetProducts_Unsuccessful(t *testing.T) {50 td := setup(t)51 defer td()52 e := echo.New()53 e.GET("/products", productCont.GetProducts)54 var FakeDataForTest = []model.Product{55 {123, "007", "123", "123", 123, "123", 123, time.Now(), time.Now()},56 {321, "001", "123", "123", 123, "123", 123, time.Now(), time.Now()},57 {4213, "790", "123", "123", 123, "123", 123, time.Now(), time.Now()},58 }59 err := error(fmt.Errorf("TestError"))60 mockProductRepo.EXPECT().GetRepoProducts().Return(FakeDataForTest, err)61 request := httptest.NewRequest("GET", "/products", nil)62 rec := httptest.NewRecorder()63 c := e.NewContext(request, rec)64 // Assertions65 if assert.Error(t, productCont.GetProducts(c)) {66 assert.Equal(t, http.StatusOK, rec.Code)67 //assert.Equal(t, userJSON, rec.Body.String())68 }69}70func TestGetProductByID_Success(t *testing.T) {71 td := setup(t)72 defer td()73 e := echo.New()74 e.GET("/products/:id", productCont.GetProductByID)75 FakeDataForTest := RandomProduct()76 mockProductRepo.EXPECT().GetRepoProductByID(gomock.Any()).Return(&FakeDataForTest, nil)77 req := httptest.NewRequest("GET", "/products/:id", nil)78 rec := httptest.NewRecorder()79 c := e.NewContext(req, rec)80 err := productCont.GetProductByID(c)81 require.NoError(t, err)82}83func TestGetProductByID_Unsuccessful(t *testing.T) {84 td := setup(t)85 defer td()86 e := echo.New()87 e.GET("/products/:id", productCont.GetProductByID)88 err := fmt.Errorf("TestError")89 FakeDataForTest := RandomProduct()90 mockProductRepo.EXPECT().GetRepoProductByID(gomock.Any()).Return(&FakeDataForTest, err)91 req := httptest.NewRequest("GET", "/products/:id", nil)92 rec := httptest.NewRecorder()93 c := e.NewContext(req, rec)94 err = productCont.GetProductByID(c)95 require.Error(t, err)96 require.Equal(t, http.StatusOK, rec.Code)97}98func TestFindProductQueryParams_Success(t *testing.T) {99 td := setup(t)100 defer td()101 var array []model.Product102 e := echo.New()103 e.GET("/find-products", productCont.FindProductQueryParams)104 mockProductRepo.EXPECT().FindRepoProductQueryParams(gomock.Any(), gomock.Any(), gomock.Any()).Return(array, nil)105 req := httptest.NewRequest("GET", "/find-products", nil)106 rec := httptest.NewRecorder()107 c := e.NewContext(req, rec)108 err := productCont.FindProductQueryParams(c)109 require.NoError(t, err)110}111func TestFindProductQueryParams_Unsuccessful(t *testing.T) {112 td := setup(t)113 defer td()114 //FakeDataForTest := RandomProduct()115 var array []model.Product116 err := fmt.Errorf("TestError")117 e := echo.New()118 e.GET("/find-products", productCont.FindProductQueryParams)119 mockProductRepo.EXPECT().FindRepoProductQueryParams(gomock.Any(), gomock.Any(), gomock.Any()).Return(array, err)120 req := httptest.NewRequest("GET", "/find-products", nil)121 res := httptest.NewRecorder()122 c := e.NewContext(req, res)123 err = productCont.FindProductQueryParams(c)124 require.Error(t, err)125 //require.NotNil(t, array)126 require.Equal(t, http.StatusOK, res.Code)127}128func TestAddNewProduct_Success(t *testing.T) {129 td := setup(t)130 defer td()131 e := echo.New()132 e.POST("/products", productCont.AddNewProduct)133 mockProductRepo.EXPECT().AddNewRepoProduct(gomock.Any()).Return(nil)134 req := httptest.NewRequest("POST", "/products", nil)135 res := httptest.NewRecorder()136 c := e.NewContext(req, res)137 err := productCont.AddNewProduct(c)138 require.NoError(t, err)139 require.Equal(t, http.StatusOK, res.Code)140}141func TestAddNewProduct_Unsuccessful(t *testing.T) {142 td := setup(t)143 defer td()144 err := fmt.Errorf("TestError")145 e := echo.New()146 mockProductRepo.EXPECT().AddNewRepoProduct(gomock.Any()).Return(err)147 req := httptest.NewRequest("POST", "/products", nil)148 res := httptest.NewRecorder()149 c := e.NewContext(req, res)150 err = productCont.AddNewProduct(c)151 require.Nil(t, err)152 require.Equal(t, http.StatusOK, res.Code)153}154func TestUpdateProductByID_Success(t *testing.T) {155 td := setup(t)156 defer td()157 FakeDataForTest := RandomProduct()158 e := echo.New()159 e.PUT("/update-product", productCont.UpdateProductByID)160 mockProductRepo.EXPECT().UpdateRepoProductByID(&FakeDataForTest).Return(RandomProduct().Code, nil)161 req := httptest.NewRequest("PUT", "/update-products", nil)162 res := httptest.NewRecorder()163 c := e.NewContext(req, res)164 err := productCont.UpdateProductByID(c)165 require.NoError(t, err)166}167func TestUpdateProductByID_Unsuccessful(t *testing.T) {168 td := setup(t)169 defer td()170 FakeDataForTest := RandomProduct()171 err1 := fmt.Errorf("TestError")172 e := echo.New()173 e.PUT("/update-product", productCont.UpdateProductByID)174 mockProductRepo.EXPECT().UpdateRepoProductByID(&FakeDataForTest).Return(RandomProduct().Code, err1)175 req := httptest.NewRequest("PUT", "/update-products", nil)176 res := httptest.NewRecorder()177 c := e.NewContext(req, res)178 require.Error(t, err1)179 err := productCont.UpdateProductByID(c)180 require.NoError(t, err)181}182func TestDeleteProductByID_Success(t *testing.T) {183 td := setup(t)184 defer td()185 e := echo.New()186 e.DELETE("/delete-product/:id", productCont.DeleteProductByID)187 mockProductRepo.EXPECT().DeleteRepoProductByID(gomock.Any()).Return(nil)188 req := httptest.NewRequest("DELETE", "/delete-product/:id", nil)189 res := httptest.NewRecorder()190 c := e.NewContext(req, res)191 err := productCont.DeleteProductByID(c)192 require.NoError(t, err)193}194func TestDeleteProductByID_Unsuccessful(t *testing.T) {195 td := setup(t)196 defer td()197 err := fmt.Errorf("TestError")198 e := echo.New()199 e.DELETE("/delete-product/:id", productCont.DeleteProductByID)200 mockProductRepo.EXPECT().DeleteRepoProductByID(gomock.Any()).Return(err)201 req := httptest.NewRequest("DELETE", "/delete-product/:id", nil)202 res := httptest.NewRecorder()203 c := e.NewContext(req, res)204 err2 := productCont.DeleteProductByID(c)205 require.Error(t, err)206 require.NoError(t, err2)207}208func RandomProduct() model.Product {209 return model.Product{210 Id: rand.Int(),211 Code: random.String(4),212 Name: random.String(4),213 Category: random.String(4),214 Price: rand.Int(),215 Color: random.String(4),216 Size: rand.Int(),217 UpdatedAt: time.Time{},218 CreatedAt: time.Time{},219 }220}...
dynamic_test.go
Source:dynamic_test.go
1package log2import (3 "testing"4 "time"5 "github.com/signalfx/golib/v3/timekeeper/timekeepertest"6 . "github.com/smartystreets/goconvey/convey"7)8func BenchmarkValueBindingTimestamp(b *testing.B) {9 benchmarkValueBindingTimestamp(b, Discard)10}11func BenchmarkValueBindingTimestampCount(b *testing.B) {12 benchmarkValueBindingTimestamp(b, &Counter{})13}14func benchmarkValueBindingTimestamp(b *testing.B, logger Logger) {15 b.Helper()16 lc := NewContext(logger).With("ts", DefaultTimestamp)17 b.ReportAllocs()18 b.ResetTimer()19 for i := 0; i < b.N; i++ {20 lc.Log("k", "v")21 }22}23func BenchmarkValueBindingCaller(b *testing.B) {24 benchmarkValueBindingCaller(b, Discard)25}26func BenchmarkValueBindingCallerCount(b *testing.B) {27 benchmarkValueBindingCaller(b, &Counter{})28}29func benchmarkValueBindingCaller(b *testing.B, logger Logger) {30 b.Helper()31 lc := NewContext(logger).With("caller", DefaultCaller)32 b.ReportAllocs()33 b.ResetTimer()34 for i := 0; i < b.N; i++ {35 lc.Log("k", "v")36 }37}38func between(start, mid, end time.Time) bool {39 return !mid.Before(start) && !end.Before(mid)40}41func TestTimeSince(t *testing.T) {42 Convey("Normal time since", t, func() {43 td := &TimeSince{}44 c := NewChannelLogger(1, nil)45 l := NewContext(c)46 Convey("Empty should work", func() {47 l.Log("td", td)48 msg := <-c.Out49 _, ok := msg[1].(time.Duration)50 So(ok, ShouldBeTrue)51 })52 Convey("Should allow overrides", func() {53 start := time.Now()54 tk := timekeepertest.NewStubClock(start)55 td.TimeKeeper = tk56 td.Start = start57 tk.Incr(time.Second)58 l.Log("td", td)59 msg := <-c.Out60 So(msg[1].(time.Duration), ShouldEqual, time.Second)61 })62 })63}64func TestTimeDynamic(t *testing.T) {65 Convey("Normal time dynamic", t, func() {66 td := &TimeDynamic{}67 c := NewChannelLogger(1, nil)68 l := NewContext(c)69 Convey("Empty should work", func() {70 start := time.Now()71 l.Log("ts", td)72 later := time.Now()73 msg := <-c.Out74 So(between(start, msg[1].(time.Time), later), ShouldBeTrue)75 })76 Convey("UTC should convert", func() {77 td.UTC = true78 l.Log("ts", td)79 msg := <-c.Out80 So(msg[1].(time.Time).Location(), ShouldEqual, time.UTC)81 })82 Convey("Layout should change", func() {83 td.AsString = true84 l.Log("ts", td)85 msg1 := <-c.Out86 td.Layout = time.RFC3339Nano87 l.Log("ts", td)88 msg2 := <-c.Out89 So(msg1[1].(string), ShouldNotResemble, msg2[1].(string))90 })91 })92}...
HtmlFormatter_integration_test.go
Source:HtmlFormatter_integration_test.go
...8 "goselect/parser/writer"9 "testing"10)11func TestHtmlFormatter(t *testing.T) {12 newContext := context.NewContext(context.NewFunctions(), context.NewAttributes())13 aParser, err := parser.NewParser("select lower(name), contains(lower(name), 'log') from ./resources/TestResultsWithProjections/multi order by 1", newContext)14 if err != nil {15 t.Fatalf("error is %v", err)16 }17 selectQuery, err := aParser.Parse()18 if err != nil {19 t.Fatalf("error is %v", err)20 }21 queryResults, _ := executor.NewSelectQueryExecutor(selectQuery, newContext, executor.NewDefaultOptions()).Execute()22 html := writer.NewHtmlFormatter().Format(selectQuery.Projections, queryResults)23 expected := "<html><body><table style=\"width:100%; border: 1px solid black\"><tr><th style=\"border: 1px solid black\">lower(name)</th><th style=\"border: 1px solid black\">contains(lower(name),log)</th></tr><tr><td style=\"border: 1px solid black\">testresultswithprojections_a.log</td><td style=\"border: 1px solid black\">Y</td></tr><tr><td style=\"border: 1px solid black\">testresultswithprojections_b.log</td><td style=\"border: 1px solid black\">Y</td></tr><tr><td style=\"border: 1px solid black\">testresultswithprojections_c.txt</td><td style=\"border: 1px solid black\">N</td></tr><tr><td style=\"border: 1px solid black\">testresultswithprojections_d.txt</td><td style=\"border: 1px solid black\">N</td></tr><tr><td colspan=\"2\" style=\"border: 1px solid black\">Rows: 4</td></tr></table></body></html>"24 if expected != html {25 t.Fatalf("Expected html formatter to format %v, received %v", expected, html)26 }27}...
newContext
Using AI Code Generation
1import (2func main() {3 ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)4 defer cancel()5 go func() {6 time.Sleep(10 * time.Second)7 cancel()8 }()9 doSomething(ctx)10}11func doSomething(ctx context.Context) {12 select {13 case <-ctx.Done():14 fmt.Println("Context is done")15 fmt.Println("Doing something")16 }17 time.Sleep(2 * time.Second)18 fmt.Println("Done")19}
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!!