How to use httpClient method of launcher Package

Best Rod code snippet using launcher.httpClient

launcher_helpers.go

Source:launcher_helpers.go Github

copy

Full Screen

...48 User *influxdb.User49 Org *influxdb.Organization50 Bucket *influxdb.Bucket51 Auth *influxdb.Authorization52 httpClient *httpc.Client53 apiClient *api.APIClient54 // Flag to act as standard server: disk store, no-e2e testing flag55 realServer bool56}57// RunAndSetupNewLauncherOrFail shorcuts the most common pattern used in testing,58// building a new TestLauncher, running it, and setting it up with an initial user.59func RunAndSetupNewLauncherOrFail(ctx context.Context, tb testing.TB, setters ...OptSetter) *TestLauncher {60 tb.Helper()61 l := NewTestLauncher()62 l.RunOrFail(tb, ctx, setters...)63 defer func() {64 // If setup fails, shut down the launcher.65 if tb.Failed() {66 l.Shutdown(ctx)67 }68 }()69 l.SetupOrFail(tb)70 return l71}72// NewTestLauncher returns a new instance of TestLauncher.73func NewTestLauncher() *TestLauncher {74 l := &TestLauncher{Launcher: NewLauncher()}75 path, err := os.MkdirTemp("", "")76 if err != nil {77 panic(err)78 }79 l.Path = path80 return l81}82// NewTestLauncherServer returns a new instance of TestLauncher configured as real server (disk store, no e2e flag).83func NewTestLauncherServer() *TestLauncher {84 l := NewTestLauncher()85 l.realServer = true86 return l87}88// URL returns the URL to connect to the HTTP server.89func (tl *TestLauncher) URL() *url.URL {90 u := url.URL{91 Host: fmt.Sprintf("127.0.0.1:%d", tl.Launcher.httpPort),92 Scheme: "http",93 }94 if tl.Launcher.tlsEnabled {95 u.Scheme = "https"96 }97 return &u98}99type OptSetter = func(o *InfluxdOpts)100func (tl *TestLauncher) SetFlagger(flagger feature.Flagger) {101 tl.Launcher.flagger = flagger102}103// Run executes the program, failing the test if the launcher fails to start.104func (tl *TestLauncher) RunOrFail(tb testing.TB, ctx context.Context, setters ...OptSetter) {105 if err := tl.Run(tb, ctx, setters...); err != nil {106 tb.Fatal(err)107 }108}109// Run executes the program with additional arguments to set paths and ports.110// Passed arguments will overwrite/add to the default ones.111func (tl *TestLauncher) Run(tb zaptest.TestingT, ctx context.Context, setters ...OptSetter) error {112 opts := NewOpts(viper.New())113 if !tl.realServer {114 opts.StoreType = "memory"115 opts.Testing = true116 }117 opts.TestingAlwaysAllowSetup = true118 opts.BoltPath = filepath.Join(tl.Path, bolt.DefaultFilename)119 opts.SqLitePath = filepath.Join(tl.Path, sqlite.DefaultFilename)120 opts.EnginePath = filepath.Join(tl.Path, "engine")121 opts.HttpBindAddress = "127.0.0.1:0"122 opts.LogLevel = zap.DebugLevel123 opts.ReportingDisabled = true124 opts.ConcurrencyQuota = 32125 opts.QueueSize = 16126 for _, setter := range setters {127 setter(opts)128 }129 // Set up top-level logger to write into the test-case.130 tl.Launcher.log = zaptest.NewLogger(tb, zaptest.Level(opts.LogLevel)).With(zap.String("test_name", tb.Name()))131 return tl.Launcher.run(ctx, opts)132}133// Shutdown stops the program and cleans up temporary paths.134func (tl *TestLauncher) Shutdown(ctx context.Context) error {135 defer os.RemoveAll(tl.Path)136 tl.cancel()137 return tl.Launcher.Shutdown(ctx)138}139// ShutdownOrFail stops the program and cleans up temporary paths. Fail on error.140func (tl *TestLauncher) ShutdownOrFail(tb testing.TB, ctx context.Context) {141 tb.Helper()142 if err := tl.Shutdown(ctx); err != nil {143 tb.Fatal(err)144 }145}146// Setup creates a new user, bucket, org, and auth token.147func (tl *TestLauncher) Setup() error {148 results, err := tl.OnBoard(&influxdb.OnboardingRequest{149 User: "USER",150 Password: "PASSWORD",151 Org: "ORG",152 Bucket: "BUCKET",153 })154 if err != nil {155 return err156 }157 tl.User = results.User158 tl.Org = results.Org159 tl.Bucket = results.Bucket160 tl.Auth = results.Auth161 return nil162}163// SetupOrFail creates a new user, bucket, org, and auth token. Fail on error.164func (tl *TestLauncher) SetupOrFail(tb testing.TB) {165 if err := tl.Setup(); err != nil {166 tb.Fatal(err)167 }168}169// OnBoard attempts an on-boarding request.170// The on-boarding status is also reset to allow multiple user/org/buckets to be created.171func (tl *TestLauncher) OnBoard(req *influxdb.OnboardingRequest) (*influxdb.OnboardingResults, error) {172 return tl.apibackend.OnboardingService.OnboardInitialUser(context.Background(), req)173}174// OnBoardOrFail attempts an on-boarding request or fails on error.175// The on-boarding status is also reset to allow multiple user/org/buckets to be created.176func (tl *TestLauncher) OnBoardOrFail(tb testing.TB, req *influxdb.OnboardingRequest) *influxdb.OnboardingResults {177 tb.Helper()178 res, err := tl.OnBoard(req)179 if err != nil {180 tb.Fatal(err)181 }182 return res183}184// WriteOrFail attempts a write to the organization and bucket identified by to or fails if there is an error.185func (tl *TestLauncher) WriteOrFail(tb testing.TB, to *influxdb.OnboardingResults, data string) {186 tb.Helper()187 resp, err := nethttp.DefaultClient.Do(tl.NewHTTPRequestOrFail(tb, "POST", fmt.Sprintf("/api/v2/write?org=%s&bucket=%s", to.Org.ID, to.Bucket.ID), to.Auth.Token, data))188 if err != nil {189 tb.Fatal(err)190 }191 body, err := io.ReadAll(resp.Body)192 if err != nil {193 tb.Fatal(err)194 }195 if err := resp.Body.Close(); err != nil {196 tb.Fatal(err)197 }198 if resp.StatusCode != nethttp.StatusNoContent {199 tb.Fatalf("unexpected status code: %d, body: %s, headers: %v", resp.StatusCode, body, resp.Header)200 }201}202// WritePoints attempts a write to the organization and bucket used during setup.203func (tl *TestLauncher) WritePoints(data string) error {204 req, err := tl.NewHTTPRequest(205 "POST", fmt.Sprintf("/api/v2/write?org=%s&bucket=%s", tl.Org.ID, tl.Bucket.ID),206 tl.Auth.Token, data)207 if err != nil {208 return err209 }210 resp, err := nethttp.DefaultClient.Do(req)211 if err != nil {212 return err213 }214 body, err := io.ReadAll(resp.Body)215 if err != nil {216 return err217 }218 if err := resp.Body.Close(); err != nil {219 return err220 }221 if resp.StatusCode != nethttp.StatusNoContent {222 return fmt.Errorf("unexpected status code: %d, body: %s, headers: %v", resp.StatusCode, body, resp.Header)223 }224 return nil225}226// WritePointsOrFail attempts a write to the organization and bucket used during setup or fails if there is an error.227func (tl *TestLauncher) WritePointsOrFail(tb testing.TB, data string) {228 tb.Helper()229 if err := tl.WritePoints(data); err != nil {230 tb.Fatal(err)231 }232}233// MustExecuteQuery executes the provided query panicking if an error is encountered.234// Callers of MustExecuteQuery must call Done on the returned QueryResults.235func (tl *TestLauncher) MustExecuteQuery(query string) *QueryResults {236 results, err := tl.ExecuteQuery(query)237 if err != nil {238 panic(err)239 }240 return results241}242// ExecuteQuery executes the provided query against the ith query node.243// Callers of ExecuteQuery must call Done on the returned QueryResults.244func (tl *TestLauncher) ExecuteQuery(q string) (*QueryResults, error) {245 ctx := influxdbcontext.SetAuthorizer(context.Background(), mock.NewMockAuthorizer(true, nil))246 ctx, _ = feature.Annotate(ctx, tl.flagger)247 fq, err := tl.QueryController().Query(ctx, &query.Request{248 Authorization: tl.Auth,249 OrganizationID: tl.Auth.OrgID,250 Compiler: lang.FluxCompiler{251 Query: q,252 }})253 if err != nil {254 return nil, err255 }256 results := make([]flux.Result, 0, 1)257 for res := range fq.Results() {258 results = append(results, res)259 }260 if err := fq.Err(); err != nil {261 fq.Done()262 return nil, err263 }264 return &QueryResults{265 Results: results,266 Query: fq,267 }, nil268}269// QueryAndConsume queries InfluxDB using the request provided. It uses a function to consume the results obtained.270// It returns the first error encountered when requesting the query, consuming the results, or executing the query.271func (tl *TestLauncher) QueryAndConsume(ctx context.Context, req *query.Request, fn func(r flux.Result) error) error {272 res, err := tl.FluxQueryService().Query(ctx, req)273 if err != nil {274 return err275 }276 // iterate over results to populate res.Err()277 var gotErr error278 for res.More() {279 if err := fn(res.Next()); gotErr == nil {280 gotErr = err281 }282 }283 if gotErr != nil {284 return gotErr285 }286 return res.Err()287}288// QueryAndNopConsume does the same as QueryAndConsume but consumes results with a nop function.289func (tl *TestLauncher) QueryAndNopConsume(ctx context.Context, req *query.Request) error {290 return tl.QueryAndConsume(ctx, req, func(r flux.Result) error {291 return r.Tables().Do(func(table flux.Table) error {292 return nil293 })294 })295}296// FluxQueryOrFail performs a query to the specified organization and returns the results297// or fails if there is an error.298func (tl *TestLauncher) FluxQueryOrFail(tb testing.TB, org *influxdb.Organization, token string, query string) string {299 tb.Helper()300 b, err := http.SimpleQuery(tl.URL(), query, org.Name, token)301 if err != nil {302 tb.Fatal(err)303 }304 return string(b)305}306// QueryFlux returns the csv response from a flux query.307// It also removes all the \r to make it easier to write tests.308func (tl *TestLauncher) QueryFlux(tb testing.TB, org *influxdb.Organization, token, query string) string {309 tb.Helper()310 b, err := http.SimpleQuery(tl.URL(), query, org.Name, token)311 if err != nil {312 tb.Fatal(err)313 }314 // remove all \r as well as the extra terminating \n315 b = bytes.ReplaceAll(b, []byte("\r"), nil)316 return string(b[:len(b)-1])317}318func (tl *TestLauncher) BackupOrFail(tb testing.TB, ctx context.Context, req clibackup.Params) {319 tb.Helper()320 require.NoError(tb, tl.Backup(tb, ctx, req))321}322func (tl *TestLauncher) Backup(tb testing.TB, ctx context.Context, req clibackup.Params) error {323 tb.Helper()324 return tl.BackupService(tb).Backup(ctx, &req)325}326func (tl *TestLauncher) RestoreOrFail(tb testing.TB, ctx context.Context, req clirestore.Params) {327 tb.Helper()328 require.NoError(tb, tl.Restore(tb, ctx, req))329}330func (tl *TestLauncher) Restore(tb testing.TB, ctx context.Context, req clirestore.Params) error {331 tb.Helper()332 return tl.RestoreService(tb).Restore(ctx, &req)333}334// MustNewHTTPRequest returns a new nethttp.Request with base URL and auth attached. Fail on error.335func (tl *TestLauncher) MustNewHTTPRequest(method, rawurl, body string) *nethttp.Request {336 req, err := nethttp.NewRequest(method, tl.URL().String()+rawurl, strings.NewReader(body))337 if err != nil {338 panic(err)339 }340 req.Header.Set("Authorization", "Token "+tl.Auth.Token)341 return req342}343// NewHTTPRequest returns a new nethttp.Request with base URL and auth attached.344func (tl *TestLauncher) NewHTTPRequest(method, rawurl, token string, body string) (*nethttp.Request, error) {345 req, err := nethttp.NewRequest(method, tl.URL().String()+rawurl, strings.NewReader(body))346 if err != nil {347 return nil, err348 }349 req.Header.Set("Authorization", "Token "+token)350 return req, nil351}352// NewHTTPRequestOrFail returns a new nethttp.Request with base URL and auth attached. Fail on error.353func (tl *TestLauncher) NewHTTPRequestOrFail(tb testing.TB, method, rawurl, token string, body string) *nethttp.Request {354 tb.Helper()355 req, err := tl.NewHTTPRequest(method, rawurl, token, body)356 if err != nil {357 tb.Fatal(err)358 }359 return req360}361// Services362func (tl *TestLauncher) FluxService() *http.FluxService {363 return &http.FluxService{Addr: tl.URL().String(), Token: tl.Auth.Token}364}365func (tl *TestLauncher) FluxQueryService() *http.FluxQueryService {366 return &http.FluxQueryService{Addr: tl.URL().String(), Token: tl.Auth.Token}367}368func (tl *TestLauncher) BucketService(tb testing.TB) *tenant.BucketClientService {369 tb.Helper()370 return &tenant.BucketClientService{Client: tl.HTTPClient(tb)}371}372func (tl *TestLauncher) DashboardService(tb testing.TB) influxdb.DashboardService {373 tb.Helper()374 return &dashboardTransport.DashboardService{Client: tl.HTTPClient(tb)}375}376func (tl *TestLauncher) LabelService(tb testing.TB) influxdb.LabelService {377 tb.Helper()378 return &label.LabelClientService{Client: tl.HTTPClient(tb)}379}380func (tl *TestLauncher) NotificationEndpointService(tb testing.TB) *http.NotificationEndpointService {381 tb.Helper()382 return http.NewNotificationEndpointService(tl.HTTPClient(tb))383}384func (tl *TestLauncher) NotificationRuleService(tb testing.TB) influxdb.NotificationRuleStore {385 tb.Helper()386 return http.NewNotificationRuleService(tl.HTTPClient(tb))387}388func (tl *TestLauncher) OrgService(tb testing.TB) influxdb.OrganizationService {389 tb.Helper()390 return &tenant.OrgClientService{Client: tl.HTTPClient(tb)}391}392func (tl *TestLauncher) PkgerService(tb testing.TB) pkger.SVC {393 return &pkger.HTTPRemoteService{Client: tl.HTTPClient(tb)}394}395func (tl *TestLauncher) TaskServiceKV(tb testing.TB) taskmodel.TaskService {396 return tl.kvService397}398func (tl *TestLauncher) TelegrafService(tb testing.TB) *http.TelegrafService {399 tb.Helper()400 return http.NewTelegrafService(tl.HTTPClient(tb))401}402func (tl *TestLauncher) VariableService(tb testing.TB) *http.VariableService {403 tb.Helper()404 return &http.VariableService{Client: tl.HTTPClient(tb)}405}406func (tl *TestLauncher) AuthorizationService(tb testing.TB) *http.AuthorizationService {407 tb.Helper()408 return &http.AuthorizationService{Client: tl.HTTPClient(tb)}409}410func (tl *TestLauncher) TaskService(tb testing.TB) taskmodel.TaskService {411 tb.Helper()412 return &http.TaskService{Client: tl.HTTPClient(tb)}413}414func (tl *TestLauncher) BackupService(tb testing.TB) *clibackup.Client {415 tb.Helper()416 client := tl.APIClient(tb)417 return &clibackup.Client{418 CLI: clients.CLI{},419 BackupApi: client.BackupApi,420 HealthApi: client.HealthApi,421 }422}423func (tl *TestLauncher) RestoreService(tb testing.TB) *clirestore.Client {424 tb.Helper()425 client := tl.APIClient(tb)426 return &clirestore.Client{427 CLI: clients.CLI{},428 HealthApi: client.HealthApi,429 RestoreApi: client.RestoreApi,430 BucketsApi: client.BucketsApi,431 OrganizationsApi: client.OrganizationsApi,432 ApiConfig: client,433 }434}435func (tl *TestLauncher) ResetHTTPCLient() {436 tl.httpClient = nil437}438func (tl *TestLauncher) HTTPClient(tb testing.TB) *httpc.Client {439 tb.Helper()440 if tl.httpClient == nil {441 token := ""442 if tl.Auth != nil {443 token = tl.Auth.Token444 }445 client, err := http.NewHTTPClient(tl.URL().String(), token, false)446 if err != nil {447 tb.Fatal(err)448 }449 tl.httpClient = client450 }451 return tl.httpClient452}453func (tl *TestLauncher) APIClient(tb testing.TB) *api.APIClient {454 tb.Helper()455 if tl.apiClient == nil {456 params := api.ConfigParams{457 Host: tl.URL(),458 }459 if tl.Auth != nil {460 params.Token = &tl.Auth.Token461 }462 tl.apiClient = api.NewAPIClient(api.NewAPIConfig(params))463 }464 return tl.apiClient465}...

Full Screen

Full Screen

httpClient

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 client := &http.Client{}4 if err != nil {5 fmt.Println("Error:", err)6 }7 resp, err := client.Do(req)8 if err != nil {9 fmt.Println("Error:", err)10 }11 defer resp.Body.Close()12 fmt.Println("Response status:", resp.Status)13}14import (15func main() {16 if err != nil {17 fmt.Println("Error:", err)18 }19 resp, err := http.DefaultClient.Do(req)20 if err != nil {21 fmt.Println("Error:", err)22 }23 defer resp.Body.Close()24 fmt.Println("Response status:", resp.Status)25}26import (27func main() {28 if err != nil {29 fmt.Println("Error:", err)30 }31 defer resp.Body.Close()32 fmt.Println("Response status:", resp.Status)33}34import (35func main() {36 if err != nil {37 fmt.Println("Error:", err)38 }39 defer resp.Body.Close()40 fmt.Println("Response status:", resp.Status)41}42import (43func main() {44 if err != nil {45 fmt.Println("Error:", err)46 }47 defer resp.Body.Close()48 fmt.Println("Response status:", resp.Status)49}

Full Screen

Full Screen

httpClient

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 if err != nil {4 fmt.Println(err)5 } else {6 fmt.Println(resp.Status)7 }8}9import (10func main() {11 client := &http.Client{}12 if err != nil {13 fmt.Println(err)14 } else {15 fmt.Println(resp.Status)16 }17}18import (19func main() {20 client := &http.Client{21 }22 if err != nil {23 fmt.Println(err)24 } else {25 fmt.Println(resp.Status)26 }27}28import (29func main() {30 client := &http.Client{31 Transport: &http.Transport{32 },33 }34 if err != nil {35 fmt.Println(err)36 } else {37 fmt.Println(resp.Status)38 }39}40import (41func main() {42 client := &http.Client{43 Transport: &http.Transport{44 },45 }46 if err != nil {47 fmt.Println(err)48 } else {

Full Screen

Full Screen

httpClient

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println("URL:>", url)4 var jsonStr = []byte(`{"name":"test"}`)5 req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))6 req.Header.Set("X-Custom-Header", "myvalue")7 req.Header.Set("Content-Type", "application/json")8 client := &http.Client{}9 resp, err := client.Do(req)10 if err != nil {11 panic(err)12 }13 defer resp.Body.Close()14 fmt.Println("response Status:", resp.Status)15 fmt.Println("response Headers:", resp.Header)16 body, _ := ioutil.ReadAll(resp.Body)17 fmt.Println("response Body:", string(body))18}

Full Screen

Full Screen

httpClient

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println("Hello, playground")4 if err != nil {5 }6 defer resp.Body.Close()7 fmt.Println(resp)8}

Full Screen

Full Screen

httpClient

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 launcher := new(Launcher)4 launcher.httpClient()5}6import (7func main() {8 launcher := new(Launcher)9 launcher.httpGet()10}11import (12func main() {13 launcher := new(Launcher)14 launcher.httpGet()15}16import (17func main() {18 launcher := new(Launcher)19 launcher.httpGet()20}21import (22func main() {23 launcher := new(Launcher)24 launcher.httpGet()25}26import (27func main() {28 launcher := new(Launcher)29 launcher.httpGet()30}31import (32func main() {33 launcher := new(Launcher)34 launcher.httpGet()35}36import (37func main() {38 launcher := new(Launcher)39 launcher.httpGet()40}41import (42func main() {43 launcher := new(Launcher)44 launcher.httpGet()45}46import (47func main() {

Full Screen

Full Screen

httpClient

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 client := http.Client{}4 response, err := client.Do(request)5 if err != nil {6 fmt.Println(err)7 } else {8 fmt.Println(response)9 }10}11import (12func main() {13 client := http.Client{}14 response, err := client.Do(request)15 if err != nil {16 fmt.Println(err)17 } else {18 fmt.Println(response)19 }20}21import (22func main() {23 client := http.Client{}24 response, err := client.Do(request)25 if err != nil {26 fmt.Println(err)27 } else {28 fmt.Println(response)29 }30}31import (32func main() {33 client := http.Client{}34 response, err := client.Do(request)35 if err != nil {36 fmt.Println(err)37 } else {38 fmt.Println(response)39 }40}

Full Screen

Full Screen

httpClient

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 resp, err := http.Get(url)4 if err != nil {5 fmt.Printf("%s", err)6 os.Exit(1)7 }8 fmt.Printf("%s", resp.Status)9}10import (11func main() {12 resp, err := http.Get(url)13 if err != nil {14 fmt.Printf("%s", err)15 os.Exit(1)16 }17 fmt.Printf("%s", resp.Status)18}19import (20func main() {21 resp, err := http.Get(url)22 if err != nil {23 fmt.Printf("%s", err)24 os.Exit(1)25 }26 fmt.Printf("%s", resp.Status)27}28import (29func main() {30 resp, err := http.Get(url)31 if err != nil {32 fmt.Printf("%s", err)33 os.Exit(1)34 }35 fmt.Printf("%s", resp.Status)36}37import (38func main() {39 resp, err := http.Get(url)40 if err != nil {41 fmt.Printf("%s", err)42 os.Exit(1)43 }

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