How to use exitIfErr method of ginkgo Package

Best Ginkgo code snippet using ginkgo.exitIfErr

core_dsl.go

Source:core_dsl.go Github

copy

Full Screen

...36var client parallel_support.Client37func init() {38 var err error39 flagSet, err = types.BuildTestSuiteFlagSet(&suiteConfig, &reporterConfig)40 exitIfErr(err)41 GinkgoWriter = internal.NewWriter(os.Stdout)42}43func exitIfErr(err error) {44 if err != nil {45 if outputInterceptor != nil {46 outputInterceptor.Shutdown()47 }48 if client != nil {49 client.Close()50 }51 fmt.Fprintln(formatter.ColorableStdErr, err.Error())52 os.Exit(1)53 }54}55func exitIfErrors(errors []error) {56 if len(errors) > 0 {57 if outputInterceptor != nil {58 outputInterceptor.Shutdown()59 }60 if client != nil {61 client.Close()62 }63 for _, err := range errors {64 fmt.Fprintln(formatter.ColorableStdErr, err.Error())65 }66 os.Exit(1)67 }68}69//The interface implemented by GinkgoWriter70type GinkgoWriterInterface interface {71 io.Writer72 Print(a ...interface{})73 Printf(format string, a ...interface{})74 Println(a ...interface{})75 TeeTo(writer io.Writer)76 ClearTeeWriters()77}78/*79GinkgoWriter implements a GinkgoWriterInterface and io.Writer80When running in verbose mode (ginkgo -v) any writes to GinkgoWriter will be immediately printed81to stdout. Otherwise, GinkgoWriter will buffer any writes produced during the current test and flush them to screen82only if the current test fails.83GinkgoWriter also provides convenience Print, Printf and Println methods and allows you to tee to a custom writer via GinkgoWriter.TeeTo(writer).84Writes to GinkgoWriter are immediately sent to any registered TeeTo() writers. You can unregister all TeeTo() Writers with GinkgoWriter.ClearTeeWriters()85You can learn more at https://onsi.github.io/ginkgo/#logging-output86*/87var GinkgoWriter GinkgoWriterInterface88//The interface by which Ginkgo receives *testing.T89type GinkgoTestingT interface {90 Fail()91}92/*93GinkgoConfiguration returns the configuration of the current suite.94The first return value is the SuiteConfig which controls aspects of how the suite runs,95the second return value is the ReporterConfig which controls aspects of how Ginkgo's default96reporter emits output.97Mutating the returned configurations has no effect. To reconfigure Ginkgo programmatically you need98to pass in your mutated copies into RunSpecs().99You can learn more at https://onsi.github.io/ginkgo/#overriding-ginkgos-command-line-configuration-in-the-suite100*/101func GinkgoConfiguration() (types.SuiteConfig, types.ReporterConfig) {102 return suiteConfig, reporterConfig103}104/*105GinkgoRandomSeed returns the seed used to randomize spec execution order. It is106useful for seeding your own pseudorandom number generators to ensure107consistent executions from run to run, where your tests contain variability (for108example, when selecting random spec data).109You can learn more at https://onsi.github.io/ginkgo/#spec-randomization110*/111func GinkgoRandomSeed() int64 {112 return suiteConfig.RandomSeed113}114/*115GinkgoParallelProcess returns the parallel process number for the current ginkgo process116The process number is 1-indexed. You can use GinkgoParallelProcess() to shard access to shared117resources across your suites. You can learn more about patterns for sharding at https://onsi.github.io/ginkgo/#patterns-for-parallel-integration-specs118For more on how specs are parallelized in Ginkgo, see http://onsi.github.io/ginkgo/#spec-parallelization119*/120func GinkgoParallelProcess() int {121 return suiteConfig.ParallelProcess122}123/*124PauseOutputInterception() pauses Ginkgo's output interception. This is only relevant125when running in parallel and output to stdout/stderr is being intercepted. You generally126don't need to call this function - however there are cases when Ginkgo's output interception127mechanisms can interfere with external processes launched by the test process.128In particular, if an external process is launched that has cmd.Stdout/cmd.Stderr set to os.Stdout/os.Stderr129then Ginkgo's output interceptor will hang. To circumvent this, set cmd.Stdout/cmd.Stderr to GinkgoWriter.130If, for some reason, you aren't able to do that, you can PauseOutputInterception() before starting the process131then ResumeOutputInterception() after starting it.132Note that PauseOutputInterception() does not cause stdout writes to print to the console -133this simply stops intercepting and storing stdout writes to an internal buffer.134*/135func PauseOutputInterception() {136 if outputInterceptor == nil {137 return138 }139 outputInterceptor.PauseIntercepting()140}141//ResumeOutputInterception() - see docs for PauseOutputInterception()142func ResumeOutputInterception() {143 if outputInterceptor == nil {144 return145 }146 outputInterceptor.ResumeIntercepting()147}148/*149RunSpecs is the entry point for the Ginkgo spec runner.150You must call this within a Golang testing TestX(t *testing.T) function.151If you bootstrapped your suite with "ginkgo bootstrap" this is already152done for you.153Ginkgo is typically configured via command-line flags. This configuration154can be overridden, however, and passed into RunSpecs as optional arguments:155 func TestMySuite(t *testing.T) {156 RegisterFailHandler(gomega.Fail)157 // fetch the current config158 suiteConfig, reporterConfig := GinkgoConfiguration()159 // adjust it160 suiteConfig.SkipStrings = []string{"NEVER-RUN"}161 reporterConfig.FullTrace = true162 // pass it in to RunSpecs163 RunSpecs(t, "My Suite", suiteConfig, reporterConfig)164 }165Note that some configuration changes can lead to undefined behavior. For example,166you should not change ParallelProcess or ParallelTotal as the Ginkgo CLI is responsible167for setting these and orchestrating parallel specs across the parallel processes. See http://onsi.github.io/ginkgo/#spec-parallelization168for more on how specs are parallelized in Ginkgo.169You can also pass suite-level Label() decorators to RunSpecs. The passed-in labels will apply to all specs in the suite.170*/171func RunSpecs(t GinkgoTestingT, description string, args ...interface{}) bool {172 if suiteDidRun {173 exitIfErr(types.GinkgoErrors.RerunningSuite())174 }175 suiteDidRun = true176 suiteLabels := Labels{}177 configErrors := []error{}178 for _, arg := range args {179 switch arg := arg.(type) {180 case types.SuiteConfig:181 suiteConfig = arg182 case types.ReporterConfig:183 reporterConfig = arg184 case Labels:185 suiteLabels = append(suiteLabels, arg...)186 default:187 configErrors = append(configErrors, types.GinkgoErrors.UnknownTypePassedToRunSpecs(arg))188 }189 }190 exitIfErrors(configErrors)191 configErrors = types.VetConfig(flagSet, suiteConfig, reporterConfig)192 if len(configErrors) > 0 {193 fmt.Fprintf(formatter.ColorableStdErr, formatter.F("{{red}}Ginkgo detected configuration issues:{{/}}\n"))194 for _, err := range configErrors {195 fmt.Fprintf(formatter.ColorableStdErr, err.Error())196 }197 os.Exit(1)198 }199 var reporter reporters.Reporter200 if suiteConfig.ParallelTotal == 1 {201 reporter = reporters.NewDefaultReporter(reporterConfig, formatter.ColorableStdOut)202 outputInterceptor = internal.NoopOutputInterceptor{}203 client = nil204 } else {205 reporter = reporters.NoopReporter{}206 switch strings.ToLower(suiteConfig.OutputInterceptorMode) {207 case "swap":208 outputInterceptor = internal.NewOSGlobalReassigningOutputInterceptor()209 case "none":210 outputInterceptor = internal.NoopOutputInterceptor{}211 default:212 outputInterceptor = internal.NewOutputInterceptor()213 }214 client = parallel_support.NewClient(suiteConfig.ParallelHost)215 if !client.Connect() {216 client = nil217 exitIfErr(types.GinkgoErrors.UnreachableParallelHost(suiteConfig.ParallelHost))218 }219 defer client.Close()220 }221 writer := GinkgoWriter.(*internal.Writer)222 if reporterConfig.Verbose && suiteConfig.ParallelTotal == 1 {223 writer.SetMode(internal.WriterModeStreamAndBuffer)224 } else {225 writer.SetMode(internal.WriterModeBufferOnly)226 }227 if reporterConfig.WillGenerateReport() {228 registerReportAfterSuiteNodeForAutogeneratedReports(reporterConfig)229 }230 err := global.Suite.BuildTree()231 exitIfErr(err)232 suitePath, err := os.Getwd()233 exitIfErr(err)234 suitePath, err = filepath.Abs(suitePath)235 exitIfErr(err)236 passed, hasFocusedTests := global.Suite.Run(description, suiteLabels, suitePath, global.Failer, reporter, writer, outputInterceptor, interrupt_handler.NewInterruptHandler(suiteConfig.Timeout, client), client, suiteConfig)237 outputInterceptor.Shutdown()238 flagSet.ValidateDeprecations(deprecationTracker)239 if deprecationTracker.DidTrackDeprecations() {240 fmt.Fprintln(formatter.ColorableStdErr, deprecationTracker.DeprecationsReport())241 }242 if !passed {243 t.Fail()244 }245 if passed && hasFocusedTests && strings.TrimSpace(os.Getenv("GINKGO_EDITOR_INTEGRATION")) == "" {246 fmt.Println("PASS | FOCUSED")247 os.Exit(types.GINKGO_FOCUS_EXIT_CODE)248 }249 return passed250}251/*252Skip instructs Ginkgo to skip the current spec253You can call Skip in any Setup or Subject node closure.254For more on how to filter specs in Ginkgo see https://onsi.github.io/ginkgo/#filtering-specs255*/256func Skip(message string, callerSkip ...int) {257 skip := 0258 if len(callerSkip) > 0 {259 skip = callerSkip[0]260 }261 cl := types.NewCodeLocationWithStackTrace(skip + 1)262 global.Failer.Skip(message, cl)263 panic(types.GinkgoErrors.UncaughtGinkgoPanic(cl))264}265/*266Fail notifies Ginkgo that the current spec has failed. (Gomega will call Fail for you automatically when an assertion fails.)267Under the hood, Fail panics to end execution of the current spec. Ginkgo will catch this panic and proceed with268the subsequent spec. If you call Fail, or make an assertion, within a goroutine launched by your spec you must269add defer GinkgoRecover() to the goroutine to catch the panic emitted by Fail.270You can call Fail in any Setup or Subject node closure.271You can learn more about how Ginkgo manages failures here: https://onsi.github.io/ginkgo/#mental-model-how-ginkgo-handles-failure272*/273func Fail(message string, callerSkip ...int) {274 skip := 0275 if len(callerSkip) > 0 {276 skip = callerSkip[0]277 }278 cl := types.NewCodeLocationWithStackTrace(skip + 1)279 global.Failer.Fail(message, cl)280 panic(types.GinkgoErrors.UncaughtGinkgoPanic(cl))281}282/*283AbortSuite instructs Ginkgo to fail the current spec and skip all subsequent specs, thereby aborting the suite.284You can call AbortSuite in any Setup or Subject node closure.285You can learn more about how Ginkgo handles suite interruptions here: https://onsi.github.io/ginkgo/#interrupting-aborting-and-timing-out-suites286*/287func AbortSuite(message string, callerSkip ...int) {288 skip := 0289 if len(callerSkip) > 0 {290 skip = callerSkip[0]291 }292 cl := types.NewCodeLocationWithStackTrace(skip + 1)293 global.Failer.AbortSuite(message, cl)294 panic(types.GinkgoErrors.UncaughtGinkgoPanic(cl))295}296/*297GinkgoRecover should be deferred at the top of any spawned goroutine that (may) call `Fail`298Since Gomega assertions call fail, you should throw a `defer GinkgoRecover()` at the top of any goroutine that299calls out to Gomega300Here's why: Ginkgo's `Fail` method records the failure and then panics to prevent301further assertions from running. This panic must be recovered. Normally, Ginkgo recovers the panic for you,302however if a panic originates on a goroutine *launched* from one of your specs there's no303way for Ginkgo to rescue the panic. To do this, you must remember to `defer GinkgoRecover()` at the top of such a goroutine.304You can learn more about how Ginkgo manages failures here: https://onsi.github.io/ginkgo/#mental-model-how-ginkgo-handles-failure305*/306func GinkgoRecover() {307 e := recover()308 if e != nil {309 global.Failer.Panic(types.NewCodeLocationWithStackTrace(1), e)310 }311}312// pushNode is used by the various test construction DSL methods to push nodes onto the suite313// it handles returned errors, emits a detailed error message to help the user learn what they may have done wrong, then exits314func pushNode(node internal.Node, errors []error) bool {315 exitIfErrors(errors)316 exitIfErr(global.Suite.PushNode(node))317 return true318}319/*320Describe nodes are Container nodes that allow you to organize your specs. A Describe node's closure can contain any number of321Setup nodes (e.g. BeforeEach, AfterEach, JustBeforeEach), and Subject nodes (i.e. It).322Context and When nodes are aliases for Describe - use whichever gives your suite a better narrative flow. It is idomatic323to Describe the behavior of an object or function and, within that Describe, outline a number of Contexts and Whens.324You can learn more at https://onsi.github.io/ginkgo/#organizing-specs-with-container-nodes325In addition, container nodes can be decorated with a variety of decorators. You can learn more here: https://onsi.github.io/ginkgo/#decorator-reference326*/327func Describe(text string, args ...interface{}) bool {328 return pushNode(internal.NewNode(deprecationTracker, types.NodeTypeContainer, text, args...))329}330/*331FDescribe focuses specs within the Describe block.332*/333func FDescribe(text string, args ...interface{}) bool {334 args = append(args, internal.Focus)335 return pushNode(internal.NewNode(deprecationTracker, types.NodeTypeContainer, text, args...))336}337/*338PDescribe marks specs within the Describe block as pending.339*/340func PDescribe(text string, args ...interface{}) bool {341 args = append(args, internal.Pending)342 return pushNode(internal.NewNode(deprecationTracker, types.NodeTypeContainer, text, args...))343}344/*345XDescribe marks specs within the Describe block as pending.346XDescribe is an alias for PDescribe347*/348var XDescribe = PDescribe349/* Context is an alias for Describe - it generates the exact same kind of Container node */350var Context, FContext, PContext, XContext = Describe, FDescribe, PDescribe, XDescribe351/* When is an alias for Describe - it generates the exact same kind of Container node */352func When(text string, args ...interface{}) bool {353 return pushNode(internal.NewNode(deprecationTracker, types.NodeTypeContainer, "when "+text, args...))354}355/* When is an alias for Describe - it generates the exact same kind of Container node */356func FWhen(text string, args ...interface{}) bool {357 args = append(args, internal.Focus)358 return pushNode(internal.NewNode(deprecationTracker, types.NodeTypeContainer, "when "+text, args...))359}360/* When is an alias for Describe - it generates the exact same kind of Container node */361func PWhen(text string, args ...interface{}) bool {362 args = append(args, internal.Pending)363 return pushNode(internal.NewNode(deprecationTracker, types.NodeTypeContainer, "when "+text, args...))364}365var XWhen = PWhen366/*367It nodes are Subject nodes that contain your spec code and assertions.368Each It node corresponds to an individual Ginkgo spec. You cannot nest any other Ginkgo nodes within an It node's closure.369You can learn more at https://onsi.github.io/ginkgo/#spec-subjects-it370In addition, subject nodes can be decorated with a variety of decorators. You can learn more here: https://onsi.github.io/ginkgo/#decorator-reference371*/372func It(text string, args ...interface{}) bool {373 return pushNode(internal.NewNode(deprecationTracker, types.NodeTypeIt, text, args...))374}375/*376FIt allows you to focus an individual It.377*/378func FIt(text string, args ...interface{}) bool {379 args = append(args, internal.Focus)380 return pushNode(internal.NewNode(deprecationTracker, types.NodeTypeIt, text, args...))381}382/*383PIt allows you to mark an individual It as pending.384*/385func PIt(text string, args ...interface{}) bool {386 args = append(args, internal.Pending)387 return pushNode(internal.NewNode(deprecationTracker, types.NodeTypeIt, text, args...))388}389/*390XIt allows you to mark an individual It as pending.391XIt is an alias for PIt392*/393var XIt = PIt394/*395Specify is an alias for It - it can allow for more natural wording in some context.396*/397var Specify, FSpecify, PSpecify, XSpecify = It, FIt, PIt, XIt398/*399By allows you to better document complex Specs.400Generally you should try to keep your Its short and to the point. This is not always possible, however,401especially in the context of integration tests that capture complex or lengthy workflows.402By allows you to document such flows. By may be called within a Setup or Subject node (It, BeforeEach, etc...)403and will simply log the passed in text to the GinkgoWriter. If By is handed a function it will immediately run the function.404By will also generate and attach a ReportEntry to the spec. This will ensure that By annotations appear in Ginkgo's machine-readable reports.405Note that By does not generate a new Ginkgo node - rather it is simply synctactic sugar around GinkgoWriter and AddReportEntry406You can learn more about By here: https://onsi.github.io/ginkgo/#documenting-complex-specs-by407*/408func By(text string, callback ...func()) {409 if !global.Suite.InRunPhase() {410 exitIfErr(types.GinkgoErrors.ByNotDuringRunPhase(types.NewCodeLocation(1)))411 }412 value := struct {413 Text string414 Duration time.Duration415 }{416 Text: text,417 }418 t := time.Now()419 AddReportEntry("By Step", ReportEntryVisibilityNever, Offset(1), &value, t)420 formatter := formatter.NewWithNoColorBool(reporterConfig.NoColor)421 GinkgoWriter.Println(formatter.F("{{bold}}STEP:{{/}} %s {{gray}}%s{{/}}", text, t.Format(types.GINKGO_TIME_FORMAT)))422 if len(callback) == 1 {423 callback[0]()424 value.Duration = time.Since(t)...

Full Screen

Full Screen

main.go

Source:main.go Github

copy

Full Screen

...29 flag.BoolVar(&opts.printDebug, "print-debug", false, "Print all spec prefixes in non-regexp format. Use for debugging")30 flag.StringVar(&opts.logLevel, "log-level", logrus.ErrorLevel.String(), "Configure the logging level")31 flag.Parse()32 if opts.printChunk >= opts.numChunks {33 exitIfErr(fmt.Errorf("the chunk to print (%d) must be a smaller number than the number of chunks (%d)", opts.printChunk, opts.numChunks))34 }35 dir := flag.Arg(0)36 if dir == "" {37 exitIfErr(fmt.Errorf("test directory required as the argument"))38 }39 // Clean dir.40 var err error41 dir, err = filepath.Abs(dir)42 exitIfErr(err)43 wd, err := os.Getwd()44 exitIfErr(err)45 dir, err = filepath.Rel(wd, dir)46 exitIfErr(err)47 exitIfErr(opts.run(dir))48}49func exitIfErr(err error) {50 if err != nil {51 log.Fatal(err)52 }53}54func (opts options) run(dir string) error {55 level, err := logrus.ParseLevel(opts.logLevel)56 if err != nil {57 return fmt.Errorf("failed to parse the %s log level: %v", opts.logLevel, err)58 }59 logger := logrus.New()60 logger.SetLevel(level)61 describes, err := findDescribes(logger, dir)62 if err != nil {63 return err...

Full Screen

Full Screen

exitIfErr

Using AI Code Generation

copy

Full Screen

1import (2func TestExitIfErr(t *testing.T) {3 gomega.RegisterFailHandler(ginkgo.Fail)4 ginkgo.RunSpecs(t, "TestExitIfErr Suite")5}6var _ = ginkgo.Describe("TestExitIfErr", func() {7 ginkgo.It("should exit if err is not nil", func() {8 ginkgo.By("calling exitIfErr with a non nil error")9 err := fmt.Errorf("this is an error")10 ginkgo.ExitIfErr(err)11 ginkgo.Fail("should have exited")12 })13})14import (15func TestExitIfErr(t *testing.T) {16 gomega.RegisterFailHandler(ginkgo.Fail)17 ginkgo.RunSpecs(t, "TestExitIfErr Suite")18}19var _ = ginkgo.Describe("TestExitIfErr", func() {20 ginkgo.It("should not exit if err is nil", func() {21 ginkgo.By("calling exitIfErr with a nil error")22 ginkgo.ExitIfErr(err)23 ginkgo.Fail("should not have exited")24 })25})

Full Screen

Full Screen

exitIfErr

Using AI Code Generation

copy

Full Screen

1import (2func TestGinkgo(t *testing.T) {3 RegisterFailHandler(Fail)4 RunSpecs(t, "Ginkgo Suite")5}6var _ = Describe("Ginkgo", func() {7 Context("Test Ginkgo", func() {8 It("should exit if error", func() {9 exitIfErr(fmt.Errorf("error"))10 })11 })12})13import (14func exitIfErr(err error) {15 if err != nil {16 fmt.Println(err)17 }18}19--- FAIL: TestGinkgo (0.00s)20 --- FAIL: TestGinkgo/Test_Ginkgo (0.00s)

Full Screen

Full Screen

exitIfErr

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 ginkgo.ExitIfError(fmt.Errorf("error"))4}5import (6func main() {7 ginkgo.ExitIfError(nil)8}9import (10func main() {11 ginkgo.ExitIfError(fmt.Errorf("error"))12}

Full Screen

Full Screen

exitIfErr

Using AI Code Generation

copy

Full Screen

1func main() {2 var ginkgo = Ginkgo{}3 ginkgo.exitIfErr(errors.New("error"))4}5func main() {6 var ginkgo = Ginkgo{}7 ginkgo.exitIfErr(errors.New("error"))8}9func main() {10 var ginkgo = Ginkgo{}11 ginkgo.exitIfErr(errors.New("error"))12}13func main() {14 var ginkgo = Ginkgo{}15 ginkgo.exitIfErr(errors.New("error"))16}17func main() {18 var ginkgo = Ginkgo{}19 ginkgo.exitIfErr(errors.New("error"))20}21func main() {22 var ginkgo = Ginkgo{}23 ginkgo.exitIfErr(errors.New("error"))24}25func main() {26 var ginkgo = Ginkgo{}27 ginkgo.exitIfErr(errors.New("error"))28}29func main() {30 var ginkgo = Ginkgo{}31 ginkgo.exitIfErr(errors.New("error"))32}33func main() {34 var ginkgo = Ginkgo{}35 ginkgo.exitIfErr(errors.New("error"))36}37func main() {38 var ginkgo = Ginkgo{}39 ginkgo.exitIfErr(errors.New("error"))40}41func main() {42 var ginkgo = Ginkgo{}

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful