ginkgo_dsl.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610
  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. return RunSpecsWithCustomReporters(t, description, specReporters)
  174. }
  175. //To run your tests with Ginkgo's default reporter and your custom reporter(s), replace
  176. //RunSpecs() with this method.
  177. func RunSpecsWithDefaultAndCustomReporters(t GinkgoTestingT, description string, specReporters []Reporter) bool {
  178. specReporters = append(specReporters, buildDefaultReporter())
  179. return RunSpecsWithCustomReporters(t, description, specReporters)
  180. }
  181. //To run your tests with your custom reporter(s) (and *not* Ginkgo's default reporter), replace
  182. //RunSpecs() with this method. Note that parallel tests will not work correctly without the default reporter
  183. func RunSpecsWithCustomReporters(t GinkgoTestingT, description string, specReporters []Reporter) bool {
  184. writer := GinkgoWriter.(*writer.Writer)
  185. writer.SetStream(config.DefaultReporterConfig.Verbose)
  186. reporters := make([]reporters.Reporter, len(specReporters))
  187. for i, reporter := range specReporters {
  188. reporters[i] = reporter
  189. }
  190. passed, hasFocusedTests := globalSuite.Run(t, description, reporters, writer, config.GinkgoConfig)
  191. if passed && hasFocusedTests && strings.TrimSpace(os.Getenv("GINKGO_EDITOR_INTEGRATION")) == "" {
  192. fmt.Println("PASS | FOCUSED")
  193. os.Exit(types.GINKGO_FOCUS_EXIT_CODE)
  194. }
  195. return passed
  196. }
  197. func buildDefaultReporter() Reporter {
  198. remoteReportingServer := config.GinkgoConfig.StreamHost
  199. if remoteReportingServer == "" {
  200. stenographer := stenographer.New(!config.DefaultReporterConfig.NoColor, config.GinkgoConfig.FlakeAttempts > 1, colorable.NewColorableStdout())
  201. return reporters.NewDefaultReporter(config.DefaultReporterConfig, stenographer)
  202. } else {
  203. debugFile := ""
  204. if config.GinkgoConfig.DebugParallel {
  205. debugFile = fmt.Sprintf("ginkgo-node-%d.log", config.GinkgoConfig.ParallelNode)
  206. }
  207. return remote.NewForwardingReporter(config.DefaultReporterConfig, remoteReportingServer, &http.Client{}, remote.NewOutputInterceptor(), GinkgoWriter.(*writer.Writer), debugFile)
  208. }
  209. }
  210. //Skip notifies Ginkgo that the current spec was skipped.
  211. func Skip(message string, callerSkip ...int) {
  212. skip := 0
  213. if len(callerSkip) > 0 {
  214. skip = callerSkip[0]
  215. }
  216. globalFailer.Skip(message, codelocation.New(skip+1))
  217. panic(GINKGO_PANIC)
  218. }
  219. //Fail notifies Ginkgo that the current spec has failed. (Gomega will call Fail for you automatically when an assertion fails.)
  220. func Fail(message string, callerSkip ...int) {
  221. skip := 0
  222. if len(callerSkip) > 0 {
  223. skip = callerSkip[0]
  224. }
  225. globalFailer.Fail(message, codelocation.New(skip+1))
  226. panic(GINKGO_PANIC)
  227. }
  228. //GinkgoRecover should be deferred at the top of any spawned goroutine that (may) call `Fail`
  229. //Since Gomega assertions call fail, you should throw a `defer GinkgoRecover()` at the top of any goroutine that
  230. //calls out to Gomega
  231. //
  232. //Here's why: Ginkgo's `Fail` method records the failure and then panics to prevent
  233. //further assertions from running. This panic must be recovered. Ginkgo does this for you
  234. //if the panic originates in a Ginkgo node (an It, BeforeEach, etc...)
  235. //
  236. //Unfortunately, if a panic originates on a goroutine *launched* from one of these nodes there's no
  237. //way for Ginkgo to rescue the panic. To do this, you must remember to `defer GinkgoRecover()` at the top of such a goroutine.
  238. func GinkgoRecover() {
  239. e := recover()
  240. if e != nil {
  241. globalFailer.Panic(codelocation.New(1), e)
  242. }
  243. }
  244. //Describe blocks allow you to organize your specs. A Describe block can contain any number of
  245. //BeforeEach, AfterEach, JustBeforeEach, It, and Measurement blocks.
  246. //
  247. //In addition you can nest Describe, Context and When blocks. Describe, Context and When blocks are functionally
  248. //equivalent. The difference is purely semantic -- you typical Describe the behavior of an object
  249. //or method and, within that Describe, outline a number of Contexts and Whens.
  250. func Describe(text string, body func()) bool {
  251. globalSuite.PushContainerNode(text, body, types.FlagTypeNone, codelocation.New(1))
  252. return true
  253. }
  254. //You can focus the tests within a describe block using FDescribe
  255. func FDescribe(text string, body func()) bool {
  256. globalSuite.PushContainerNode(text, body, types.FlagTypeFocused, codelocation.New(1))
  257. return true
  258. }
  259. //You can mark the tests within a describe block as pending using PDescribe
  260. func PDescribe(text string, body func()) bool {
  261. globalSuite.PushContainerNode(text, body, types.FlagTypePending, codelocation.New(1))
  262. return true
  263. }
  264. //You can mark the tests within a describe block as pending using XDescribe
  265. func XDescribe(text string, body func()) bool {
  266. globalSuite.PushContainerNode(text, body, types.FlagTypePending, codelocation.New(1))
  267. return true
  268. }
  269. //Context blocks allow you to organize your specs. A Context block can contain any number of
  270. //BeforeEach, AfterEach, JustBeforeEach, It, and Measurement blocks.
  271. //
  272. //In addition you can nest Describe, Context and When blocks. Describe, Context and When blocks are functionally
  273. //equivalent. The difference is purely semantic -- you typical Describe the behavior of an object
  274. //or method and, within that Describe, outline a number of Contexts and Whens.
  275. func Context(text string, body func()) bool {
  276. globalSuite.PushContainerNode(text, body, types.FlagTypeNone, codelocation.New(1))
  277. return true
  278. }
  279. //You can focus the tests within a describe block using FContext
  280. func FContext(text string, body func()) bool {
  281. globalSuite.PushContainerNode(text, body, types.FlagTypeFocused, codelocation.New(1))
  282. return true
  283. }
  284. //You can mark the tests within a describe block as pending using PContext
  285. func PContext(text string, body func()) bool {
  286. globalSuite.PushContainerNode(text, body, types.FlagTypePending, codelocation.New(1))
  287. return true
  288. }
  289. //You can mark the tests within a describe block as pending using XContext
  290. func XContext(text string, body func()) bool {
  291. globalSuite.PushContainerNode(text, body, types.FlagTypePending, codelocation.New(1))
  292. return true
  293. }
  294. //When blocks allow you to organize your specs. A When block can contain any number of
  295. //BeforeEach, AfterEach, JustBeforeEach, It, and Measurement blocks.
  296. //
  297. //In addition you can nest Describe, Context and When blocks. Describe, Context and When blocks are functionally
  298. //equivalent. The difference is purely semantic -- you typical Describe the behavior of an object
  299. //or method and, within that Describe, outline a number of Contexts and Whens.
  300. func When(text string, body func()) bool {
  301. globalSuite.PushContainerNode("when "+text, body, types.FlagTypeNone, codelocation.New(1))
  302. return true
  303. }
  304. //You can focus the tests within a describe block using FWhen
  305. func FWhen(text string, body func()) bool {
  306. globalSuite.PushContainerNode("when "+text, body, types.FlagTypeFocused, codelocation.New(1))
  307. return true
  308. }
  309. //You can mark the tests within a describe block as pending using PWhen
  310. func PWhen(text string, body func()) bool {
  311. globalSuite.PushContainerNode("when "+text, body, types.FlagTypePending, codelocation.New(1))
  312. return true
  313. }
  314. //You can mark the tests within a describe block as pending using XWhen
  315. func XWhen(text string, body func()) bool {
  316. globalSuite.PushContainerNode("when "+text, body, types.FlagTypePending, codelocation.New(1))
  317. return true
  318. }
  319. //It blocks contain your test code and assertions. You cannot nest any other Ginkgo blocks
  320. //within an It block.
  321. //
  322. //Ginkgo will normally run It blocks synchronously. To perform asynchronous tests, pass a
  323. //function that accepts a Done channel. When you do this, you can also provide an optional timeout.
  324. func It(text string, body interface{}, timeout ...float64) bool {
  325. globalSuite.PushItNode(text, body, types.FlagTypeNone, codelocation.New(1), parseTimeout(timeout...))
  326. return true
  327. }
  328. //You can focus individual Its using FIt
  329. func FIt(text string, body interface{}, timeout ...float64) bool {
  330. globalSuite.PushItNode(text, body, types.FlagTypeFocused, codelocation.New(1), parseTimeout(timeout...))
  331. return true
  332. }
  333. //You can mark Its as pending using PIt
  334. func PIt(text string, _ ...interface{}) bool {
  335. globalSuite.PushItNode(text, func() {}, types.FlagTypePending, codelocation.New(1), 0)
  336. return true
  337. }
  338. //You can mark Its as pending using XIt
  339. func XIt(text string, _ ...interface{}) bool {
  340. globalSuite.PushItNode(text, func() {}, types.FlagTypePending, codelocation.New(1), 0)
  341. return true
  342. }
  343. //Specify blocks are aliases for It blocks and allow for more natural wording in situations
  344. //which "It" does not fit into a natural sentence flow. All the same protocols apply for Specify blocks
  345. //which apply to It blocks.
  346. func Specify(text string, body interface{}, timeout ...float64) bool {
  347. globalSuite.PushItNode(text, body, types.FlagTypeNone, codelocation.New(1), parseTimeout(timeout...))
  348. return true
  349. }
  350. //You can focus individual Specifys using FSpecify
  351. func FSpecify(text string, body interface{}, timeout ...float64) bool {
  352. globalSuite.PushItNode(text, body, types.FlagTypeFocused, codelocation.New(1), parseTimeout(timeout...))
  353. return true
  354. }
  355. //You can mark Specifys as pending using PSpecify
  356. func PSpecify(text string, is ...interface{}) bool {
  357. globalSuite.PushItNode(text, func() {}, types.FlagTypePending, codelocation.New(1), 0)
  358. return true
  359. }
  360. //You can mark Specifys as pending using XSpecify
  361. func XSpecify(text string, is ...interface{}) bool {
  362. globalSuite.PushItNode(text, func() {}, types.FlagTypePending, codelocation.New(1), 0)
  363. return true
  364. }
  365. //By allows you to better document large Its.
  366. //
  367. //Generally you should try to keep your Its short and to the point. This is not always possible, however,
  368. //especially in the context of integration tests that capture a particular workflow.
  369. //
  370. //By allows you to document such flows. By must be called within a runnable node (It, BeforeEach, Measure, etc...)
  371. //By will simply log the passed in text to the GinkgoWriter. If By is handed a function it will immediately run the function.
  372. func By(text string, callbacks ...func()) {
  373. preamble := "\x1b[1mSTEP\x1b[0m"
  374. if config.DefaultReporterConfig.NoColor {
  375. preamble = "STEP"
  376. }
  377. fmt.Fprintln(GinkgoWriter, preamble+": "+text)
  378. if len(callbacks) == 1 {
  379. callbacks[0]()
  380. }
  381. if len(callbacks) > 1 {
  382. panic("just one callback per By, please")
  383. }
  384. }
  385. //Measure blocks run the passed in body function repeatedly (determined by the samples argument)
  386. //and accumulate metrics provided to the Benchmarker by the body function.
  387. //
  388. //The body function must have the signature:
  389. // func(b Benchmarker)
  390. func Measure(text string, body interface{}, samples int) bool {
  391. globalSuite.PushMeasureNode(text, body, types.FlagTypeNone, codelocation.New(1), samples)
  392. return true
  393. }
  394. //You can focus individual Measures using FMeasure
  395. func FMeasure(text string, body interface{}, samples int) bool {
  396. globalSuite.PushMeasureNode(text, body, types.FlagTypeFocused, codelocation.New(1), samples)
  397. return true
  398. }
  399. //You can mark Maeasurements as pending using PMeasure
  400. func PMeasure(text string, _ ...interface{}) bool {
  401. globalSuite.PushMeasureNode(text, func(b Benchmarker) {}, types.FlagTypePending, codelocation.New(1), 0)
  402. return true
  403. }
  404. //You can mark Maeasurements as pending using XMeasure
  405. func XMeasure(text string, _ ...interface{}) bool {
  406. globalSuite.PushMeasureNode(text, func(b Benchmarker) {}, types.FlagTypePending, codelocation.New(1), 0)
  407. return true
  408. }
  409. //BeforeSuite blocks are run just once before any specs are run. When running in parallel, each
  410. //parallel node process will call BeforeSuite.
  411. //
  412. //BeforeSuite blocks can be made asynchronous by providing a body function that accepts a Done channel
  413. //
  414. //You may only register *one* BeforeSuite handler per test suite. You typically do so in your bootstrap file at the top level.
  415. func BeforeSuite(body interface{}, timeout ...float64) bool {
  416. globalSuite.SetBeforeSuiteNode(body, codelocation.New(1), parseTimeout(timeout...))
  417. return true
  418. }
  419. //AfterSuite blocks are *always* run after all the specs regardless of whether specs have passed or failed.
  420. //Moreover, if Ginkgo receives an interrupt signal (^C) it will attempt to run the AfterSuite before exiting.
  421. //
  422. //When running in parallel, each parallel node process will call AfterSuite.
  423. //
  424. //AfterSuite blocks can be made asynchronous by providing a body function that accepts a Done channel
  425. //
  426. //You may only register *one* AfterSuite handler per test suite. You typically do so in your bootstrap file at the top level.
  427. func AfterSuite(body interface{}, timeout ...float64) bool {
  428. globalSuite.SetAfterSuiteNode(body, codelocation.New(1), parseTimeout(timeout...))
  429. return true
  430. }
  431. //SynchronizedBeforeSuite blocks are primarily meant to solve the problem of setting up singleton external resources shared across
  432. //nodes when running tests in parallel. For example, say you have a shared database that you can only start one instance of that
  433. //must be used in your tests. When running in parallel, only one node should set up the database and all other nodes should wait
  434. //until that node is done before running.
  435. //
  436. //SynchronizedBeforeSuite accomplishes this by taking *two* function arguments. The first is only run on parallel node #1. The second is
  437. //run on all nodes, but *only* after the first function completes succesfully. Ginkgo also makes it possible to send data from the first function (on Node 1)
  438. //to the second function (on all the other nodes).
  439. //
  440. //The functions have the following signatures. The first function (which only runs on node 1) has the signature:
  441. //
  442. // func() []byte
  443. //
  444. //or, to run asynchronously:
  445. //
  446. // func(done Done) []byte
  447. //
  448. //The byte array returned by the first function is then passed to the second function, which has the signature:
  449. //
  450. // func(data []byte)
  451. //
  452. //or, to run asynchronously:
  453. //
  454. // func(data []byte, done Done)
  455. //
  456. //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:
  457. //
  458. // var dbClient db.Client
  459. // var dbRunner db.Runner
  460. //
  461. // var _ = SynchronizedBeforeSuite(func() []byte {
  462. // dbRunner = db.NewRunner()
  463. // err := dbRunner.Start()
  464. // Ω(err).ShouldNot(HaveOccurred())
  465. // return []byte(dbRunner.URL)
  466. // }, func(data []byte) {
  467. // dbClient = db.NewClient()
  468. // err := dbClient.Connect(string(data))
  469. // Ω(err).ShouldNot(HaveOccurred())
  470. // })
  471. func SynchronizedBeforeSuite(node1Body interface{}, allNodesBody interface{}, timeout ...float64) bool {
  472. globalSuite.SetSynchronizedBeforeSuiteNode(
  473. node1Body,
  474. allNodesBody,
  475. codelocation.New(1),
  476. parseTimeout(timeout...),
  477. )
  478. return true
  479. }
  480. //SynchronizedAfterSuite blocks complement the SynchronizedBeforeSuite blocks in solving the problem of setting up
  481. //external singleton resources shared across nodes when running tests in parallel.
  482. //
  483. //SynchronizedAfterSuite accomplishes this by taking *two* function arguments. The first runs on all nodes. The second runs only on parallel node #1
  484. //and *only* after all other nodes have finished and exited. This ensures that node 1, and any resources it is running, remain alive until
  485. //all other nodes are finished.
  486. //
  487. //Both functions have the same signature: either func() or func(done Done) to run asynchronously.
  488. //
  489. //Here's a pseudo-code example that complements that given in SynchronizedBeforeSuite. Here, SynchronizedAfterSuite is used to tear down the shared database
  490. //only after all nodes have finished:
  491. //
  492. // var _ = SynchronizedAfterSuite(func() {
  493. // dbClient.Cleanup()
  494. // }, func() {
  495. // dbRunner.Stop()
  496. // })
  497. func SynchronizedAfterSuite(allNodesBody interface{}, node1Body interface{}, timeout ...float64) bool {
  498. globalSuite.SetSynchronizedAfterSuiteNode(
  499. allNodesBody,
  500. node1Body,
  501. codelocation.New(1),
  502. parseTimeout(timeout...),
  503. )
  504. return true
  505. }
  506. //BeforeEach blocks are run before It blocks. When multiple BeforeEach blocks are defined in nested
  507. //Describe and Context blocks the outermost BeforeEach blocks are run first.
  508. //
  509. //Like It blocks, BeforeEach blocks can be made asynchronous by providing a body function that accepts
  510. //a Done channel
  511. func BeforeEach(body interface{}, timeout ...float64) bool {
  512. globalSuite.PushBeforeEachNode(body, codelocation.New(1), parseTimeout(timeout...))
  513. return true
  514. }
  515. //JustBeforeEach blocks are run before It blocks but *after* all BeforeEach blocks. For more details,
  516. //read the [documentation](http://onsi.github.io/ginkgo/#separating_creation_and_configuration_)
  517. //
  518. //Like It blocks, BeforeEach blocks can be made asynchronous by providing a body function that accepts
  519. //a Done channel
  520. func JustBeforeEach(body interface{}, timeout ...float64) bool {
  521. globalSuite.PushJustBeforeEachNode(body, codelocation.New(1), parseTimeout(timeout...))
  522. return true
  523. }
  524. //AfterEach blocks are run after It blocks. When multiple AfterEach blocks are defined in nested
  525. //Describe and Context blocks the innermost AfterEach blocks are run first.
  526. //
  527. //Like It blocks, AfterEach blocks can be made asynchronous by providing a body function that accepts
  528. //a Done channel
  529. func AfterEach(body interface{}, timeout ...float64) bool {
  530. globalSuite.PushAfterEachNode(body, codelocation.New(1), parseTimeout(timeout...))
  531. return true
  532. }
  533. func parseTimeout(timeout ...float64) time.Duration {
  534. if len(timeout) == 0 {
  535. return time.Duration(defaultTimeout * int64(time.Second))
  536. } else {
  537. return time.Duration(timeout[0] * float64(time.Second))
  538. }
  539. }