Best Syzkaller code snippet using serializer.Write
apiserver.go
Source:apiserver.go
...45}46// mux is an object that can register http handlers.47type Mux interface {48 Handle(pattern string, handler http.Handler)49 HandleFunc(pattern string, handler func(http.ResponseWriter, *http.Request))50}51// APIGroupVersion is a helper for exposing rest.Storage objects as http.Handlers via go-restful52// It handles URLs of the form:53// /${storage_key}[/${object_name}]54// Where 'storage_key' points to a rest.Storage object stored in storage.55// This object should contain all parameterization necessary for running a particular API version56type APIGroupVersion struct {57 Storage map[string]rest.Storage58 Root string59 // GroupVersion is the external group version60 GroupVersion unversioned.GroupVersion61 // RequestInfoResolver is used to parse URLs for the legacy proxy handler. Don't use this for anything else62 // TODO: refactor proxy handler to use sub resources63 RequestInfoResolver *RequestInfoResolver64 // OptionsExternalVersion controls the Kubernetes APIVersion used for common objects in the apiserver65 // schema like api.Status, api.DeleteOptions, and api.ListOptions. Other implementors may66 // define a version "v1beta1" but want to use the Kubernetes "v1" internal objects. If67 // empty, defaults to GroupVersion.68 OptionsExternalVersion *unversioned.GroupVersion69 Mapper meta.RESTMapper70 // Serializer is used to determine how to convert responses from API methods into bytes to send over71 // the wire.72 Serializer runtime.NegotiatedSerializer73 ParameterCodec runtime.ParameterCodec74 Typer runtime.ObjectTyper75 Creater runtime.ObjectCreater76 Convertor runtime.ObjectConvertor77 Copier runtime.ObjectCopier78 Linker runtime.SelfLinker79 Admit admission.Interface80 Context api.RequestContextMapper81 MinRequestTimeout time.Duration82 // SubresourceGroupVersionKind contains the GroupVersionKind overrides for each subresource that is83 // accessible from this API group version. The GroupVersionKind is that of the external version of84 // the subresource. The key of this map should be the path of the subresource. The keys here should85 // match the keys in the Storage map above for subresources.86 SubresourceGroupVersionKind map[string]unversioned.GroupVersionKind87}88type ProxyDialerFunc func(network, addr string) (net.Conn, error)89// TODO: Pipe these in through the apiserver cmd line90const (91 // Minimum duration before timing out read/write requests92 MinTimeoutSecs = 30093 // Maximum duration before timing out read/write requests94 MaxTimeoutSecs = 60095)96// InstallREST registers the REST handlers (storage, watch, proxy and redirect) into a restful Container.97// It is expected that the provided path root prefix will serve all operations. Root MUST NOT end98// in a slash.99func (g *APIGroupVersion) InstallREST(container *restful.Container) error {100 installer := g.newInstaller()101 ws := installer.NewWebService()102 apiResources, registrationErrors := installer.Install(ws)103 AddSupportedResourcesWebService(g.Serializer, ws, g.GroupVersion, apiResources)104 container.Add(ws)105 return utilerrors.NewAggregate(registrationErrors)106}107// UpdateREST registers the REST handlers for this APIGroupVersion to an existing web service108// in the restful Container. It will use the prefix (root/version) to find the existing109// web service. If a web service does not exist within the container to support the prefix110// this method will return an error.111func (g *APIGroupVersion) UpdateREST(container *restful.Container) error {112 installer := g.newInstaller()113 var ws *restful.WebService = nil114 for i, s := range container.RegisteredWebServices() {115 if s.RootPath() == installer.prefix {116 ws = container.RegisteredWebServices()[i]117 break118 }119 }120 if ws == nil {121 return apierrors.NewInternalError(fmt.Errorf("unable to find an existing webservice for prefix %s", installer.prefix))122 }123 apiResources, registrationErrors := installer.Install(ws)124 AddSupportedResourcesWebService(g.Serializer, ws, g.GroupVersion, apiResources)125 return utilerrors.NewAggregate(registrationErrors)126}127// newInstaller is a helper to create the installer. Used by InstallREST and UpdateREST.128func (g *APIGroupVersion) newInstaller() *APIInstaller {129 prefix := path.Join(g.Root, g.GroupVersion.Group, g.GroupVersion.Version)130 installer := &APIInstaller{131 group: g,132 info: g.RequestInfoResolver,133 prefix: prefix,134 minRequestTimeout: g.MinRequestTimeout,135 }136 return installer137}138// TODO: document all handlers139// InstallVersionHandler registers the APIServer's `/version` handler140func InstallVersionHandler(mux Mux, container *restful.Container) {141 // Set up a service to return the git code version.142 versionWS := new(restful.WebService)143 versionWS.Path("/version")144 versionWS.Doc("git code version from which this is built")145 versionWS.Route(146 versionWS.GET("/").To(handleVersion).147 Doc("get the code version").148 Operation("getCodeVersion").149 Produces(restful.MIME_JSON).150 Consumes(restful.MIME_JSON).151 Writes(version.Info{}))152 container.Add(versionWS)153}154// InstallLogsSupport registers the APIServer log support function into a mux.155func InstallLogsSupport(mux Mux) {156 // TODO: use restful: ws.Route(ws.GET("/logs/{logpath:*}").To(fileHandler))157 // See github.com/emicklei/go-restful/blob/master/examples/restful-serve-static.go158 mux.Handle("/logs/", http.StripPrefix("/logs/", http.FileServer(http.Dir("/var/log/"))))159}160// TODO: needs to perform response type negotiation, this is probably the wrong way to recover panics161func InstallRecoverHandler(s runtime.NegotiatedSerializer, container *restful.Container) {162 container.RecoverHandler(func(panicReason interface{}, httpWriter http.ResponseWriter) {163 logStackOnRecover(s, panicReason, httpWriter)164 })165}166//TODO: Unify with RecoverPanics?167func logStackOnRecover(s runtime.NegotiatedSerializer, panicReason interface{}, w http.ResponseWriter) {168 var buffer bytes.Buffer169 buffer.WriteString(fmt.Sprintf("recover from panic situation: - %v\r\n", panicReason))170 for i := 2; ; i += 1 {171 _, file, line, ok := rt.Caller(i)172 if !ok {173 break174 }175 buffer.WriteString(fmt.Sprintf(" %s:%d\r\n", file, line))176 }177 glog.Errorln(buffer.String())178 headers := http.Header{}179 if ct := w.Header().Get("Content-Type"); len(ct) > 0 {180 headers.Set("Accept", ct)181 }182 errorNegotiated(apierrors.NewGenericServerResponse(http.StatusInternalServerError, "", api.Resource(""), "", "", 0, false), s, unversioned.GroupVersion{}, w, &http.Request{Header: headers})183}184func InstallServiceErrorHandler(s runtime.NegotiatedSerializer, container *restful.Container, requestResolver *RequestInfoResolver, apiVersions []string) {185 container.ServiceErrorHandler(func(serviceErr restful.ServiceError, request *restful.Request, response *restful.Response) {186 serviceErrorHandler(s, requestResolver, apiVersions, serviceErr, request, response)187 })188}189func serviceErrorHandler(s runtime.NegotiatedSerializer, requestResolver *RequestInfoResolver, apiVersions []string, serviceErr restful.ServiceError, request *restful.Request, response *restful.Response) {190 errorNegotiated(apierrors.NewGenericServerResponse(serviceErr.Code, "", api.Resource(""), "", "", 0, false), s, unversioned.GroupVersion{}, response.ResponseWriter, request.Request)191}192// Adds a service to return the supported api versions at the legacy /api.193func AddApiWebService(s runtime.NegotiatedSerializer, container *restful.Container, apiPrefix string, getAPIVersionsFunc func(req *restful.Request) *unversioned.APIVersions) {194 // TODO: InstallREST should register each version automatically195 // Because in release 1.1, /api returns response with empty APIVersion, we196 // use StripVersionNegotiatedSerializer to keep the response backwards197 // compatible.198 ss := StripVersionNegotiatedSerializer{s}199 versionHandler := APIVersionHandler(ss, getAPIVersionsFunc)200 ws := new(restful.WebService)201 ws.Path(apiPrefix)202 ws.Doc("get available API versions")203 ws.Route(ws.GET("/").To(versionHandler).204 Doc("get available API versions").205 Operation("getAPIVersions").206 Produces(s.SupportedMediaTypes()...).207 Consumes(s.SupportedMediaTypes()...).208 Writes(unversioned.APIVersions{}))209 container.Add(ws)210}211// stripVersionEncoder strips APIVersion field from the encoding output. It's212// used to keep the responses at the discovery endpoints backward compatible213// with release-1.1, when the responses have empty APIVersion.214type stripVersionEncoder struct {215 encoder runtime.Encoder216 serializer runtime.Serializer217}218func (c stripVersionEncoder) Encode(obj runtime.Object, w io.Writer) error {219 buf := bytes.NewBuffer([]byte{})220 err := c.encoder.Encode(obj, buf)221 if err != nil {222 return err223 }224 roundTrippedObj, gvk, err := c.serializer.Decode(buf.Bytes(), nil, nil)225 if err != nil {226 return err227 }228 gvk.Group = ""229 gvk.Version = ""230 roundTrippedObj.GetObjectKind().SetGroupVersionKind(*gvk)231 return c.serializer.Encode(roundTrippedObj, w)232}233// StripVersionNegotiatedSerializer will return stripVersionEncoder when234// EncoderForVersion is called. See comments for stripVersionEncoder.235type StripVersionNegotiatedSerializer struct {236 runtime.NegotiatedSerializer237}238func (n StripVersionNegotiatedSerializer) EncoderForVersion(encoder runtime.Encoder, gv unversioned.GroupVersion) runtime.Encoder {239 serializer, ok := encoder.(runtime.Serializer)240 if !ok {241 // The stripVersionEncoder needs both an encoder and decoder, but is called from a context that doesn't have access to the242 // decoder. We do a best effort cast here (since this code path is only for backwards compatibility) to get access to the caller's243 // decoder.244 panic(fmt.Sprintf("Unable to extract serializer from %#v", encoder))245 }246 versioned := n.NegotiatedSerializer.EncoderForVersion(encoder, gv)247 return stripVersionEncoder{versioned, serializer}248}249func keepUnversioned(group string) bool {250 return group == "" || group == "extensions"251}252// Adds a service to return the supported api versions at /apis.253func AddApisWebService(s runtime.NegotiatedSerializer, container *restful.Container, apiPrefix string, f func(req *restful.Request) []unversioned.APIGroup) {254 // Because in release 1.1, /apis returns response with empty APIVersion, we255 // use StripVersionNegotiatedSerializer to keep the response backwards256 // compatible.257 ss := StripVersionNegotiatedSerializer{s}258 rootAPIHandler := RootAPIHandler(ss, f)259 ws := new(restful.WebService)260 ws.Path(apiPrefix)261 ws.Doc("get available API versions")262 ws.Route(ws.GET("/").To(rootAPIHandler).263 Doc("get available API versions").264 Operation("getAPIVersions").265 Produces(s.SupportedMediaTypes()...).266 Consumes(s.SupportedMediaTypes()...).267 Writes(unversioned.APIGroupList{}))268 container.Add(ws)269}270// Adds a service to return the supported versions, preferred version, and name271// of a group. E.g., a such web service will be registered at /apis/extensions.272func AddGroupWebService(s runtime.NegotiatedSerializer, container *restful.Container, path string, group unversioned.APIGroup) {273 ss := s274 if keepUnversioned(group.Name) {275 // Because in release 1.1, /apis/extensions returns response with empty276 // APIVersion, we use StripVersionNegotiatedSerializer to keep the277 // response backwards compatible.278 ss = StripVersionNegotiatedSerializer{s}279 }280 groupHandler := GroupHandler(ss, group)281 ws := new(restful.WebService)282 ws.Path(path)283 ws.Doc("get information of a group")284 ws.Route(ws.GET("/").To(groupHandler).285 Doc("get information of a group").286 Operation("getAPIGroup").287 Produces(s.SupportedMediaTypes()...).288 Consumes(s.SupportedMediaTypes()...).289 Writes(unversioned.APIGroup{}))290 container.Add(ws)291}292// Adds a service to return the supported resources, E.g., a such web service293// will be registered at /apis/extensions/v1.294func AddSupportedResourcesWebService(s runtime.NegotiatedSerializer, ws *restful.WebService, groupVersion unversioned.GroupVersion, apiResources []unversioned.APIResource) {295 ss := s296 if keepUnversioned(groupVersion.Group) {297 // Because in release 1.1, /apis/extensions/v1beta1 returns response298 // with empty APIVersion, we use StripVersionNegotiatedSerializer to299 // keep the response backwards compatible.300 ss = StripVersionNegotiatedSerializer{s}301 }302 resourceHandler := SupportedResourcesHandler(ss, groupVersion, apiResources)303 ws.Route(ws.GET("/").To(resourceHandler).304 Doc("get available resources").305 Operation("getAPIResources").306 Produces(s.SupportedMediaTypes()...).307 Consumes(s.SupportedMediaTypes()...).308 Writes(unversioned.APIResourceList{}))309}310// handleVersion writes the server's version information.311func handleVersion(req *restful.Request, resp *restful.Response) {312 writeRawJSON(http.StatusOK, version.Get(), resp.ResponseWriter)313}314// APIVersionHandler returns a handler which will list the provided versions as available.315func APIVersionHandler(s runtime.NegotiatedSerializer, getAPIVersionsFunc func(req *restful.Request) *unversioned.APIVersions) restful.RouteFunction {316 return func(req *restful.Request, resp *restful.Response) {317 writeNegotiated(s, unversioned.GroupVersion{}, resp.ResponseWriter, req.Request, http.StatusOK, getAPIVersionsFunc(req))318 }319}320// RootAPIHandler returns a handler which will list the provided groups and versions as available.321func RootAPIHandler(s runtime.NegotiatedSerializer, f func(req *restful.Request) []unversioned.APIGroup) restful.RouteFunction {322 return func(req *restful.Request, resp *restful.Response) {323 writeNegotiated(s, unversioned.GroupVersion{}, resp.ResponseWriter, req.Request, http.StatusOK, &unversioned.APIGroupList{Groups: f(req)})324 }325}326// GroupHandler returns a handler which will return the api.GroupAndVersion of327// the group.328func GroupHandler(s runtime.NegotiatedSerializer, group unversioned.APIGroup) restful.RouteFunction {329 return func(req *restful.Request, resp *restful.Response) {330 writeNegotiated(s, unversioned.GroupVersion{}, resp.ResponseWriter, req.Request, http.StatusOK, &group)331 }332}333// SupportedResourcesHandler returns a handler which will list the provided resources as available.334func SupportedResourcesHandler(s runtime.NegotiatedSerializer, groupVersion unversioned.GroupVersion, apiResources []unversioned.APIResource) restful.RouteFunction {335 return func(req *restful.Request, resp *restful.Response) {336 writeNegotiated(s, unversioned.GroupVersion{}, resp.ResponseWriter, req.Request, http.StatusOK, &unversioned.APIResourceList{GroupVersion: groupVersion.String(), APIResources: apiResources})337 }338}339// write renders a returned runtime.Object to the response as a stream or an encoded object. If the object340// returned by the response implements rest.ResourceStreamer that interface will be used to render the341// response. The Accept header and current API version will be passed in, and the output will be copied342// directly to the response body. If content type is returned it is used, otherwise the content type will343// be "application/octet-stream". All other objects are sent to standard JSON serialization.344func write(statusCode int, gv unversioned.GroupVersion, s runtime.NegotiatedSerializer, object runtime.Object, w http.ResponseWriter, req *http.Request) {345 if stream, ok := object.(rest.ResourceStreamer); ok {346 out, flush, contentType, err := stream.InputStream(gv.String(), req.Header.Get("Accept"))347 if err != nil {348 errorNegotiated(err, s, gv, w, req)349 return350 }351 if out == nil {352 // No output provided - return StatusNoContent353 w.WriteHeader(http.StatusNoContent)354 return355 }356 defer out.Close()357 if wsstream.IsWebSocketRequest(req) {358 r := wsstream.NewReader(out, true)359 if err := r.Copy(w, req); err != nil {360 utilruntime.HandleError(fmt.Errorf("error encountered while streaming results via websocket: %v", err))361 }362 return363 }364 if len(contentType) == 0 {365 contentType = "application/octet-stream"366 }367 w.Header().Set("Content-Type", contentType)368 w.WriteHeader(statusCode)369 writer := w.(io.Writer)370 if flush {371 writer = flushwriter.Wrap(w)372 }373 io.Copy(writer, out)374 return375 }376 writeNegotiated(s, gv, w, req, statusCode, object)377}378// writeNegotiated renders an object in the content type negotiated by the client379func writeNegotiated(s runtime.NegotiatedSerializer, gv unversioned.GroupVersion, w http.ResponseWriter, req *http.Request, statusCode int, object runtime.Object) {380 serializer, err := negotiateOutputSerializer(req, s)381 if err != nil {382 status := errToAPIStatus(err)383 writeRawJSON(int(status.Code), status, w)384 return385 }386 w.Header().Set("Content-Type", serializer.MediaType)387 w.WriteHeader(statusCode)388 encoder := s.EncoderForVersion(serializer, gv)389 if err := encoder.Encode(object, w); err != nil {390 errorJSONFatal(err, encoder, w)391 }392}393// errorNegotiated renders an error to the response. Returns the HTTP status code of the error.394func errorNegotiated(err error, s runtime.NegotiatedSerializer, gv unversioned.GroupVersion, w http.ResponseWriter, req *http.Request) int {395 status := errToAPIStatus(err)396 code := int(status.Code)397 // when writing an error, check to see if the status indicates a retry after period398 if status.Details != nil && status.Details.RetryAfterSeconds > 0 {399 delay := strconv.Itoa(int(status.Details.RetryAfterSeconds))400 w.Header().Set("Retry-After", delay)401 }402 writeNegotiated(s, gv, w, req, code, status)403 return code404}405// errorJSONFatal renders an error to the response, and if codec fails will render plaintext.406// Returns the HTTP status code of the error.407func errorJSONFatal(err error, codec runtime.Encoder, w http.ResponseWriter) int {408 utilruntime.HandleError(fmt.Errorf("apiserver was unable to write a JSON response: %v", err))409 status := errToAPIStatus(err)410 code := int(status.Code)411 output, err := runtime.Encode(codec, status)412 if err != nil {413 w.WriteHeader(code)414 fmt.Fprintf(w, "%s: %s", status.Reason, status.Message)415 return code416 }417 w.Header().Set("Content-Type", "application/json")418 w.WriteHeader(code)419 w.Write(output)420 return code421}422// writeRawJSON writes a non-API object in JSON.423func writeRawJSON(statusCode int, object interface{}, w http.ResponseWriter) {424 output, err := json.MarshalIndent(object, "", " ")425 if err != nil {426 http.Error(w, err.Error(), http.StatusInternalServerError)427 return428 }429 w.Header().Set("Content-Type", "application/json")430 w.WriteHeader(statusCode)431 w.Write(output)432}433func parseTimeout(str string) time.Duration {434 if str != "" {435 timeout, err := time.ParseDuration(str)436 if err == nil {437 return timeout438 }439 glog.Errorf("Failed to parse %q: %v", str, err)440 }441 return 30 * time.Second442}443func readBody(req *http.Request) ([]byte, error) {444 defer req.Body.Close()445 return ioutil.ReadAll(req.Body)...
http_test.go
Source:http_test.go
...81 },82 }83 for _, tt := range tests {84 t.Run(tt.name, func(t *testing.T) {85 ts.Config.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {86 require.Equal(t, tt.expectedMethod, r.Method)87 w.WriteHeader(http.StatusOK)88 })89 serializer := influx.NewSerializer()90 tt.plugin.SetSerializer(serializer)91 err = tt.plugin.Connect()92 if tt.connectError {93 require.Error(t, err)94 return95 }96 require.NoError(t, err)97 err = tt.plugin.Write([]telegraf.Metric{getMetric()})98 require.NoError(t, err)99 })100 }101}102func TestStatusCode(t *testing.T) {103 ts := httptest.NewServer(http.NotFoundHandler())104 defer ts.Close()105 u, err := url.Parse(fmt.Sprintf("http://%s", ts.Listener.Addr().String()))106 require.NoError(t, err)107 tests := []struct {108 name string109 plugin *HTTP110 statusCode int111 errFunc func(t *testing.T, err error)112 }{113 {114 name: "success",115 plugin: &HTTP{116 URL: u.String(),117 },118 statusCode: http.StatusOK,119 errFunc: func(t *testing.T, err error) {120 require.NoError(t, err)121 },122 },123 {124 name: "1xx status is an error",125 plugin: &HTTP{126 URL: u.String(),127 },128 statusCode: 103,129 errFunc: func(t *testing.T, err error) {130 require.Error(t, err)131 },132 },133 {134 name: "3xx status is an error",135 plugin: &HTTP{136 URL: u.String(),137 },138 statusCode: http.StatusMultipleChoices,139 errFunc: func(t *testing.T, err error) {140 require.Error(t, err)141 },142 },143 {144 name: "4xx status is an error",145 plugin: &HTTP{146 URL: u.String(),147 },148 statusCode: http.StatusMultipleChoices,149 errFunc: func(t *testing.T, err error) {150 require.Error(t, err)151 },152 },153 }154 for _, tt := range tests {155 t.Run(tt.name, func(t *testing.T) {156 ts.Config.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {157 w.WriteHeader(tt.statusCode)158 })159 serializer := influx.NewSerializer()160 tt.plugin.SetSerializer(serializer)161 err = tt.plugin.Connect()162 require.NoError(t, err)163 err = tt.plugin.Write([]telegraf.Metric{getMetric()})164 tt.errFunc(t, err)165 })166 }167}168func TestContentType(t *testing.T) {169 ts := httptest.NewServer(http.NotFoundHandler())170 defer ts.Close()171 u, err := url.Parse(fmt.Sprintf("http://%s", ts.Listener.Addr().String()))172 require.NoError(t, err)173 tests := []struct {174 name string175 plugin *HTTP176 expected string177 }{178 {179 name: "default is text plain",180 plugin: &HTTP{181 URL: u.String(),182 },183 expected: defaultContentType,184 },185 {186 name: "overwrite content_type",187 plugin: &HTTP{188 URL: u.String(),189 Headers: map[string]string{"Content-Type": "application/json"},190 },191 expected: "application/json",192 },193 }194 for _, tt := range tests {195 t.Run(tt.name, func(t *testing.T) {196 ts.Config.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {197 require.Equal(t, tt.expected, r.Header.Get("Content-Type"))198 w.WriteHeader(http.StatusOK)199 })200 serializer := influx.NewSerializer()201 tt.plugin.SetSerializer(serializer)202 err = tt.plugin.Connect()203 require.NoError(t, err)204 err = tt.plugin.Write([]telegraf.Metric{getMetric()})205 require.NoError(t, err)206 })207 }208}209func TestContentEncodingGzip(t *testing.T) {210 ts := httptest.NewServer(http.NotFoundHandler())211 defer ts.Close()212 u, err := url.Parse(fmt.Sprintf("http://%s", ts.Listener.Addr().String()))213 require.NoError(t, err)214 tests := []struct {215 name string216 plugin *HTTP217 payload string218 expected string219 }{220 {221 name: "default is no content encoding",222 plugin: &HTTP{223 URL: u.String(),224 },225 expected: "",226 },227 {228 name: "overwrite content_encoding",229 plugin: &HTTP{230 URL: u.String(),231 ContentEncoding: "gzip",232 },233 expected: "gzip",234 },235 }236 for _, tt := range tests {237 t.Run(tt.name, func(t *testing.T) {238 ts.Config.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {239 require.Equal(t, tt.expected, r.Header.Get("Content-Encoding"))240 body := r.Body241 var err error242 if r.Header.Get("Content-Encoding") == "gzip" {243 body, err = gzip.NewReader(r.Body)244 require.NoError(t, err)245 }246 payload, err := ioutil.ReadAll(body)247 require.NoError(t, err)248 require.Contains(t, string(payload), "cpu value=42")249 w.WriteHeader(http.StatusNoContent)250 })251 serializer := influx.NewSerializer()252 tt.plugin.SetSerializer(serializer)253 err = tt.plugin.Connect()254 require.NoError(t, err)255 err = tt.plugin.Write([]telegraf.Metric{getMetric()})256 require.NoError(t, err)257 })258 }259}260func TestBasicAuth(t *testing.T) {261 ts := httptest.NewServer(http.NotFoundHandler())262 defer ts.Close()263 u, err := url.Parse(fmt.Sprintf("http://%s", ts.Listener.Addr().String()))264 require.NoError(t, err)265 tests := []struct {266 name string267 plugin *HTTP268 }{269 {270 name: "default",271 plugin: &HTTP{272 URL: u.String(),273 },274 },275 {276 name: "username only",277 plugin: &HTTP{278 URL: u.String(),279 Username: "username",280 },281 },282 {283 name: "password only",284 plugin: &HTTP{285 URL: u.String(),286 Password: "pa$$word",287 },288 },289 {290 name: "username and password",291 plugin: &HTTP{292 URL: u.String(),293 Username: "username",294 Password: "pa$$word",295 },296 },297 }298 for _, tt := range tests {299 t.Run(tt.name, func(t *testing.T) {300 ts.Config.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {301 username, password, _ := r.BasicAuth()302 require.Equal(t, tt.plugin.Username, username)303 require.Equal(t, tt.plugin.Password, password)304 w.WriteHeader(http.StatusOK)305 })306 serializer := influx.NewSerializer()307 tt.plugin.SetSerializer(serializer)308 err = tt.plugin.Connect()309 require.NoError(t, err)310 err = tt.plugin.Write([]telegraf.Metric{getMetric()})311 require.NoError(t, err)312 })313 }314}315type TestHandlerFunc func(t *testing.T, w http.ResponseWriter, r *http.Request)316func TestOAuthClientCredentialsGrant(t *testing.T) {317 ts := httptest.NewServer(http.NotFoundHandler())318 defer ts.Close()319 var token = "2YotnFZFEjr1zCsicMWpAA"320 u, err := url.Parse(fmt.Sprintf("http://%s", ts.Listener.Addr().String()))321 require.NoError(t, err)322 tests := []struct {323 name string324 plugin *HTTP325 tokenHandler TestHandlerFunc326 handler TestHandlerFunc327 }{328 {329 name: "no credentials",330 plugin: &HTTP{331 URL: u.String(),332 },333 handler: func(t *testing.T, w http.ResponseWriter, r *http.Request) {334 require.Len(t, r.Header["Authorization"], 0)335 w.WriteHeader(http.StatusOK)336 },337 },338 {339 name: "success",340 plugin: &HTTP{341 URL: u.String() + "/write",342 ClientID: "howdy",343 ClientSecret: "secret",344 TokenURL: u.String() + "/token",345 Scopes: []string{"urn:opc:idm:__myscopes__"},346 },347 tokenHandler: func(t *testing.T, w http.ResponseWriter, r *http.Request) {348 w.WriteHeader(http.StatusOK)349 values := url.Values{}350 values.Add("access_token", token)351 values.Add("token_type", "bearer")352 values.Add("expires_in", "3600")353 w.Write([]byte(values.Encode()))354 },355 handler: func(t *testing.T, w http.ResponseWriter, r *http.Request) {356 require.Equal(t, []string{"Bearer " + token}, r.Header["Authorization"])357 w.WriteHeader(http.StatusOK)358 },359 },360 }361 for _, tt := range tests {362 t.Run(tt.name, func(t *testing.T) {363 ts.Config.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {364 switch r.URL.Path {365 case "/write":366 tt.handler(t, w, r)367 case "/token":368 tt.tokenHandler(t, w, r)369 }370 })371 serializer := influx.NewSerializer()372 tt.plugin.SetSerializer(serializer)373 err = tt.plugin.Connect()374 require.NoError(t, err)375 err = tt.plugin.Write([]telegraf.Metric{getMetric()})376 require.NoError(t, err)377 })378 }379}380func TestDefaultUserAgent(t *testing.T) {381 ts := httptest.NewServer(http.NotFoundHandler())382 defer ts.Close()383 u, err := url.Parse(fmt.Sprintf("http://%s", ts.Listener.Addr().String()))384 require.NoError(t, err)385 internal.SetVersion("1.2.3")386 t.Run("default-user-agent", func(t *testing.T) {387 ts.Config.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {388 require.Equal(t, "Telegraf/1.2.3", r.Header.Get("User-Agent"))389 w.WriteHeader(http.StatusOK)390 })391 client := &HTTP{392 URL: u.String(),393 Method: defaultMethod,394 }395 serializer := influx.NewSerializer()396 client.SetSerializer(serializer)397 err = client.Connect()398 require.NoError(t, err)399 err = client.Write([]telegraf.Metric{getMetric()})400 require.NoError(t, err)401 })402}...
serialize_test.go
Source:serialize_test.go
...7import (8 "bytes"9 "testing"10)11func TestNewWriter(t *testing.T) {12 buf := new(bytes.Buffer)13 s := NewWriter(buf)14 s.NextDataType("Test")15 s.WriteColumnNames([]string{"A", "B", "C"})16 s.AddRow().WriteBoolValue(true).WriteIntValue(1).WriteStringValue("abc").Done()17 r := s.AddRow()18 r.WriteBoolValue(false)19 r.WriteIntValue(2)20 r.WriteStringValue("def")21 r.Done()22 s.NextDataType("Second")23 s.WriteColumnNames([]string{"X"})24 r = s.AddRow()25 r.WriteStringValue("Y")26 r.Done()27 s.Finish()28 if s.Err() != nil {29 t.Errorf("Err() = %v", s.Err())30 }31 expected := "Test\nA\tB\tC\ntrue\t1\tabc\nfalse\t2\tdef\n\nSecond\nX\nY\n\n"32 if out := buf.String(); out != expected {33 t.Errorf("Invalid serialization, got\n%s\nwant\n%s", out, expected)34 }35}36func TestSerializer_Err(t *testing.T) {37 tests := []struct {38 name string39 f func(*Serializer)40 }{41 {42 "NextDataType two times in a row",43 func(s *Serializer) {44 s.NextDataType("a")45 s.NextDataType("b")46 },47 },48 {49 "Zero columns",50 func(s *Serializer) {51 s.NextDataType("a")52 s.WriteColumnNames([]string{})53 },54 },55 {56 "No Data columns",57 func(s *Serializer) {58 s.NextDataType("a")59 s.WriteColumnNames([]string{"c"})60 s.NextDataType("b")61 },62 },63 {64 "Too few data columns",65 func(s *Serializer) {66 s.NextDataType("a")67 s.WriteColumnNames([]string{"b", "c"})68 s.AddRow().WriteBoolValue(true).Done()69 },70 },71 {72 "Too many data columns",73 func(s *Serializer) {74 s.NextDataType("a")75 s.WriteColumnNames([]string{"b", "c"})76 s.AddRow().WriteBoolValue(true).WriteBoolValue(false).WriteBoolValue(true).Done()77 },78 },79 {80 "Not calling Done on a Row, before the next row",81 func(s *Serializer) {82 s.NextDataType("a")83 s.WriteColumnNames([]string{"b", "c"})84 s.AddRow().WriteBoolValue(true).WriteBoolValue(false)85 s.AddRow()86 },87 },88 {89 "Not calling Done on a Row, before the next data type",90 func(s *Serializer) {91 s.NextDataType("a")92 s.WriteColumnNames([]string{"b", "c"})93 s.AddRow().WriteBoolValue(true).WriteBoolValue(false)94 s.NextDataType("b")95 },96 },97 {98 "Calling finish twice",99 func(s *Serializer) {100 s.NextDataType("a")101 s.WriteColumnNames([]string{"b", "c"})102 s.AddRow().WriteBoolValue(true).WriteBoolValue(false).Done()103 s.Finish()104 s.Finish()105 },106 },107 {108 "Writing column names twice",109 func(s *Serializer) {110 s.NextDataType("a")111 s.WriteColumnNames([]string{"b", "c"})112 s.WriteColumnNames([]string{"d", "e"})113 },114 },115 {116 "Writing column names without a data type",117 func(s *Serializer) {118 s.WriteColumnNames([]string{"b", "c"})119 },120 },121 {122 "Writing column names without a data type, for the second type",123 func(s *Serializer) {124 s.NextDataType("a")125 s.WriteColumnNames([]string{"b", "c"})126 s.AddRow().WriteBoolValue(true).WriteBoolValue(false).Done()127 s.WriteColumnNames([]string{"b", "c"})128 },129 },130 }131 for _, tt := range tests {132 t.Run(tt.name, func(t *testing.T) {133 b := new(bytes.Buffer)134 s := NewWriter(b)135 tt.f(s)136 if err := s.Err(); err == nil {137 t.Errorf("Serializer.Err() error = nil, wanted error")138 }139 })140 }141}...
Write
Using AI Code Generation
1var serializer = new Serializer();2serializer.Write("Hello");3serializer.Write(5);4var serializer = new Serializer();5var str = serializer.Read();6var num = serializer.Read();7cannot use serializer (type *Serializer) as type Serializer in return argument8cannot use serializer (type *Serializer) as type Serializer in return argument9cannot use serializer (type *Serializer) as type Serializer in return argument10cannot use serializer (type *Serializer) as type Serializer in return argument11cannot use serializer (type *Serializer) as type Serializer in return argument12cannot use serializer (type *Serializer) as type Serializer in return argument13cannot use serializer (type *Serializer) as type Serializer in return argument14cannot use serializer (type *Serializer) as type Serializer in return argument15cannot use serializer (type *Serializer) as type Serializer in return argument16cannot use serializer (type *Serializer) as type Serializer in return argument17cannot use serializer (type *Serializer) as type Serializer in return argument18cannot use serializer (type *Serializer) as type Serializer
Write
Using AI Code Generation
1import (2type Person struct {3}4func main() {5 p := Person{"Bob", 20}6 serializedPerson, err := json.Marshal(p)7 if err != nil {8 log.Fatal("Error while serializing object")9 }10 err = ioutil.WriteFile("person.json", serializedPerson, 0644)11 if err != nil {12 log.Fatal("Error while writing to file")13 }14 fmt.Println("Successfully wrote to file")15}16import (17type Person struct {18}19func main() {20 serializedPerson, err := ioutil.ReadFile("person.json")21 if err != nil {22 log.Fatal("Error while reading file")23 }24 err = json.Unmarshal(serializedPerson, &p)25 if err != nil {26 log.Fatal("Error while deserializing object")27 }28 fmt.Println("Name: ", p.Name)29 fmt.Println("Age: ", p.Age)30}
Write
Using AI Code Generation
1import (2type Serializer struct {3}4func (s *Serializer) Write(v interface{}) {5 switch reflect.TypeOf(v).Kind() {6 s.w.WriteString(strconv.Itoa(v.(int)))7 s.w.WriteString(v.(string))8 s.w.WriteString(strconv.FormatBool(v.(bool)))9 }10}11func main() {12 s := Serializer{bufio.NewWriter(os.Stdout)}13 s.Write(10)14 s.w.Flush()15}16import (17type Serializer struct {18}19func (s *Serializer) Write(v interface{}) {20 switch reflect.TypeOf(v).Kind() {21 s.w.WriteString(strconv.Itoa(v.(int)))22 s.w.WriteString(v.(string))23 s.w.WriteString(strconv.FormatBool(v.(bool)))24 }25}26func main() {27 s := Serializer{bufio.NewWriter(os.Stdout)}28 s.Write([]interface{}{10, "Hello", true})29 s.w.Flush()30}31import (32type Serializer struct {33}34func (s *Serializer) Write(v interface{}) {35 switch reflect.TypeOf(v).Kind() {
Write
Using AI Code Generation
1import (2type Person struct {3}4func main() {5 file, err := os.Create("person.dat")6 if err != nil {7 fmt.Println("Error in creating file")8 }9 encoder := gob.NewEncoder(file)10 err = encoder.Encode(p)11 if err != nil {12 fmt.Println("Error in encoding")13 }14 file.Close()15}16import (17type Person struct {18}19func main() {20 file, err := os.Open("person.dat")21 if err != nil {22 fmt.Println("Error in opening file")23 }24 decoder := gob.NewDecoder(file)25 err = decoder.Decode(&p)26 if err != nil {27 fmt.Println("Error in decoding")28 }29 file.Close()30 fmt.Println("Name: ", p.Name)31 fmt.Println("Age: ", p.Age)32 fmt.Println("Address: ", p.Address)33}
Write
Using AI Code Generation
1import (2func main() {3 fmt.Println("Hello World")4 enc := codec.NewEncoderBytes(&b, &h)5 enc.Encode("Hello World")6 dec := codec.NewDecoderBytes(b, &w)7 dec.Decode(&s)8 fmt.Println(s)9}
Write
Using AI Code Generation
1func main() {2 fmt.Println("Hello World!")3 s := serializer.NewSerializer()4 w := serializer.NewWriter(s)5 w.Write("Hello World!")6}7func main() {8 fmt.Println("Hello World!")9 s := serializer.NewSerializer()10 w := serializer.NewWriter(s)11 w.Write("Hello World!")12 w.Write("Hello World!")13}14func main() {15 fmt.Println("Hello World!")16 s := serializer.NewSerializer()17 w := serializer.NewWriter(s)18 w.Write("Hello World!")19 w.Write("Hello World!")20 w.Write("Hello World!")21}22func main() {23 fmt.Println("Hello World!")24 s := serializer.NewSerializer()25 w := serializer.NewWriter(s)26 w.Write("Hello World!")
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!!