Best Go-testdeep code snippet using ctxerr.String
kube_docker_client.go
Source:kube_docker_client.go
...229 var buf bytes.Buffer230 if err := json.NewEncoder(&buf).Encode(auth); err != nil {231 return "", err232 }233 return base64.URLEncoding.EncodeToString(buf.Bytes()), nil234}235// progress is a wrapper of dockermessage.JSONMessage with a lock protecting it.236type progress struct {237 sync.RWMutex238 // message stores the latest docker json message.239 message *dockermessage.JSONMessage240 // timestamp of the latest update.241 timestamp time.Time242}243func newProgress() *progress {244 return &progress{timestamp: time.Now()}245}246func (p *progress) set(msg *dockermessage.JSONMessage) {247 p.Lock()248 defer p.Unlock()249 p.message = msg250 p.timestamp = time.Now()251}252func (p *progress) get() (string, time.Time) {253 p.RLock()254 defer p.RUnlock()255 if p.message == nil {256 return "No progress", p.timestamp257 }258 // The following code is based on JSONMessage.Display259 var prefix string260 if p.message.ID != "" {261 prefix = fmt.Sprintf("%s: ", p.message.ID)262 }263 if p.message.Progress == nil {264 return fmt.Sprintf("%s%s", prefix, p.message.Status), p.timestamp265 }266 return fmt.Sprintf("%s%s %s", prefix, p.message.Status, p.message.Progress.String()), p.timestamp267}268// progressReporter keeps the newest image pulling progress and periodically report the newest progress.269type progressReporter struct {270 *progress271 image string272 cancel context.CancelFunc273 stopCh chan struct{}274 imagePullProgressDeadline time.Duration275}276// newProgressReporter creates a new progressReporter for specific image with specified reporting interval277func newProgressReporter(image string, cancel context.CancelFunc, imagePullProgressDeadline time.Duration) *progressReporter {278 return &progressReporter{279 progress: newProgress(),280 image: image,281 cancel: cancel,282 stopCh: make(chan struct{}),283 imagePullProgressDeadline: imagePullProgressDeadline,284 }285}286// start starts the progressReporter287func (p *progressReporter) start() {288 go func() {289 ticker := time.NewTicker(defaultImagePullingProgressReportInterval)290 defer ticker.Stop()291 for {292 // TODO(random-liu): Report as events.293 select {294 case <-ticker.C:295 progress, timestamp := p.progress.get()296 // If there is no progress for p.imagePullProgressDeadline, cancel the operation.297 if time.Since(timestamp) > p.imagePullProgressDeadline {298 klog.Errorf("Cancel pulling image %q because of no progress for %v, latest progress: %q", p.image, p.imagePullProgressDeadline, progress)299 p.cancel()300 return301 }302 klog.V(2).Infof("Pulling image %q: %q", p.image, progress)303 case <-p.stopCh:304 progress, _ := p.progress.get()305 klog.V(2).Infof("Stop pulling image %q: %q", p.image, progress)306 return307 }308 }309 }()310}311// stop stops the progressReporter312func (p *progressReporter) stop() {313 close(p.stopCh)314}315func (d *kubeDockerClient) PullImage(image string, auth dockertypes.AuthConfig, opts dockertypes.ImagePullOptions) error {316 // RegistryAuth is the base64 encoded credentials for the registry317 base64Auth, err := base64EncodeAuth(auth)318 if err != nil {319 return err320 }321 opts.RegistryAuth = base64Auth322 ctx, cancel := d.getCancelableContext()323 defer cancel()324 resp, err := d.client.ImagePull(ctx, image, opts)325 if err != nil {326 return err327 }328 defer resp.Close()329 reporter := newProgressReporter(image, cancel, d.imagePullProgressDeadline)330 reporter.start()331 defer reporter.stop()332 decoder := json.NewDecoder(resp)333 for {334 var msg dockermessage.JSONMessage335 err := decoder.Decode(&msg)336 if err == io.EOF {337 break338 }339 if err != nil {340 return err341 }342 if msg.Error != nil {343 return msg.Error344 }345 reporter.set(&msg)346 }347 return nil348}349func (d *kubeDockerClient) RemoveImage(image string, opts dockertypes.ImageRemoveOptions) ([]dockertypes.ImageDeleteResponseItem, error) {350 ctx, cancel := d.getTimeoutContext()351 defer cancel()352 resp, err := d.client.ImageRemove(ctx, image, opts)353 if ctxErr := contextError(ctx); ctxErr != nil {354 return nil, ctxErr355 }356 if dockerapi.IsErrNotFound(err) {357 return nil, ImageNotFoundError{ID: image}358 }359 return resp, err360}361func (d *kubeDockerClient) Logs(id string, opts dockertypes.ContainerLogsOptions, sopts StreamOptions) error {362 ctx, cancel := d.getCancelableContext()363 defer cancel()364 resp, err := d.client.ContainerLogs(ctx, id, opts)365 if ctxErr := contextError(ctx); ctxErr != nil {366 return ctxErr367 }368 if err != nil {369 return err370 }371 defer resp.Close()372 return d.redirectResponseToOutputStream(sopts.RawTerminal, sopts.OutputStream, sopts.ErrorStream, resp)373}374func (d *kubeDockerClient) Version() (*dockertypes.Version, error) {375 ctx, cancel := d.getTimeoutContext()376 defer cancel()377 resp, err := d.client.ServerVersion(ctx)378 if ctxErr := contextError(ctx); ctxErr != nil {379 return nil, ctxErr380 }381 if err != nil {382 return nil, err383 }384 return &resp, nil385}386func (d *kubeDockerClient) Info() (*dockertypes.Info, error) {387 ctx, cancel := d.getTimeoutContext()388 defer cancel()389 resp, err := d.client.Info(ctx)390 if ctxErr := contextError(ctx); ctxErr != nil {391 return nil, ctxErr392 }393 if err != nil {394 return nil, err395 }396 return &resp, nil397}398// TODO(random-liu): Add unit test for exec and attach functions, just like what go-dockerclient did.399func (d *kubeDockerClient) CreateExec(id string, opts dockertypes.ExecConfig) (*dockertypes.IDResponse, error) {400 ctx, cancel := d.getTimeoutContext()401 defer cancel()402 resp, err := d.client.ContainerExecCreate(ctx, id, opts)403 if ctxErr := contextError(ctx); ctxErr != nil {404 return nil, ctxErr405 }406 if err != nil {407 return nil, err408 }409 return &resp, nil410}411func (d *kubeDockerClient) StartExec(startExec string, opts dockertypes.ExecStartCheck, sopts StreamOptions) error {412 ctx, cancel := d.getCancelableContext()413 defer cancel()414 if opts.Detach {415 err := d.client.ContainerExecStart(ctx, startExec, opts)416 if ctxErr := contextError(ctx); ctxErr != nil {417 return ctxErr418 }419 return err420 }421 resp, err := d.client.ContainerExecAttach(ctx, startExec, dockertypes.ExecStartCheck{422 Detach: opts.Detach,423 Tty: opts.Tty,424 })425 if ctxErr := contextError(ctx); ctxErr != nil {426 return ctxErr427 }428 if err != nil {429 return err430 }431 defer resp.Close()432 if sopts.ExecStarted != nil {433 // Send a message to the channel indicating that the exec has started. This is needed so434 // interactive execs can handle resizing correctly - the request to resize the TTY has to happen435 // after the call to d.client.ContainerExecAttach, and because d.holdHijackedConnection below436 // blocks, we use sopts.ExecStarted to signal the caller that it's ok to resize.437 sopts.ExecStarted <- struct{}{}438 }439 return d.holdHijackedConnection(sopts.RawTerminal || opts.Tty, sopts.InputStream, sopts.OutputStream, sopts.ErrorStream, resp)440}441func (d *kubeDockerClient) InspectExec(id string) (*dockertypes.ContainerExecInspect, error) {442 ctx, cancel := d.getTimeoutContext()443 defer cancel()444 resp, err := d.client.ContainerExecInspect(ctx, id)445 if ctxErr := contextError(ctx); ctxErr != nil {446 return nil, ctxErr447 }448 if err != nil {449 return nil, err450 }451 return &resp, nil452}453func (d *kubeDockerClient) AttachToContainer(id string, opts dockertypes.ContainerAttachOptions, sopts StreamOptions) error {454 ctx, cancel := d.getCancelableContext()455 defer cancel()456 resp, err := d.client.ContainerAttach(ctx, id, opts)457 if ctxErr := contextError(ctx); ctxErr != nil {458 return ctxErr459 }460 if err != nil {461 return err462 }463 defer resp.Close()464 return d.holdHijackedConnection(sopts.RawTerminal, sopts.InputStream, sopts.OutputStream, sopts.ErrorStream, resp)465}466func (d *kubeDockerClient) ResizeExecTTY(id string, height, width uint) error {467 ctx, cancel := d.getCancelableContext()468 defer cancel()469 return d.client.ContainerExecResize(ctx, id, dockertypes.ResizeOptions{470 Height: height,471 Width: width,472 })473}474func (d *kubeDockerClient) ResizeContainerTTY(id string, height, width uint) error {475 ctx, cancel := d.getCancelableContext()476 defer cancel()477 return d.client.ContainerResize(ctx, id, dockertypes.ResizeOptions{478 Height: height,479 Width: width,480 })481}482// GetContainerStats is currently only used for Windows container stats483func (d *kubeDockerClient) GetContainerStats(id string) (*dockertypes.StatsJSON, error) {484 ctx, cancel := d.getCancelableContext()485 defer cancel()486 response, err := d.client.ContainerStats(ctx, id, false)487 if err != nil {488 return nil, err489 }490 dec := json.NewDecoder(response.Body)491 var stats dockertypes.StatsJSON492 err = dec.Decode(&stats)493 if err != nil {494 return nil, err495 }496 defer response.Body.Close()497 return &stats, nil498}499// redirectResponseToOutputStream redirect the response stream to stdout and stderr. When tty is true, all stream will500// only be redirected to stdout.501func (d *kubeDockerClient) redirectResponseToOutputStream(tty bool, outputStream, errorStream io.Writer, resp io.Reader) error {502 if outputStream == nil {503 outputStream = ioutil.Discard504 }505 if errorStream == nil {506 errorStream = ioutil.Discard507 }508 var err error509 if tty {510 _, err = io.Copy(outputStream, resp)511 } else {512 _, err = dockerstdcopy.StdCopy(outputStream, errorStream, resp)513 }514 return err515}516// holdHijackedConnection hold the HijackedResponse, redirect the inputStream to the connection, and redirect the response517// stream to stdout and stderr. NOTE: If needed, we could also add context in this function.518func (d *kubeDockerClient) holdHijackedConnection(tty bool, inputStream io.Reader, outputStream, errorStream io.Writer, resp dockertypes.HijackedResponse) error {519 receiveStdout := make(chan error)520 if outputStream != nil || errorStream != nil {521 go func() {522 receiveStdout <- d.redirectResponseToOutputStream(tty, outputStream, errorStream, resp.Reader)523 }()524 }525 stdinDone := make(chan struct{})526 go func() {527 if inputStream != nil {528 io.Copy(resp.Conn, inputStream)529 }530 resp.CloseWrite()531 close(stdinDone)532 }()533 select {534 case err := <-receiveStdout:535 return err536 case <-stdinDone:537 if outputStream != nil || errorStream != nil {538 return <-receiveStdout539 }540 }541 return nil542}543// getCancelableContext returns a new cancelable context. For long running requests without timeout, we use cancelable544// context to avoid potential resource leak, although the current implementation shouldn't leak resource.545func (d *kubeDockerClient) getCancelableContext() (context.Context, context.CancelFunc) {546 return context.WithCancel(context.Background())547}548// getTimeoutContext returns a new context with default request timeout549func (d *kubeDockerClient) getTimeoutContext() (context.Context, context.CancelFunc) {550 return context.WithTimeout(context.Background(), d.timeout)551}552// getCustomTimeoutContext returns a new context with a specific request timeout553func (d *kubeDockerClient) getCustomTimeoutContext(timeout time.Duration) (context.Context, context.CancelFunc) {554 // Pick the larger of the two555 if d.timeout > timeout {556 timeout = d.timeout557 }558 return context.WithTimeout(context.Background(), timeout)559}560// contextError checks the context, and returns error if the context is timeout.561func contextError(ctx context.Context) error {562 if ctx.Err() == context.DeadlineExceeded {563 return operationTimeout{err: ctx.Err()}564 }565 return ctx.Err()566}567// StreamOptions are the options used to configure the stream redirection568type StreamOptions struct {569 RawTerminal bool570 InputStream io.Reader571 OutputStream io.Writer572 ErrorStream io.Writer573 ExecStarted chan struct{}574}575// operationTimeout is the error returned when the docker operations are timeout.576type operationTimeout struct {577 err error578}579func (e operationTimeout) Error() string {580 return fmt.Sprintf("operation timeout: %v", e.err)581}582// containerNotFoundErrorRegx is the regexp of container not found error message.583var containerNotFoundErrorRegx = regexp.MustCompile(`No such container: [0-9a-z]+`)584// IsContainerNotFoundError checks whether the error is container not found error.585func IsContainerNotFoundError(err error) bool {586 return containerNotFoundErrorRegx.MatchString(err.Error())587}588// ImageNotFoundError is the error returned by InspectImage when image not found.589// Expose this to inject error in dockershim for testing.590type ImageNotFoundError struct {591 ID string592}593func (e ImageNotFoundError) Error() string {594 return fmt.Sprintf("no such image: %q", e.ID)595}596// IsImageNotFoundError checks whether the error is image not found error. This is exposed597// to share with dockershim.598func IsImageNotFoundError(err error) bool {599 _, ok := err.(ImageNotFoundError)600 return ok...
String
Using AI Code Generation
1import (2func main() {3 err := golerror.New("This is a new error")4 fmt.Println(err)5}6import (7func main() {8 err := golerror.New("This is a new error")9 fmt.Println(err)10 fmt.Println("Error: ", err.Error())11}12import (13func main() {14 err := golerror.New("This is a new error")15 fmt.Println("Error: ", err.Error())16}17import (18func main() {19 err := golerror.New("This is a new error")20 fmt.Println("Error: ", err.Error())21}22import (23func main() {24 err := golerror.New("
String
Using AI Code Generation
1import (2func main() {3 ctxerr := golctxerr.New("main", "main")4 fmt.Println(ctxerr.String())5}6import (7func main() {8 ctxerr := golctxerr.New("main", "main")9 fmt.Println(ctxerr.Error())10}11import (12func main() {13 ctxerr := golctxerr.New("main", "main")14 fmt.Println(ctxerr)15}16import (17func main() {18 ctxerr := golctxerr.New("main", "main")19 fmt.Println(ctxerr.Error())20}21import (22func main() {23 ctxerr := golctxerr.New("main", "main")24 fmt.Println(ctxerr)25}26import (27func main() {28 ctxerr := golctxerr.New("main", "main")29 fmt.Println(ctxerr.Error())30}31import (32func main() {33 ctxerr := golctxerr.New("main", "main")34 fmt.Println(ctxerr)35}36import (37func main() {38 ctxerr := golctxerr.New("main", "
String
Using AI Code Generation
1import (2func main() {3 err = ctxerr.New("error message", ctxerr.WithCode(500))4 fmt.Println(err)5}6error message (code: 500)7import (8func main() {9 err = ctxerr.New("error message", ctxerr.WithCode(500))10 fmt.Println(err)11 fmt.Println(ctxerr.StackTrace(err))12}13error message (code: 500)14import (15func main() {16 err = ctxerr.New("error message", ctxerr.WithCode(500))17 fmt.Println(err)18 fmt.Println(ctxerr.StackTrace(err))19 fmt.Println(ctxerr.StackTrace(err, ctxerr.WithContext("user", "alextanhongpin")))20}21error message (code: 500)
String
Using AI Code Generation
1import "fmt"2import "github.com/GoLangsam/ctxerr"3func main() {4 e = ctxerr.New("error string")5 fmt.Println(e)6}7import "fmt"8import "github.com/GoLangsam/ctxerr"9func main() {10 e = ctxerr.New("error string")11 fmt.Println(e)12 fmt.Println(e.Error())13}14import "fmt"15import "github.com/GoLangsam/ctxerr"16func main() {17 e = ctxerr.New("error string")18 fmt.Println(e)19 fmt.Println(e.Error())20 fmt.Println(e.String())21}22import "fmt"23import "github.com/GoLangsam/ctxerr"24func main() {25 e = ctxerr.New("error string")26 fmt.Println(e)27 fmt.Println(e.Error())28 fmt.Println(e.String())29 fmt.Println(e)30}31import "fmt"32import "github.com/GoLangsam/ctxerr"33func main() {34 e = ctxerr.New("error string")35 fmt.Println(e)36 fmt.Println(e.Error())37 fmt.Println(e.String())38 fmt.Println(e)39 fmt.Println(e.Error())40}41import "fmt"42import "github.com/GoLangsam/ctxerr"43func main() {
String
Using AI Code Generation
1import (2func main() {3 err := ctxerr.New("context error")4 fmt.Println(err)5}6import (7func main() {8 err := ctxerr.New("context error")9 err = ctxerr.Wrap(err, os.Open("file.txt"))10 fmt.Println(err)11}12import (13func main() {14 err := ctxerr.New("context error")15 err = ctxerr.Wrap(err, os.Open("file.txt"))16 fmt.Println(err)17 fmt.Println(err.Details())18}19import (20func main() {21 err := ctxerr.New("context error")22 err = ctxerr.Wrap(err,
String
Using AI Code Generation
1import (2func main() {3 err := ctxerr.New("error message")4 fmt.Println(err)5}6import (7func main() {8 err := ctxerr.New("error message")9 err = ctxerr.Wrap(err, "context message")10 fmt.Println(err)11 fmt.Println(os.IsExist(err))12}13import (14func main() {15 err := ctxerr.New("error message")16 err = ctxerr.Wrapf(err, "context message: %s", "error message")17 fmt.Println(err)18 fmt.Println(os.IsExist(err))19}
String
Using AI Code Generation
1import "fmt"2import "github.com/rajdeepd/ctxerr"3func main() {4 err := ctxerr.New("Error occured")5 fmt.Println(err)6}7Error()8Error()9Error()10Error()11Error()
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!!