You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

670 lines
26 KiB

  1. /*
  2. Ginkgo is a BDD-style testing framework for Golang
  3. The godoc documentation describes Ginkgo's API. More comprehensive documentation (with examples!) is available at http://onsi.github.io/ginkgo/
  4. Ginkgo's preferred matcher library is [Gomega](http://github.com/onsi/gomega)
  5. Ginkgo on Github: http://github.com/onsi/ginkgo
  6. Ginkgo is MIT-Licensed
  7. */
  8. package ginkgo
  9. import (
  10. "flag"
  11. "fmt"
  12. "io"
  13. "net/http"
  14. "os"
  15. "reflect"
  16. "strings"
  17. "time"
  18. "github.com/onsi/ginkgo/config"
  19. "github.com/onsi/ginkgo/internal/codelocation"
  20. "github.com/onsi/ginkgo/internal/global"
  21. "github.com/onsi/ginkgo/internal/remote"
  22. "github.com/onsi/ginkgo/internal/testingtproxy"
  23. "github.com/onsi/ginkgo/internal/writer"
  24. "github.com/onsi/ginkgo/reporters"
  25. "github.com/onsi/ginkgo/reporters/stenographer"
  26. colorable "github.com/onsi/ginkgo/reporters/stenographer/support/go-colorable"
  27. "github.com/onsi/ginkgo/types"
  28. )
  29. var deprecationTracker = types.NewDeprecationTracker()
  30. const GINKGO_VERSION = config.VERSION
  31. const GINKGO_PANIC = `
  32. Your test failed.
  33. Ginkgo panics to prevent subsequent assertions from running.
  34. Normally Ginkgo rescues this panic so you shouldn't see it.
  35. But, if you make an assertion in a goroutine, Ginkgo can't capture the panic.
  36. To circumvent this, you should call
  37. defer GinkgoRecover()
  38. at the top of the goroutine that caused this panic.
  39. `
  40. func init() {
  41. config.Flags(flag.CommandLine, "ginkgo", true)
  42. GinkgoWriter = writer.New(os.Stdout)
  43. }
  44. //GinkgoWriter implements an io.Writer
  45. //When running in verbose mode any writes to GinkgoWriter will be immediately printed
  46. //to stdout. Otherwise, GinkgoWriter will buffer any writes produced during the current test and flush them to screen
  47. //only if the current test fails.
  48. var GinkgoWriter io.Writer
  49. //The interface by which Ginkgo receives *testing.T
  50. type GinkgoTestingT interface {
  51. Fail()
  52. }
  53. //GinkgoRandomSeed returns the seed used to randomize spec execution order. It is
  54. //useful for seeding your own pseudorandom number generators (PRNGs) to ensure
  55. //consistent executions from run to run, where your tests contain variability (for
  56. //example, when selecting random test data).
  57. func GinkgoRandomSeed() int64 {
  58. return config.GinkgoConfig.RandomSeed
  59. }
  60. //GinkgoParallelNode returns the parallel node number for the current ginkgo process
  61. //The node number is 1-indexed
  62. func GinkgoParallelNode() int {
  63. return config.GinkgoConfig.ParallelNode
  64. }
  65. //Some matcher libraries or legacy codebases require a *testing.T
  66. //GinkgoT implements an interface analogous to *testing.T and can be used if
  67. //the library in question accepts *testing.T through an interface
  68. //
  69. // For example, with testify:
  70. // assert.Equal(GinkgoT(), 123, 123, "they should be equal")
  71. //
  72. // Or with gomock:
  73. // gomock.NewController(GinkgoT())
  74. //
  75. // GinkgoT() takes an optional offset argument that can be used to get the
  76. // correct line number associated with the failure.
  77. func GinkgoT(optionalOffset ...int) GinkgoTInterface {
  78. offset := 3
  79. if len(optionalOffset) > 0 {
  80. offset = optionalOffset[0]
  81. }
  82. failedFunc := func() bool {
  83. return CurrentGinkgoTestDescription().Failed
  84. }
  85. nameFunc := func() string {
  86. return CurrentGinkgoTestDescription().FullTestText
  87. }
  88. return testingtproxy.New(GinkgoWriter, Fail, Skip, failedFunc, nameFunc, offset)
  89. }
  90. //The interface returned by GinkgoT(). This covers most of the methods
  91. //in the testing package's T.
  92. type GinkgoTInterface interface {
  93. Cleanup(func())
  94. Error(args ...interface{})
  95. Errorf(format string, args ...interface{})
  96. Fail()
  97. FailNow()
  98. Failed() bool
  99. Fatal(args ...interface{})
  100. Fatalf(format string, args ...interface{})
  101. Helper()
  102. Log(args ...interface{})
  103. Logf(format string, args ...interface{})
  104. Name() string
  105. Parallel()
  106. Skip(args ...interface{})
  107. SkipNow()
  108. Skipf(format string, args ...interface{})
  109. Skipped() bool
  110. TempDir() string
  111. }
  112. //Custom Ginkgo test reporters must implement the Reporter interface.
  113. //
  114. //The custom reporter is passed in a SuiteSummary when the suite begins and ends,
  115. //and a SpecSummary just before a spec begins and just after a spec ends
  116. type Reporter reporters.Reporter
  117. //Asynchronous specs are given a channel of the Done type. You must close or write to the channel
  118. //to tell Ginkgo that your async test is done.
  119. type Done chan<- interface{}
  120. //GinkgoTestDescription represents the information about the current running test returned by CurrentGinkgoTestDescription
  121. // FullTestText: a concatenation of ComponentTexts and the TestText
  122. // ComponentTexts: a list of all texts for the Describes & Contexts leading up to the current test
  123. // TestText: the text in the actual It or Measure node
  124. // IsMeasurement: true if the current test is a measurement
  125. // FileName: the name of the file containing the current test
  126. // LineNumber: the line number for the current test
  127. // Failed: if the current test has failed, this will be true (useful in an AfterEach)
  128. type GinkgoTestDescription struct {
  129. FullTestText string
  130. ComponentTexts []string
  131. TestText string
  132. IsMeasurement bool
  133. FileName string
  134. LineNumber int
  135. Failed bool
  136. Duration time.Duration
  137. }
  138. //CurrentGinkgoTestDescripton returns information about the current running test.
  139. func CurrentGinkgoTestDescription() GinkgoTestDescription {
  140. summary, ok := global.Suite.CurrentRunningSpecSummary()
  141. if !ok {
  142. return GinkgoTestDescription{}
  143. }
  144. subjectCodeLocation := summary.ComponentCodeLocations[len(summary.ComponentCodeLocations)-1]
  145. return GinkgoTestDescription{
  146. ComponentTexts: summary.ComponentTexts[1:],
  147. FullTestText: strings.Join(summary.ComponentTexts[1:], " "),
  148. TestText: summary.ComponentTexts[len(summary.ComponentTexts)-1],
  149. IsMeasurement: summary.IsMeasurement,
  150. FileName: subjectCodeLocation.FileName,
  151. LineNumber: subjectCodeLocation.LineNumber,
  152. Failed: summary.HasFailureState(),
  153. Duration: summary.RunTime,
  154. }
  155. }
  156. //Measurement tests receive a Benchmarker.
  157. //
  158. //You use the Time() function to time how long the passed in body function takes to run
  159. //You use the RecordValue() function to track arbitrary numerical measurements.
  160. //The RecordValueWithPrecision() function can be used alternatively to provide the unit
  161. //and resolution of the numeric measurement.
  162. //The optional info argument is passed to the test reporter and can be used to
  163. // provide the measurement data to a custom reporter with context.
  164. //
  165. //See http://onsi.github.io/ginkgo/#benchmark_tests for more details
  166. type Benchmarker interface {
  167. Time(name string, body func(), info ...interface{}) (elapsedTime time.Duration)
  168. RecordValue(name string, value float64, info ...interface{})
  169. RecordValueWithPrecision(name string, value float64, units string, precision int, info ...interface{})
  170. }
  171. //RunSpecs is the entry point for the Ginkgo test runner.
  172. //You must call this within a Golang testing TestX(t *testing.T) function.
  173. //
  174. //To bootstrap a test suite you can use the Ginkgo CLI:
  175. //
  176. // ginkgo bootstrap
  177. func RunSpecs(t GinkgoTestingT, description string) bool {
  178. specReporters := []Reporter{buildDefaultReporter()}
  179. if config.DefaultReporterConfig.ReportFile != "" {
  180. reportFile := config.DefaultReporterConfig.ReportFile
  181. specReporters[0] = reporters.NewJUnitReporter(reportFile)
  182. specReporters = append(specReporters, buildDefaultReporter())
  183. }
  184. return runSpecsWithCustomReporters(t, description, specReporters)
  185. }
  186. //To run your tests with Ginkgo's default reporter and your custom reporter(s), replace
  187. //RunSpecs() with this method.
  188. func RunSpecsWithDefaultAndCustomReporters(t GinkgoTestingT, description string, specReporters []Reporter) bool {
  189. deprecationTracker.TrackDeprecation(types.Deprecations.CustomReporter())
  190. specReporters = append(specReporters, buildDefaultReporter())
  191. return runSpecsWithCustomReporters(t, description, specReporters)
  192. }
  193. //To run your tests with your custom reporter(s) (and *not* Ginkgo's default reporter), replace
  194. //RunSpecs() with this method. Note that parallel tests will not work correctly without the default reporter
  195. func RunSpecsWithCustomReporters(t GinkgoTestingT, description string, specReporters []Reporter) bool {
  196. deprecationTracker.TrackDeprecation(types.Deprecations.CustomReporter())
  197. return runSpecsWithCustomReporters(t, description, specReporters)
  198. }
  199. func runSpecsWithCustomReporters(t GinkgoTestingT, description string, specReporters []Reporter) bool {
  200. writer := GinkgoWriter.(*writer.Writer)
  201. writer.SetStream(config.DefaultReporterConfig.Verbose)
  202. reporters := make([]reporters.Reporter, len(specReporters))
  203. for i, reporter := range specReporters {
  204. reporters[i] = reporter
  205. }
  206. passed, hasFocusedTests := global.Suite.Run(t, description, reporters, writer, config.GinkgoConfig)
  207. if deprecationTracker.DidTrackDeprecations() {
  208. fmt.Fprintln(colorable.NewColorableStderr(), deprecationTracker.DeprecationsReport())
  209. }
  210. if passed && hasFocusedTests && strings.TrimSpace(os.Getenv("GINKGO_EDITOR_INTEGRATION")) == "" {
  211. fmt.Println("PASS | FOCUSED")
  212. os.Exit(types.GINKGO_FOCUS_EXIT_CODE)
  213. }
  214. return passed
  215. }
  216. func buildDefaultReporter() Reporter {
  217. remoteReportingServer := config.GinkgoConfig.StreamHost
  218. if remoteReportingServer == "" {
  219. stenographer := stenographer.New(!config.DefaultReporterConfig.NoColor, config.GinkgoConfig.FlakeAttempts > 1, colorable.NewColorableStdout())
  220. return reporters.NewDefaultReporter(config.DefaultReporterConfig, stenographer)
  221. } else {
  222. debugFile := ""
  223. if config.GinkgoConfig.DebugParallel {
  224. debugFile = fmt.Sprintf("ginkgo-node-%d.log", config.GinkgoConfig.ParallelNode)
  225. }
  226. return remote.NewForwardingReporter(config.DefaultReporterConfig, remoteReportingServer, &http.Client{}, remote.NewOutputInterceptor(), GinkgoWriter.(*writer.Writer), debugFile)
  227. }
  228. }
  229. //Skip notifies Ginkgo that the current spec was skipped.
  230. func Skip(message string, callerSkip ...int) {
  231. skip := 0
  232. if len(callerSkip) > 0 {
  233. skip = callerSkip[0]
  234. }
  235. global.Failer.Skip(message, codelocation.New(skip+1))
  236. panic(GINKGO_PANIC)
  237. }
  238. //Fail notifies Ginkgo that the current spec has failed. (Gomega will call Fail for you automatically when an assertion fails.)
  239. func Fail(message string, callerSkip ...int) {
  240. skip := 0
  241. if len(callerSkip) > 0 {
  242. skip = callerSkip[0]
  243. }
  244. global.Failer.Fail(message, codelocation.New(skip+1))
  245. panic(GINKGO_PANIC)
  246. }
  247. //GinkgoRecover should be deferred at the top of any spawned goroutine that (may) call `Fail`
  248. //Since Gomega assertions call fail, you should throw a `defer GinkgoRecover()` at the top of any goroutine that
  249. //calls out to Gomega
  250. //
  251. //Here's why: Ginkgo's `Fail` method records the failure and then panics to prevent
  252. //further assertions from running. This panic must be recovered. Ginkgo does this for you
  253. //if the panic originates in a Ginkgo node (an It, BeforeEach, etc...)
  254. //
  255. //Unfortunately, if a panic originates on a goroutine *launched* from one of these nodes there's no
  256. //way for Ginkgo to rescue the panic. To do this, you must remember to `defer GinkgoRecover()` at the top of such a goroutine.
  257. func GinkgoRecover() {
  258. e := recover()
  259. if e != nil {
  260. global.Failer.Panic(codelocation.New(1), e)
  261. }
  262. }
  263. //Describe blocks allow you to organize your specs. A Describe block can contain any number of
  264. //BeforeEach, AfterEach, JustBeforeEach, It, and Measurement blocks.
  265. //
  266. //In addition you can nest Describe, Context and When blocks. Describe, Context and When blocks are functionally
  267. //equivalent. The difference is purely semantic -- you typically Describe the behavior of an object
  268. //or method and, within that Describe, outline a number of Contexts and Whens.
  269. func Describe(text string, body func()) bool {
  270. global.Suite.PushContainerNode(text, body, types.FlagTypeNone, codelocation.New(1))
  271. return true
  272. }
  273. //You can focus the tests within a describe block using FDescribe
  274. func FDescribe(text string, body func()) bool {
  275. global.Suite.PushContainerNode(text, body, types.FlagTypeFocused, codelocation.New(1))
  276. return true
  277. }
  278. //You can mark the tests within a describe block as pending using PDescribe
  279. func PDescribe(text string, body func()) bool {
  280. global.Suite.PushContainerNode(text, body, types.FlagTypePending, codelocation.New(1))
  281. return true
  282. }
  283. //You can mark the tests within a describe block as pending using XDescribe
  284. func XDescribe(text string, body func()) bool {
  285. global.Suite.PushContainerNode(text, body, types.FlagTypePending, codelocation.New(1))
  286. return true
  287. }
  288. //Context blocks allow you to organize your specs. A Context block can contain any number of
  289. //BeforeEach, AfterEach, JustBeforeEach, It, and Measurement blocks.
  290. //
  291. //In addition you can nest Describe, Context and When blocks. Describe, Context and When blocks are functionally
  292. //equivalent. The difference is purely semantic -- you typical Describe the behavior of an object
  293. //or method and, within that Describe, outline a number of Contexts and Whens.
  294. func Context(text string, body func()) bool {
  295. global.Suite.PushContainerNode(text, body, types.FlagTypeNone, codelocation.New(1))
  296. return true
  297. }
  298. //You can focus the tests within a describe block using FContext
  299. func FContext(text string, body func()) bool {
  300. global.Suite.PushContainerNode(text, body, types.FlagTypeFocused, codelocation.New(1))
  301. return true
  302. }
  303. //You can mark the tests within a describe block as pending using PContext
  304. func PContext(text string, body func()) bool {
  305. global.Suite.PushContainerNode(text, body, types.FlagTypePending, codelocation.New(1))
  306. return true
  307. }
  308. //You can mark the tests within a describe block as pending using XContext
  309. func XContext(text string, body func()) bool {
  310. global.Suite.PushContainerNode(text, body, types.FlagTypePending, codelocation.New(1))
  311. return true
  312. }
  313. //When blocks allow you to organize your specs. A When block can contain any number of
  314. //BeforeEach, AfterEach, JustBeforeEach, It, and Measurement blocks.
  315. //
  316. //In addition you can nest Describe, Context and When blocks. Describe, Context and When blocks are functionally
  317. //equivalent. The difference is purely semantic -- you typical Describe the behavior of an object
  318. //or method and, within that Describe, outline a number of Contexts and Whens.
  319. func When(text string, body func()) bool {
  320. global.Suite.PushContainerNode("when "+text, body, types.FlagTypeNone, codelocation.New(1))
  321. return true
  322. }
  323. //You can focus the tests within a describe block using FWhen
  324. func FWhen(text string, body func()) bool {
  325. global.Suite.PushContainerNode("when "+text, body, types.FlagTypeFocused, codelocation.New(1))
  326. return true
  327. }
  328. //You can mark the tests within a describe block as pending using PWhen
  329. func PWhen(text string, body func()) bool {
  330. global.Suite.PushContainerNode("when "+text, body, types.FlagTypePending, codelocation.New(1))
  331. return true
  332. }
  333. //You can mark the tests within a describe block as pending using XWhen
  334. func XWhen(text string, body func()) bool {
  335. global.Suite.PushContainerNode("when "+text, body, types.FlagTypePending, codelocation.New(1))
  336. return true
  337. }
  338. //It blocks contain your test code and assertions. You cannot nest any other Ginkgo blocks
  339. //within an It block.
  340. //
  341. //Ginkgo will normally run It blocks synchronously. To perform asynchronous tests, pass a
  342. //function that accepts a Done channel. When you do this, you can also provide an optional timeout.
  343. func It(text string, body interface{}, timeout ...float64) bool {
  344. validateBodyFunc(body, codelocation.New(1))
  345. global.Suite.PushItNode(text, body, types.FlagTypeNone, codelocation.New(1), parseTimeout(timeout...))
  346. return true
  347. }
  348. //You can focus individual Its using FIt
  349. func FIt(text string, body interface{}, timeout ...float64) bool {
  350. validateBodyFunc(body, codelocation.New(1))
  351. global.Suite.PushItNode(text, body, types.FlagTypeFocused, codelocation.New(1), parseTimeout(timeout...))
  352. return true
  353. }
  354. //You can mark Its as pending using PIt
  355. func PIt(text string, _ ...interface{}) bool {
  356. global.Suite.PushItNode(text, func() {}, types.FlagTypePending, codelocation.New(1), 0)
  357. return true
  358. }
  359. //You can mark Its as pending using XIt
  360. func XIt(text string, _ ...interface{}) bool {
  361. global.Suite.PushItNode(text, func() {}, types.FlagTypePending, codelocation.New(1), 0)
  362. return true
  363. }
  364. //Specify blocks are aliases for It blocks and allow for more natural wording in situations
  365. //which "It" does not fit into a natural sentence flow. All the same protocols apply for Specify blocks
  366. //which apply to It blocks.
  367. func Specify(text string, body interface{}, timeout ...float64) bool {
  368. validateBodyFunc(body, codelocation.New(1))
  369. global.Suite.PushItNode(text, body, types.FlagTypeNone, codelocation.New(1), parseTimeout(timeout...))
  370. return true
  371. }
  372. //You can focus individual Specifys using FSpecify
  373. func FSpecify(text string, body interface{}, timeout ...float64) bool {
  374. validateBodyFunc(body, codelocation.New(1))
  375. global.Suite.PushItNode(text, body, types.FlagTypeFocused, codelocation.New(1), parseTimeout(timeout...))
  376. return true
  377. }
  378. //You can mark Specifys as pending using PSpecify
  379. func PSpecify(text string, is ...interface{}) bool {
  380. global.Suite.PushItNode(text, func() {}, types.FlagTypePending, codelocation.New(1), 0)
  381. return true
  382. }
  383. //You can mark Specifys as pending using XSpecify
  384. func XSpecify(text string, is ...interface{}) bool {
  385. global.Suite.PushItNode(text, func() {}, types.FlagTypePending, codelocation.New(1), 0)
  386. return true
  387. }
  388. //By allows you to better document large Its.
  389. //
  390. //Generally you should try to keep your Its short and to the point. This is not always possible, however,
  391. //especially in the context of integration tests that capture a particular workflow.
  392. //
  393. //By allows you to document such flows. By must be called within a runnable node (It, BeforeEach, Measure, etc...)
  394. //By will simply log the passed in text to the GinkgoWriter. If By is handed a function it will immediately run the function.
  395. func By(text string, callbacks ...func()) {
  396. preamble := "\x1b[1mSTEP\x1b[0m"
  397. if config.DefaultReporterConfig.NoColor {
  398. preamble = "STEP"
  399. }
  400. fmt.Fprintln(GinkgoWriter, preamble+": "+text)
  401. if len(callbacks) == 1 {
  402. callbacks[0]()
  403. }
  404. if len(callbacks) > 1 {
  405. panic("just one callback per By, please")
  406. }
  407. }
  408. //Measure blocks run the passed in body function repeatedly (determined by the samples argument)
  409. //and accumulate metrics provided to the Benchmarker by the body function.
  410. //
  411. //The body function must have the signature:
  412. // func(b Benchmarker)
  413. func Measure(text string, body interface{}, samples int) bool {
  414. global.Suite.PushMeasureNode(text, body, types.FlagTypeNone, codelocation.New(1), samples)
  415. return true
  416. }
  417. //You can focus individual Measures using FMeasure
  418. func FMeasure(text string, body interface{}, samples int) bool {
  419. global.Suite.PushMeasureNode(text, body, types.FlagTypeFocused, codelocation.New(1), samples)
  420. return true
  421. }
  422. //You can mark Measurements as pending using PMeasure
  423. func PMeasure(text string, _ ...interface{}) bool {
  424. global.Suite.PushMeasureNode(text, func(b Benchmarker) {}, types.FlagTypePending, codelocation.New(1), 0)
  425. return true
  426. }
  427. //You can mark Measurements as pending using XMeasure
  428. func XMeasure(text string, _ ...interface{}) bool {
  429. global.Suite.PushMeasureNode(text, func(b Benchmarker) {}, types.FlagTypePending, codelocation.New(1), 0)
  430. return true
  431. }
  432. //BeforeSuite blocks are run just once before any specs are run. When running in parallel, each
  433. //parallel node process will call BeforeSuite.
  434. //
  435. //BeforeSuite blocks can be made asynchronous by providing a body function that accepts a Done channel
  436. //
  437. //You may only register *one* BeforeSuite handler per test suite. You typically do so in your bootstrap file at the top level.
  438. func BeforeSuite(body interface{}, timeout ...float64) bool {
  439. validateBodyFunc(body, codelocation.New(1))
  440. global.Suite.SetBeforeSuiteNode(body, codelocation.New(1), parseTimeout(timeout...))
  441. return true
  442. }
  443. //AfterSuite blocks are *always* run after all the specs regardless of whether specs have passed or failed.
  444. //Moreover, if Ginkgo receives an interrupt signal (^C) it will attempt to run the AfterSuite before exiting.
  445. //
  446. //When running in parallel, each parallel node process will call AfterSuite.
  447. //
  448. //AfterSuite blocks can be made asynchronous by providing a body function that accepts a Done channel
  449. //
  450. //You may only register *one* AfterSuite handler per test suite. You typically do so in your bootstrap file at the top level.
  451. func AfterSuite(body interface{}, timeout ...float64) bool {
  452. validateBodyFunc(body, codelocation.New(1))
  453. global.Suite.SetAfterSuiteNode(body, codelocation.New(1), parseTimeout(timeout...))
  454. return true
  455. }
  456. //SynchronizedBeforeSuite blocks are primarily meant to solve the problem of setting up singleton external resources shared across
  457. //nodes when running tests in parallel. For example, say you have a shared database that you can only start one instance of that
  458. //must be used in your tests. When running in parallel, only one node should set up the database and all other nodes should wait
  459. //until that node is done before running.
  460. //
  461. //SynchronizedBeforeSuite accomplishes this by taking *two* function arguments. The first is only run on parallel node #1. The second is
  462. //run on all nodes, but *only* after the first function completes successfully. Ginkgo also makes it possible to send data from the first function (on Node 1)
  463. //to the second function (on all the other nodes).
  464. //
  465. //The functions have the following signatures. The first function (which only runs on node 1) has the signature:
  466. //
  467. // func() []byte
  468. //
  469. //or, to run asynchronously:
  470. //
  471. // func(done Done) []byte
  472. //
  473. //The byte array returned by the first function is then passed to the second function, which has the signature:
  474. //
  475. // func(data []byte)
  476. //
  477. //or, to run asynchronously:
  478. //
  479. // func(data []byte, done Done)
  480. //
  481. //Here's a simple pseudo-code example that starts a shared database on Node 1 and shares the database's address with the other nodes:
  482. //
  483. // var dbClient db.Client
  484. // var dbRunner db.Runner
  485. //
  486. // var _ = SynchronizedBeforeSuite(func() []byte {
  487. // dbRunner = db.NewRunner()
  488. // err := dbRunner.Start()
  489. // Ω(err).ShouldNot(HaveOccurred())
  490. // return []byte(dbRunner.URL)
  491. // }, func(data []byte) {
  492. // dbClient = db.NewClient()
  493. // err := dbClient.Connect(string(data))
  494. // Ω(err).ShouldNot(HaveOccurred())
  495. // })
  496. func SynchronizedBeforeSuite(node1Body interface{}, allNodesBody interface{}, timeout ...float64) bool {
  497. global.Suite.SetSynchronizedBeforeSuiteNode(
  498. node1Body,
  499. allNodesBody,
  500. codelocation.New(1),
  501. parseTimeout(timeout...),
  502. )
  503. return true
  504. }
  505. //SynchronizedAfterSuite blocks complement the SynchronizedBeforeSuite blocks in solving the problem of setting up
  506. //external singleton resources shared across nodes when running tests in parallel.
  507. //
  508. //SynchronizedAfterSuite accomplishes this by taking *two* function arguments. The first runs on all nodes. The second runs only on parallel node #1
  509. //and *only* after all other nodes have finished and exited. This ensures that node 1, and any resources it is running, remain alive until
  510. //all other nodes are finished.
  511. //
  512. //Both functions have the same signature: either func() or func(done Done) to run asynchronously.
  513. //
  514. //Here's a pseudo-code example that complements that given in SynchronizedBeforeSuite. Here, SynchronizedAfterSuite is used to tear down the shared database
  515. //only after all nodes have finished:
  516. //
  517. // var _ = SynchronizedAfterSuite(func() {
  518. // dbClient.Cleanup()
  519. // }, func() {
  520. // dbRunner.Stop()
  521. // })
  522. func SynchronizedAfterSuite(allNodesBody interface{}, node1Body interface{}, timeout ...float64) bool {
  523. global.Suite.SetSynchronizedAfterSuiteNode(
  524. allNodesBody,
  525. node1Body,
  526. codelocation.New(1),
  527. parseTimeout(timeout...),
  528. )
  529. return true
  530. }
  531. //BeforeEach blocks are run before It blocks. When multiple BeforeEach blocks are defined in nested
  532. //Describe and Context blocks the outermost BeforeEach blocks are run first.
  533. //
  534. //Like It blocks, BeforeEach blocks can be made asynchronous by providing a body function that accepts
  535. //a Done channel
  536. func BeforeEach(body interface{}, timeout ...float64) bool {
  537. validateBodyFunc(body, codelocation.New(1))
  538. global.Suite.PushBeforeEachNode(body, codelocation.New(1), parseTimeout(timeout...))
  539. return true
  540. }
  541. //JustBeforeEach blocks are run before It blocks but *after* all BeforeEach blocks. For more details,
  542. //read the [documentation](http://onsi.github.io/ginkgo/#separating_creation_and_configuration_)
  543. //
  544. //Like It blocks, BeforeEach blocks can be made asynchronous by providing a body function that accepts
  545. //a Done channel
  546. func JustBeforeEach(body interface{}, timeout ...float64) bool {
  547. validateBodyFunc(body, codelocation.New(1))
  548. global.Suite.PushJustBeforeEachNode(body, codelocation.New(1), parseTimeout(timeout...))
  549. return true
  550. }
  551. //JustAfterEach blocks are run after It blocks but *before* all AfterEach blocks. For more details,
  552. //read the [documentation](http://onsi.github.io/ginkgo/#separating_creation_and_configuration_)
  553. //
  554. //Like It blocks, JustAfterEach blocks can be made asynchronous by providing a body function that accepts
  555. //a Done channel
  556. func JustAfterEach(body interface{}, timeout ...float64) bool {
  557. validateBodyFunc(body, codelocation.New(1))
  558. global.Suite.PushJustAfterEachNode(body, codelocation.New(1), parseTimeout(timeout...))
  559. return true
  560. }
  561. //AfterEach blocks are run after It blocks. When multiple AfterEach blocks are defined in nested
  562. //Describe and Context blocks the innermost AfterEach blocks are run first.
  563. //
  564. //Like It blocks, AfterEach blocks can be made asynchronous by providing a body function that accepts
  565. //a Done channel
  566. func AfterEach(body interface{}, timeout ...float64) bool {
  567. validateBodyFunc(body, codelocation.New(1))
  568. global.Suite.PushAfterEachNode(body, codelocation.New(1), parseTimeout(timeout...))
  569. return true
  570. }
  571. func validateBodyFunc(body interface{}, cl types.CodeLocation) {
  572. t := reflect.TypeOf(body)
  573. if t.Kind() != reflect.Func {
  574. return
  575. }
  576. if t.NumOut() > 0 {
  577. return
  578. }
  579. if t.NumIn() == 0 {
  580. return
  581. }
  582. if t.In(0) == reflect.TypeOf(make(Done)) {
  583. deprecationTracker.TrackDeprecation(types.Deprecations.Async(), cl)
  584. }
  585. }
  586. func parseTimeout(timeout ...float64) time.Duration {
  587. if len(timeout) == 0 {
  588. return global.DefaultTimeout
  589. } else {
  590. return time.Duration(timeout[0] * float64(time.Second))
  591. }
  592. }