run_example.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. // Copyright 2019 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. //go:build !js
  5. // TODO(@musiol, @odeke-em): re-unify this entire file back into
  6. // example.go when js/wasm gets an os.Pipe implementation
  7. // and no longer needs this separation.
  8. package testing
  9. import (
  10. "fmt"
  11. "io"
  12. "os"
  13. "strings"
  14. "time"
  15. )
  16. func runExample(eg InternalExample) (ok bool) {
  17. if *chatty {
  18. fmt.Printf("=== RUN %s\n", eg.Name)
  19. }
  20. // Capture stdout.
  21. stdout := os.Stdout
  22. r, w, err := os.Pipe()
  23. if err != nil {
  24. fmt.Fprintln(os.Stderr, err)
  25. os.Exit(1)
  26. }
  27. os.Stdout = w
  28. outC := make(chan string)
  29. go func() {
  30. var buf strings.Builder
  31. _, err := io.Copy(&buf, r)
  32. r.Close()
  33. if err != nil {
  34. fmt.Fprintf(os.Stderr, "testing: copying pipe: %v\n", err)
  35. os.Exit(1)
  36. }
  37. outC <- buf.String()
  38. }()
  39. finished := false
  40. start := time.Now()
  41. // Clean up in a deferred call so we can recover if the example panics.
  42. defer func() {
  43. timeSpent := time.Since(start)
  44. // Close pipe, restore stdout, get output.
  45. w.Close()
  46. os.Stdout = stdout
  47. out := <-outC
  48. err := recover()
  49. ok = eg.processRunResult(out, timeSpent, finished, err)
  50. }()
  51. // Run example.
  52. eg.F()
  53. finished = true
  54. return
  55. }