How to use newRuntime method of http Package

Best K6 code snippet using http.newRuntime

service_test.go

Source:service_test.go Github

copy

Full Screen

...29 <-done30}31func TestNewRuntime(t *testing.T) {32 settings := DefaultSettings().WithEndpoint("test")33 rt := newRuntime(context.Background(), settings)34 defer rt.close()35 if rt.isStopping {36 t.Error("Stopping set")37 }38 // Validate rt vs settings39 if rt.ttl != settings.CacheTTL {40 t.Errorf("Mismatch ttl %d vs CacheTTL %d", rt.ttl, settings.CacheTTL)41 }42 if rt.requestTimeout != settings.RequestTimeout {43 t.Errorf("Mismatch requestTimeout %d vs RequestTimeout %d", rt.requestTimeout, settings.RequestTimeout)44 }45 if rt.endpoint != settings.Endpoint {46 t.Errorf("Mismatch endpoint %s vs Endpoint %s", rt.endpoint, settings.Endpoint)47 }48 if rt.houseKeeperPeriod != settings.CacheTTL {49 t.Errorf("Mismatch houseKeeperPeriod %d vs CacheTTL %d", rt.houseKeeperPeriod, settings.CacheTTL)50 }51}52func TestCriticalError(t *testing.T) {53 settings := DefaultSettings().WithEndpoint("test")54 rt := newRuntime(context.Background(), settings)55 defer rt.close()56 expected := errors.New("test")57 rt.criticalError(expected)58 <-rt.done()59 if rt.err != expected {60 t.Error("No critical error", rt.err)61 }62}63func TestLoggingInfo(t *testing.T) {64 called := false65 fn := func(isErr bool, fmt string, args ...interface{}) {66 if called {67 return /// stop additional logging68 }69 if isErr {70 t.Error("Not Info")71 }72 if fmt != "test" {73 t.Error("Fmt err", fmt)74 }75 called = true76 }77 settings := DefaultSettings().WithEndpoint("test").WithLogger(fn)78 rt := newRuntime(context.Background(), settings)79 defer rt.close()80 rt.logInfo("test")81 if !called {82 t.Error("Not called")83 }84}85func TestLoggingError(t *testing.T) {86 called := false87 fn := func(isErr bool, fmt string, args ...interface{}) {88 if called {89 return /// stop additional logging90 }91 if !isErr {92 t.Error("Not Error")93 }94 if fmt != "err" {95 t.Error("Fmt err", fmt)96 }97 called = true98 }99 settings := DefaultSettings().WithEndpoint("test").WithLogger(fn)100 rt := newRuntime(context.Background(), settings)101 defer rt.close()102 rt.logError("err")103 if !called {104 t.Error("Not called")105 }106}107func TestParseRequestNoMatch(t *testing.T) {108 settings := DefaultSettings().WithEndpoint("test")109 rt := newRuntime(context.Background(), settings)110 defer rt.close()111 reader := strings.NewReader("client_id=123&client_secret=456&grant_type=password&password=abc&username=def")112 req, _ := http.NewRequest("POST", "http:/something", reader)113 w := httptest.NewRecorder()114 tr, match := rt.parseRequest(w, req)115 if match {116 t.Error("Not meant to match")117 }118 if w.Code != http.StatusNotFound {119 t.Errorf("Expected code %d got %d", http.StatusNotFound, w.Code)120 }121 if tr != (tokenRequest{path: "/something"}) {122 t.Error("Unexpected token returned", tr)123 }124}125func TestParseRequestMatchBadRequestFail(t *testing.T) {126 settings := DefaultSettings().WithEndpoint("test")127 rt := newRuntime(context.Background(), settings)128 defer rt.close()129 reader := strings.NewReader("client_id=123&client_secret=456&grant_type=password&password=p1&scope=alpha+bravo&username=u1")130 req, _ := http.NewRequest("POST", "http:/something/token", reader)131 // no header coontent type132 w := httptest.NewRecorder()133 _, match := rt.parseRequest(w, req)134 if match {135 t.Error("Unexpected a match")136 }137 if w.Code != http.StatusBadRequest {138 t.Error("Status not bad", w.Code)139 }140}141func TestParseRequestMatchBody(t *testing.T) {142 settings := DefaultSettings().WithEndpoint("test")143 rt := newRuntime(context.Background(), settings)144 defer rt.close()145 reader := strings.NewReader("client_id=123&client_secret=456&grant_type=password&password=p1&scope=alpha+bravo&username=u1")146 req, _ := http.NewRequest("POST", "http:/something/token", reader)147 req.Header.Set("Content-Type", "application/x-www-form-urlencoded")148 w := httptest.NewRecorder()149 tr, match := rt.parseRequest(w, req)150 if !match {151 t.Error("Expected a match")152 }153 if w.Code != http.StatusOK {154 t.Error("Status set", w.Code)155 }156 expected := tokenRequest{157 path: "/something/token",158 clientID: "123",159 clientSecret: "456",160 username: "u1",161 password: "p1",162 scopes: "alpha bravo",163 authMode: authInBody,164 }165 if tr != expected {166 t.Error("Unexpected token returned", tr)167 }168}169func TestParseRequestMatchHeader(t *testing.T) {170 settings := DefaultSettings().WithEndpoint("test")171 rt := newRuntime(context.Background(), settings)172 defer rt.close()173 reader := strings.NewReader("grant_type=password&password=p1&scope=alpha+bravo&username=u1")174 req, _ := http.NewRequest("POST", "http:/something/token", reader)175 req.Header.Set("Content-Type", "application/x-www-form-urlencoded")176 req.SetBasicAuth("123", "456")177 w := httptest.NewRecorder()178 tr, match := rt.parseRequest(w, req)179 if !match {180 t.Error("Expected a match")181 }182 if w.Code != http.StatusOK {183 t.Error("Status set", w.Code)184 }185 expected := tokenRequest{186 path: "/something/token",187 clientID: "123",188 clientSecret: "456",189 username: "u1",190 password: "p1",191 scopes: "alpha bravo",192 authMode: authInHeader,193 }194 if tr != expected {195 t.Error("Unexpected token returned", tr)196 }197}198func TestCacheClean(t *testing.T) {199 settings := DefaultSettings().WithEndpoint("test")200 rt := newRuntime(context.Background(), settings)201 defer rt.close()202 key := tokenRequest{203 path: "/something/token",204 clientID: "123",205 clientSecret: "456",206 username: "u1",207 password: "p1",208 scopes: "alpha bravo",209 authMode: authInHeader,210 }211 now := time.Date(2020, 0o1, 0o1, 0o1, 0o0, 0o0, 0o0, time.UTC)212 expired := now.Add(-time.Hour * 24)213 rt.cache[key] = entry{214 token: []byte("test"),215 statusCode: http.StatusOK,216 expiry: expired,217 }218 key2 := key219 key2.clientID = "888"220 rt.cache[key2] = entry{221 token: []byte("keep"),222 statusCode: http.StatusOK,223 expiry: now,224 }225 rt.clean(now)226 if len(rt.cache) != 1 {227 t.Error("cache not cleared correctly")228 }229 if _, ok := rt.cache[key2]; !ok {230 t.Error("key2 missing")231 }232}233func TestLookup(t *testing.T) {234 settings := DefaultSettings().WithEndpoint("test")235 rt := newRuntime(context.Background(), settings)236 defer rt.close()237 key := tokenRequest{238 path: "/something/token",239 clientID: "123",240 clientSecret: "456",241 username: "u1",242 password: "p1",243 scopes: "alpha bravo",244 authMode: authInHeader,245 }246 now := time.Date(2020, 0o1, 0o1, 0o1, 0o0, 0o0, 0o0, time.UTC)247 expired := now.Add(-time.Hour * 24)248 rt.cache[key] = entry{249 token: []byte("test"),250 statusCode: http.StatusOK,251 expiry: expired,252 }253 entry := rt.lookup(key)254 if string(entry.token) != "test" {255 t.Error("Invalid token", entry)256 }257 key.authMode = authInBody258 entry = rt.lookup(key)259 if string(entry.token) != "" {260 t.Error("Invalid token found", entry)261 }262}263func TestHandlerFuncForCached(t *testing.T) {264 settings := DefaultSettings().WithEndpoint("test")265 rt := newRuntime(context.Background(), settings)266 defer rt.close()267 key := tokenRequest{268 path: "/something/token",269 clientID: "123",270 clientSecret: "456",271 username: "u1",272 password: "p1",273 scopes: "alpha bravo",274 authMode: authInBody,275 }276 expiry := time.Now().UTC().Add(time.Hour)277 rt.cache[key] = entry{278 token: []byte("test"),279 statusCode: http.StatusOK,280 expiry: expiry,281 }282 reader := strings.NewReader("client_id=123&client_secret=456&grant_type=password&password=p1&scope=alpha+bravo&username=u1")283 req, _ := http.NewRequest("POST", "http:/something/token", reader)284 req.Header.Set("Content-Type", "application/x-www-form-urlencoded")285 w := httptest.NewRecorder()286 rt.handleRequest(w, req)287 if w.Code != http.StatusOK {288 t.Error("Invalid status", w.Code)289 }290 body := w.Body.String()291 if body != "test" {292 t.Error("body:", body)293 }294}295func TestHandlerFuncForExpiredBadUrlFails(t *testing.T) {296 settings := DefaultSettings().WithEndpoint("test")297 rt := newRuntime(context.Background(), settings)298 defer rt.close()299 key := tokenRequest{300 path: "/something/token",301 clientID: "123",302 clientSecret: "456",303 username: "u1",304 password: "p1",305 scopes: "alpha bravo",306 authMode: authInBody,307 }308 expiry := time.Now().UTC().Add(-time.Hour)309 rt.cache[key] = entry{310 token: []byte("test"),311 statusCode: http.StatusOK,312 expiry: expiry,313 }314 reader := strings.NewReader("client_id=123&client_secret=456&grant_type=password&password=p1&scope=alpha+bravo&username=u1")315 req, _ := http.NewRequest("POST", "http:/something/token", reader)316 req.Header.Set("Content-Type", "application/x-www-form-urlencoded")317 w := httptest.NewRecorder()318 rt.handleRequest(w, req)319 if w.Code != http.StatusBadRequest {320 t.Error("Invalid status", w.Code)321 }322 expected := "{\"error\":\"bad request\",\"error_code\":400,\"error_description\":\"bad request\"}"323 body := w.Body.String()324 if !strings.HasPrefix(body, expected) {325 t.Error("body:", body)326 }327}328func TestHandlerFuncForExpiredGetsNewToken(t *testing.T) {329 settings := DefaultSettings().WithEndpoint("test")330 rt := newRuntime(context.Background(), settings)331 defer rt.close()332 expiry := time.Now().UTC().Add(3 * time.Minute)333 rt.requester = func(ctx context.Context, req *http.Request) (*http.Response, error) {334 w := httptest.NewRecorder()335 w.WriteHeader(http.StatusOK)336 t := &oauth2.Token{337 AccessToken: "test",338 Expiry: expiry,339 }340 err := json.NewEncoder(w).Encode(t)341 return w.Result(), err342 }343 reader := strings.NewReader("client_id=123&client_secret=456&grant_type=password&password=p1&scope=alpha+bravo&username=u1")344 req, _ := http.NewRequest("POST", "http:/something/token", reader)345 req.Header.Set("Content-Type", "application/x-www-form-urlencoded")346 w := httptest.NewRecorder()347 rt.handleRequest(w, req)348 if w.Code != http.StatusOK {349 t.Error("Non success status", w.Code)350 }351 body := w.Body.String()352 if !strings.HasPrefix(body, "{\"access_token\":\"test\",\"expiry\":\"") {353 t.Error("body:", body)354 }355}356func TestHandlerFuncUpdate(t *testing.T) {357 settings := DefaultSettings().WithEndpoint("test")358 rt := newRuntime(context.Background(), settings)359 defer rt.close()360 key := tokenRequest{361 path: "/something/token",362 clientID: "123",363 clientSecret: "456",364 username: "u1",365 password: "p1",366 scopes: "alpha bravo",367 authMode: authInBody,368 }369 rt.update(key, http.Header{}, []byte("test"), http.StatusOK)370 found, ok := rt.cache[key]371 if !ok {372 t.Error("Not found key")...

Full Screen

Full Screen

runtime_test.go

Source:runtime_test.go Github

copy

Full Screen

...38 }39 return otto.Value.ToInteger(value)40}41func TestRuntimeInit(t *testing.T) {42 rt, err := newRuntime()43 assert.NotNil(t, rt, "runtime should not be nil")44 assert.Nil(t, err, "err should be nil")45}46func TestRuntimeIsPlainHostName(t *testing.T) {47 rt, _ := newRuntime()48 www, err := callBooleanFunction(rt, "isPlainHostName", "www")49 assert.Nil(t, err, "should not error")50 assert.True(t, www, "'www' should be a valid plain host")51 netscape, err := callBooleanFunction(rt, "isPlainHostName", "www.netscape.com")52 assert.Nil(t, err, "should not error")53 assert.False(t, netscape, "'www.netscape.com' should not be a valid plain host")54}55func TestRuntimeDnsDomainIs(t *testing.T) {56 rt, _ := newRuntime()57 netscape, err := callBooleanFunction(rt, "dnsDomainIs", "www.netscape.com", ".netscape.com")58 assert.Nil(t, err, "should not error")59 assert.True(t, netscape, "'www.netscape.com' should be a valid host for domain '.netscape.com'")60 www, err := callBooleanFunction(rt, "dnsDomainIs", "www", ".netscape.com")61 assert.Nil(t, err, "should not error")62 assert.False(t, www, "'www' should not be a valid host for domain '.netscape.com'")63 mcom, err := callBooleanFunction(rt, "dnsDomainIs", "w.mcom.com", ".netscape.com")64 assert.Nil(t, err, "should not error")65 assert.False(t, mcom, "'www.mcom.com' should not be a valid host for domain '.netscape.com'")66}67func TestRuntimeLocalHostOrDomainIs(t *testing.T) {68 rt, _ := newRuntime()69 netscape, err := callBooleanFunction(rt, "localHostOrDomainIs", "www.netscape.com", "www.netscape.com")70 assert.Nil(t, err, "should not error")71 assert.True(t, netscape, "'www.netscape.com' should be valid as it equals the domain 'www.netscape.com'")72 www, err := callBooleanFunction(rt, "localHostOrDomainIs", "www", "www.netscape.com")73 assert.Nil(t, err, "should not error")74 assert.True(t, www, "'www' should be valid as it contains no domain part")75 mcom, err := callBooleanFunction(rt, "localHostOrDomainIs", "www.mcom.com", "wwww.netscape.com")76 assert.Nil(t, err, "should not error")77 assert.False(t, mcom, "'www.mcom.com' should not be as it contains a domain part")78 home, err := callBooleanFunction(rt, "localHostOrDomainIs", "home.netscape.com", "wwww.netscape.com")79 assert.Nil(t, err, "should not error")80 assert.False(t, home, "'home.netscape.com' should not be as it contains a domain part")81}82func TestRuntimeIsResolvable(t *testing.T) {83 rt, _ := newRuntime()84 localhost1, err := callBooleanFunction(rt, "isInNet", "localhost", "127.0.0.1", "255.255.255.255")85 assert.Nil(t, err, "should not error")86 assert.True(t, localhost1, "'localhost' should equal 127.0.0.1 with the mask 255.255.255.255")87 localhost2, err := callBooleanFunction(rt, "isInNet", "localhost", "127.0.0.0", "255.0.0.0")88 assert.Nil(t, err, "should not error")89 assert.True(t, localhost2, "'localhost' should equal 127.0.0.1 with the mask 255.0.0.0")90 localhost3, err := callBooleanFunction(rt, "isInNet", "localhost", "127.0.0.0", "255.0.0.255")91 assert.Nil(t, err, "should not error")92 assert.False(t, localhost3, "'localhost' should not equal 127.0.0.1 with the mask 255.0.0.255")93}94func TestRuntimeDnsResolve(t *testing.T) {95 rt, _ := newRuntime()96 localhost, err := callStringFunction(rt, "dnsResolve", "localhost")97 assert.Nil(t, err, "should not error")98 assert.Equal(t, localhost, "127.0.0.1", "'localhost' should equal 127.0.0.1")99}100func TestRuntimeDnsDomainLevels(t *testing.T) {101 rt, _ := newRuntime()102 www, err := callNumberFunction(rt, "dnsDomainLevels", "www")103 assert.Nil(t, err, "should not error")104 assert.Equal(t, www, int64(0), "'www' should contain 0 domain levels")105 netscape, err := callNumberFunction(rt, "dnsDomainLevels", "www.netscape.com")106 assert.Nil(t, err, "should not error")107 assert.Equal(t, netscape, int64(2), "'www.netscape.com' should contain 2 domain levels")108}109func TestRuntimeShExpMatch(t *testing.T) {110 rt, _ := newRuntime()111 ari, err := callBooleanFunction(rt, "shExpMatch", "http://home.netscape.com/people/ari/index.html", "*/ari/*")112 assert.Nil(t, err, "should not error")113 assert.True(t, ari, "'http://home.netscape.com/people/ari/index.html' should match '*/ari/*'")114 montulli, err := callBooleanFunction(rt, "shExpMatch", "http://home.netscape.com/people/montulli/index.html", "*/ari/*")115 assert.Nil(t, err, "should not error")116 assert.False(t, montulli, "'http://home.netscape.com/people/montulli/index.html' should not match '*/ari/*'")117}...

Full Screen

Full Screen

handler.go

Source:handler.go Github

copy

Full Screen

1package clinic2import (3 "fmt"4 "github.com/gorilla/mux"5 "github.com/shwoodard/jsonapi"6 "net/http"7 "strconv"8)9func GetAllPets(w http.ResponseWriter, r *http.Request) {10 jsonapiRuntime := jsonapi.NewRuntime().Instrument("/")11 w.WriteHeader(200)12 w.Header().Set("Content-Type", "application/vnd.api+json")13 pets := AllPets()14 if err := jsonapiRuntime.MarshalManyPayload(w, pets); err != nil {15 http.Error(w, err.Error(), 500)16 }17}18func GetOnePet(w http.ResponseWriter, r *http.Request) {19 vars := mux.Vars(r)20 id, err := strconv.Atoi(vars["id"])21 if err != nil {22 fmt.Println("Invalid pet id")23 return24 }25 jsonapiRuntime := jsonapi.NewRuntime().Instrument("/")26 w.WriteHeader(200)27 w.Header().Set("Content-Type", "application/vnd.api+json")28 pet := ReadPet(&Pet{Id: id})29 if err := jsonapiRuntime.MarshalOnePayload(w, pet); err != nil {30 http.Error(w, err.Error(), 500)31 }32}33func CreateNewPet(w http.ResponseWriter, r *http.Request) {34 jsonapiRuntime := jsonapi.NewRuntime().Instrument("/")35 pet := new(Pet)36 if err := jsonapiRuntime.UnmarshalPayload(r.Body, pet); err != nil {37 http.Error(w, err.Error(), 500)38 return39 }40 NewPet(pet)41 w.WriteHeader(201)42 w.Header().Set("Content-Type", "application/vnd.api+json")43}44func UpdateExistingPet(w http.ResponseWriter, r *http.Request) {45 jsonapiRuntime := jsonapi.NewRuntime().Instrument("/")46 pet := new(Pet)47 if err := jsonapiRuntime.UnmarshalPayload(r.Body, pet); err != nil {48 http.Error(w, err.Error(), 500)49 return50 }51 UpdatePet(pet)52 if err := jsonapiRuntime.MarshalOnePayload(w, pet); err != nil {53 http.Error(w, err.Error(), 500)54 }55 w.WriteHeader(201)56 w.Header().Set("Content-Type", "application/vnd.api+json")57}...

Full Screen

Full Screen

newRuntime

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 runtime := http.NewServeMux()4 runtime.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {5 fmt.Fprintf(w, "Hello World")6 })7 http.ListenAndServe(":8080", runtime)8}

Full Screen

Full Screen

newRuntime

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 client := &http.Client{}4 if err != nil {5 fmt.Println("Error in creating request")6 }7 resp, err := client.Do(req)8 if err != nil {9 fmt.Println("Error in sending request")10 }11 fmt.Println("Response Status:", resp.Status)12 fmt.Println("Response Headers:", resp.Header)13}

Full Screen

Full Screen

newRuntime

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 m := http.NewServeMux()4 m.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) {5 fmt.Fprintln(w, "Hello world!")6 })7 http.ListenAndServe(":8080", m)8}

Full Screen

Full Screen

newRuntime

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 runtime := http.NewRuntime()4 if err != nil {5 panic(err)6 }7 resp, err := runtime.Do(req)8 if err != nil {9 panic(err)10 }11 fmt.Println(resp)12}

Full Screen

Full Screen

newRuntime

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println("Hello")4 fmt.Println(http.NewServeMux())5 fmt.Println(http.DefaultServeMux)6 fmt.Println(http.DefaultClient)7}

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful