ginkgo_dsl.go 24 KB

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