How to use When method of ginkgo Package

Best Ginkgo code snippet using ginkgo.When

ginkgo_dsl.go

Source:ginkgo_dsl.go Github

copy

Full Screen

...45	globalFailer = failer.New()46	globalSuite = suite.New(globalFailer)47}48//GinkgoWriter implements an io.Writer49//When running in verbose mode any writes to GinkgoWriter will be immediately printed50//to stdout.  Otherwise, GinkgoWriter will buffer any writes produced during the current test and flush them to screen51//only if the current test fails.52var GinkgoWriter io.Writer53//The interface by which Ginkgo receives *testing.T54type GinkgoTestingT interface {55	Fail()56}57//GinkgoRandomSeed returns the seed used to randomize spec execution order.  It is58//useful for seeding your own pseudorandom number generators (PRNGs) to ensure59//consistent executions from run to run, where your tests contain variability (for60//example, when selecting random test data).61func GinkgoRandomSeed() int64 {62	return config.GinkgoConfig.RandomSeed63}64//GinkgoParallelNode returns the parallel node number for the current ginkgo process65//The node number is 1-indexed66func GinkgoParallelNode() int {67	return config.GinkgoConfig.ParallelNode68}69//Some matcher libraries or legacy codebases require a *testing.T70//GinkgoT implements an interface analogous to *testing.T and can be used if71//the library in question accepts *testing.T through an interface72//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 the80// correct line number associated with the failure.81func GinkgoT(optionalOffset ...int) GinkgoTInterface {82	offset := 383	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 methods89//in the testing package's T.90type 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() bool100	Parallel()101	Skip(args ...interface{})102	Skipf(format string, args ...interface{})103	SkipNow()104	Skipped() bool105}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 ends110type Reporter reporters.Reporter111//Asynchronous specs are given a channel of the Done type.  You must close or write to the channel112//to tell Ginkgo that your async test is done.113type Done chan<- interface{}114//GinkgoTestDescription represents the information about the current running test returned by CurrentGinkgoTestDescription115//	FullTestText: a concatenation of ComponentTexts and the TestText116//	ComponentTexts: a list of all texts for the Describes & Contexts leading up to the current test117//	TestText: the text in the actual It or Measure node118//	IsMeasurement: true if the current test is a measurement119//	FileName: the name of the file containing the current test120//	LineNumber: the line number for the current test121//	Failed: if the current test has failed, this will be true (useful in an AfterEach)122type GinkgoTestDescription struct {123	FullTestText   string124	ComponentTexts []string125	TestText       string126	IsMeasurement bool127	FileName   string128	LineNumber int129	Failed   bool130	Duration time.Duration131}132//CurrentGinkgoTestDescripton returns information about the current running test.133func 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 run153//You use the RecordValue() function to track arbitrary numerical measurements.154//The RecordValueWithPrecision() function can be used alternatively to provide the unit155//and resolution of the numeric measurement.156//The optional info argument is passed to the test reporter and can be used to157// provide the measurement data to a custom reporter with context.158//159//See http://onsi.github.io/ginkgo/#benchmark_tests for more details160type 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 bootstrap171func 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), replace176//RunSpecs() with this method.177func 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), replace182//RunSpecs() with this method.  Note that parallel tests will not work correctly without the default reporter183func 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] = reporter189	}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 passed196}197func buildDefaultReporter() Reporter {198	remoteReportingServer := config.GinkgoConfig.StreamHost199	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.211func Skip(message string, callerSkip ...int) {212	skip := 0213	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.)220func Fail(message string, callerSkip ...int) {221	skip := 0222	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 that230//calls out to Gomega231//232//Here's why: Ginkgo's `Fail` method records the failure and then panics to prevent233//further assertions from running.  This panic must be recovered.  Ginkgo does this for you234//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 no237//way for Ginkgo to rescue the panic.  To do this, you must remember to `defer GinkgoRecover()` at the top of such a goroutine.238func 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 of245//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 functionally248//equivalent.  The difference is purely semantic -- you typical Describe the behavior of an object249//or method and, within that Describe, outline a number of Contexts and Whens.250func Describe(text string, body func()) bool {251	globalSuite.PushContainerNode(text, body, types.FlagTypeNone, codelocation.New(1))252	return true253}254//You can focus the tests within a describe block using FDescribe255func FDescribe(text string, body func()) bool {256	globalSuite.PushContainerNode(text, body, types.FlagTypeFocused, codelocation.New(1))257	return true258}259//You can mark the tests within a describe block as pending using PDescribe260func PDescribe(text string, body func()) bool {261	globalSuite.PushContainerNode(text, body, types.FlagTypePending, codelocation.New(1))262	return true263}264//You can mark the tests within a describe block as pending using XDescribe265func XDescribe(text string, body func()) bool {266	globalSuite.PushContainerNode(text, body, types.FlagTypePending, codelocation.New(1))267	return true268}269//Context blocks allow you to organize your specs.  A Context block can contain any number of270//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 functionally273//equivalent.  The difference is purely semantic -- you typical Describe the behavior of an object274//or method and, within that Describe, outline a number of Contexts and Whens.275func Context(text string, body func()) bool {276	globalSuite.PushContainerNode(text, body, types.FlagTypeNone, codelocation.New(1))277	return true278}279//You can focus the tests within a describe block using FContext280func FContext(text string, body func()) bool {281	globalSuite.PushContainerNode(text, body, types.FlagTypeFocused, codelocation.New(1))282	return true283}284//You can mark the tests within a describe block as pending using PContext285func PContext(text string, body func()) bool {286	globalSuite.PushContainerNode(text, body, types.FlagTypePending, codelocation.New(1))287	return true288}289//You can mark the tests within a describe block as pending using XContext290func XContext(text string, body func()) bool {291	globalSuite.PushContainerNode(text, body, types.FlagTypePending, codelocation.New(1))292	return true293}294//When blocks allow you to organize your specs.  A When block can contain any number of295//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 functionally298//equivalent.  The difference is purely semantic -- you typical Describe the behavior of an object299//or method and, within that Describe, outline a number of Contexts and Whens.300func When(text string, body func()) bool {301	globalSuite.PushContainerNode("when "+text, body, types.FlagTypeNone, codelocation.New(1))302	return true303}304//You can focus the tests within a describe block using FWhen305func FWhen(text string, body func()) bool {306	globalSuite.PushContainerNode("when "+text, body, types.FlagTypeFocused, codelocation.New(1))307	return true308}309//You can mark the tests within a describe block as pending using PWhen310func PWhen(text string, body func()) bool {311	globalSuite.PushContainerNode("when "+text, body, types.FlagTypePending, codelocation.New(1))312	return true313}314//You can mark the tests within a describe block as pending using XWhen315func XWhen(text string, body func()) bool {316	globalSuite.PushContainerNode("when "+text, body, types.FlagTypePending, codelocation.New(1))317	return true318}319//It blocks contain your test code and assertions.  You cannot nest any other Ginkgo blocks320//within an It block.321//322//Ginkgo will normally run It blocks synchronously.  To perform asynchronous tests, pass a323//function that accepts a Done channel.  When you do this, you can also provide an optional timeout.324func It(text string, body interface{}, timeout ...float64) bool {325	globalSuite.PushItNode(text, body, types.FlagTypeNone, codelocation.New(1), parseTimeout(timeout...))326	return true327}328//You can focus individual Its using FIt329func FIt(text string, body interface{}, timeout ...float64) bool {330	globalSuite.PushItNode(text, body, types.FlagTypeFocused, codelocation.New(1), parseTimeout(timeout...))331	return true332}333//You can mark Its as pending using PIt334func PIt(text string, _ ...interface{}) bool {335	globalSuite.PushItNode(text, func() {}, types.FlagTypePending, codelocation.New(1), 0)336	return true337}338//You can mark Its as pending using XIt339func XIt(text string, _ ...interface{}) bool {340	globalSuite.PushItNode(text, func() {}, types.FlagTypePending, codelocation.New(1), 0)341	return true342}343//Specify blocks are aliases for It blocks and allow for more natural wording in situations344//which "It" does not fit into a natural sentence flow. All the same protocols apply for Specify blocks345//which apply to It blocks.346func Specify(text string, body interface{}, timeout ...float64) bool {347	globalSuite.PushItNode(text, body, types.FlagTypeNone, codelocation.New(1), parseTimeout(timeout...))348	return true349}350//You can focus individual Specifys using FSpecify351func FSpecify(text string, body interface{}, timeout ...float64) bool {352	globalSuite.PushItNode(text, body, types.FlagTypeFocused, codelocation.New(1), parseTimeout(timeout...))353	return true354}355//You can mark Specifys as pending using PSpecify356func PSpecify(text string, is ...interface{}) bool {357	globalSuite.PushItNode(text, func() {}, types.FlagTypePending, codelocation.New(1), 0)358	return true359}360//You can mark Specifys as pending using XSpecify361func XSpecify(text string, is ...interface{}) bool {362	globalSuite.PushItNode(text, func() {}, types.FlagTypePending, codelocation.New(1), 0)363	return true364}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.372func 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)390func Measure(text string, body interface{}, samples int) bool {391	globalSuite.PushMeasureNode(text, body, types.FlagTypeNone, codelocation.New(1), samples)392	return true393}394//You can focus individual Measures using FMeasure395func FMeasure(text string, body interface{}, samples int) bool {396	globalSuite.PushMeasureNode(text, body, types.FlagTypeFocused, codelocation.New(1), samples)397	return true398}399//You can mark Maeasurements as pending using PMeasure400func PMeasure(text string, _ ...interface{}) bool {401	globalSuite.PushMeasureNode(text, func(b Benchmarker) {}, types.FlagTypePending, codelocation.New(1), 0)402	return true403}404//You can mark Maeasurements as pending using XMeasure405func XMeasure(text string, _ ...interface{}) bool {406	globalSuite.PushMeasureNode(text, func(b Benchmarker) {}, types.FlagTypePending, codelocation.New(1), 0)407	return true408}409//BeforeSuite blocks are run just once before any specs are run.  When running in parallel, each410//parallel node process will call BeforeSuite.411//412//BeforeSuite blocks can be made asynchronous by providing a body function that accepts a Done channel413//414//You may only register *one* BeforeSuite handler per test suite.  You typically do so in your bootstrap file at the top level.415func BeforeSuite(body interface{}, timeout ...float64) bool {416	globalSuite.SetBeforeSuiteNode(body, codelocation.New(1), parseTimeout(timeout...))417	return true418}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 channel425//426//You may only register *one* AfterSuite handler per test suite.  You typically do so in your bootstrap file at the top level.427func AfterSuite(body interface{}, timeout ...float64) bool {428	globalSuite.SetAfterSuiteNode(body, codelocation.New(1), parseTimeout(timeout...))429	return true430}431//SynchronizedBeforeSuite blocks are primarily meant to solve the problem of setting up singleton external resources shared across432//nodes when running tests in parallel.  For example, say you have a shared database that you can only start one instance of that433//must be used in your tests.  When running in parallel, only one node should set up the database and all other nodes should wait434//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 is437//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() []byte443//444//or, to run asynchronously:445//446//	func(done Done) []byte447//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.Client459//	var dbRunner db.Runner460//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//	})471func 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 true479}480//SynchronizedAfterSuite blocks complement the SynchronizedBeforeSuite blocks in solving the problem of setting up481//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 #1484//and *only* after all other nodes have finished and exited.  This ensures that node 1, and any resources it is running, remain alive until485//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 database490//only after all nodes have finished:491//492//	var _ = SynchronizedAfterSuite(func() {493//		dbClient.Cleanup()494//	}, func() {495//		dbRunner.Stop()496//	})497func 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 true505}506//BeforeEach blocks are run before It blocks.  When multiple BeforeEach blocks are defined in nested507//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 accepts510//a Done channel511func BeforeEach(body interface{}, timeout ...float64) bool {512	globalSuite.PushBeforeEachNode(body, codelocation.New(1), parseTimeout(timeout...))513	return true514}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 accepts519//a Done channel520func JustBeforeEach(body interface{}, timeout ...float64) bool {521	globalSuite.PushJustBeforeEachNode(body, codelocation.New(1), parseTimeout(timeout...))522	return true523}524//JustAfterEach blocks are run after It blocks but *before* all AfterEach blocks.  For more details,525//read the [documentation](http://onsi.github.io/ginkgo/#separating_creation_and_configuration_)526//527//Like It blocks, JustAfterEach blocks can be made asynchronous by providing a body function that accepts528//a Done channel529func JustAfterEach(body interface{}, timeout ...float64) bool {530	globalSuite.PushJustAfterEachNode(body, codelocation.New(1), parseTimeout(timeout...))531	return true532}533//AfterEach blocks are run after It blocks.   When multiple AfterEach blocks are defined in nested534//Describe and Context blocks the innermost AfterEach blocks are run first.535//536//Like It blocks, AfterEach blocks can be made asynchronous by providing a body function that accepts537//a Done channel538func AfterEach(body interface{}, timeout ...float64) bool {539	globalSuite.PushAfterEachNode(body, codelocation.New(1), parseTimeout(timeout...))540	return true541}542func parseTimeout(timeout ...float64) time.Duration {543	if len(timeout) == 0 {544		return time.Duration(defaultTimeout * int64(time.Second))545	} else {546		return time.Duration(timeout[0] * float64(time.Second))547	}...

Full Screen

Full Screen

run_test.go

Source:run_test.go Github

copy

Full Screen

1package integration_test2import (3	"fmt"4	"io/ioutil"5	"os"6	"regexp"7	"runtime"8	"strings"9	. "github.com/onsi/ginkgo"10	"github.com/onsi/ginkgo/types"11	. "github.com/onsi/gomega"12	"github.com/onsi/gomega/gbytes"13	"github.com/onsi/gomega/gexec"14)15var _ = Describe("Running Specs", func() {16	var pathToTest string17	isWindows := (runtime.GOOS == "windows")18	denoter := "•"19	if isWindows {20		denoter = "+"21	}22	Context("when pointed at the current directory", func() {23		BeforeEach(func() {24			pathToTest = tmpPath("ginkgo")25			copyIn(fixturePath("passing_ginkgo_tests"), pathToTest, false)26		})27		It("should run the tests in the working directory", func() {28			session := startGinkgo(pathToTest, "--noColor")29			Eventually(session).Should(gexec.Exit(0))30			output := string(session.Out.Contents())31			Ω(output).Should(ContainSubstring("Running Suite: Passing_ginkgo_tests Suite"))32			Ω(output).Should(ContainSubstring(strings.Repeat(denoter, 4)))33			Ω(output).Should(ContainSubstring("SUCCESS! -- 4 Passed"))34			Ω(output).Should(ContainSubstring("Test Suite Passed"))35		})36	})37	Context("when passed an explicit package to run", func() {38		BeforeEach(func() {39			pathToTest = tmpPath("ginkgo")40			copyIn(fixturePath("passing_ginkgo_tests"), pathToTest, false)41		})42		It("should run the ginkgo style tests", func() {43			session := startGinkgo(tmpDir, "--noColor", pathToTest)44			Eventually(session).Should(gexec.Exit(0))45			output := string(session.Out.Contents())46			Ω(output).Should(ContainSubstring("Running Suite: Passing_ginkgo_tests Suite"))47			Ω(output).Should(ContainSubstring(strings.Repeat(denoter, 4)))48			Ω(output).Should(ContainSubstring("SUCCESS! -- 4 Passed"))49			Ω(output).Should(ContainSubstring("Test Suite Passed"))50		})51	})52	Context("when passed a number of packages to run", func() {53		BeforeEach(func() {54			pathToTest = tmpPath("ginkgo")55			otherPathToTest := tmpPath("other")56			copyIn(fixturePath("passing_ginkgo_tests"), pathToTest, false)57			copyIn(fixturePath("more_ginkgo_tests"), otherPathToTest, false)58		})59		It("should run the ginkgo style tests", func() {60			session := startGinkgo(tmpDir, "--noColor", "--succinct=false", "ginkgo", "./other")61			Eventually(session).Should(gexec.Exit(0))62			output := string(session.Out.Contents())63			Ω(output).Should(ContainSubstring("Running Suite: Passing_ginkgo_tests Suite"))64			Ω(output).Should(ContainSubstring("Running Suite: More_ginkgo_tests Suite"))65			Ω(output).Should(ContainSubstring("Test Suite Passed"))66		})67	})68	Context("when passed a number of packages to run, some of which have focused tests", func() {69		BeforeEach(func() {70			pathToTest = tmpPath("ginkgo")71			otherPathToTest := tmpPath("other")72			focusedPathToTest := tmpPath("focused")73			copyIn(fixturePath("passing_ginkgo_tests"), pathToTest, false)74			copyIn(fixturePath("more_ginkgo_tests"), otherPathToTest, false)75			copyIn(fixturePath("focused_fixture"), focusedPathToTest, false)76		})77		It("should exit with a status code of 2 and explain why", func() {78			session := startGinkgo(tmpDir, "--noColor", "--succinct=false", "-r")79			Eventually(session).Should(gexec.Exit(types.GINKGO_FOCUS_EXIT_CODE))80			output := string(session.Out.Contents())81			Ω(output).Should(ContainSubstring("Running Suite: Passing_ginkgo_tests Suite"))82			Ω(output).Should(ContainSubstring("Running Suite: More_ginkgo_tests Suite"))83			Ω(output).Should(ContainSubstring("Test Suite Passed"))84			Ω(output).Should(ContainSubstring("Detected Programmatic Focus - setting exit status to %d", types.GINKGO_FOCUS_EXIT_CODE))85		})86		Context("when the GINKGO_EDITOR_INTEGRATION environment variable is set", func() {87			BeforeEach(func() {88				os.Setenv("GINKGO_EDITOR_INTEGRATION", "true")89			})90			AfterEach(func() {91				os.Setenv("GINKGO_EDITOR_INTEGRATION", "")92			})93			It("should exit with a status code of 0 to allow a coverage file to be generated", func() {94				session := startGinkgo(tmpDir, "--noColor", "--succinct=false", "-r")95				Eventually(session).Should(gexec.Exit(0))96				output := string(session.Out.Contents())97				Ω(output).Should(ContainSubstring("Running Suite: Passing_ginkgo_tests Suite"))98				Ω(output).Should(ContainSubstring("Running Suite: More_ginkgo_tests Suite"))99				Ω(output).Should(ContainSubstring("Test Suite Passed"))100			})101		})102	})103	Context("when told to skipPackages", func() {104		BeforeEach(func() {105			pathToTest = tmpPath("ginkgo")106			otherPathToTest := tmpPath("other")107			focusedPathToTest := tmpPath("focused")108			copyIn(fixturePath("passing_ginkgo_tests"), pathToTest, false)109			copyIn(fixturePath("more_ginkgo_tests"), otherPathToTest, false)110			copyIn(fixturePath("focused_fixture"), focusedPathToTest, false)111		})112		It("should skip packages that match the list", func() {113			session := startGinkgo(tmpDir, "--noColor", "--skipPackage=other,focused", "-r")114			Eventually(session).Should(gexec.Exit(0))115			output := string(session.Out.Contents())116			Ω(output).Should(ContainSubstring("Passing_ginkgo_tests Suite"))117			Ω(output).ShouldNot(ContainSubstring("More_ginkgo_tests Suite"))118			Ω(output).ShouldNot(ContainSubstring("Focused_fixture Suite"))119			Ω(output).Should(ContainSubstring("Test Suite Passed"))120		})121		Context("when all packages are skipped", func() {122			It("should not run anything, but still exit 0", func() {123				session := startGinkgo(tmpDir, "--noColor", "--skipPackage=other,focused,ginkgo", "-r")124				Eventually(session).Should(gexec.Exit(0))125				output := string(session.Out.Contents())126				Ω(output).Should(ContainSubstring("All tests skipped!"))127				Ω(output).ShouldNot(ContainSubstring("Passing_ginkgo_tests Suite"))128				Ω(output).ShouldNot(ContainSubstring("More_ginkgo_tests Suite"))129				Ω(output).ShouldNot(ContainSubstring("Focused_fixture Suite"))130				Ω(output).ShouldNot(ContainSubstring("Test Suite Passed"))131			})132		})133	})134	Context("when there are no tests to run", func() {135		It("should exit 1", func() {136			session := startGinkgo(tmpDir, "--noColor", "--skipPackage=other,focused", "-r")137			Eventually(session).Should(gexec.Exit(1))138			output := string(session.Err.Contents())139			Ω(output).Should(ContainSubstring("Found no test suites"))140		})141	})142	Context("when there are test files but `go test` reports there are no tests to run", func() {143		BeforeEach(func() {144			pathToTest = tmpPath("ginkgo")145			copyIn(fixturePath("no_test_fn"), pathToTest, false)146		})147		It("suggests running ginkgo bootstrap", func() {148			session := startGinkgo(tmpDir, "--noColor", "--skipPackage=other,focused", "-r")149			Eventually(session).Should(gexec.Exit(0))150			output := string(session.Err.Contents())151			Ω(output).Should(ContainSubstring(`Found no test suites, did you forget to run "ginkgo bootstrap"?`))152		})153		It("fails if told to requireSuite", func() {154			session := startGinkgo(tmpDir, "--noColor", "--skipPackage=other,focused", "-r", "-requireSuite")155			Eventually(session).Should(gexec.Exit(1))156			output := string(session.Err.Contents())157			Ω(output).Should(ContainSubstring(`Found no test suites, did you forget to run "ginkgo bootstrap"?`))158		})159	})160	Context("when told to randomizeSuites", func() {161		BeforeEach(func() {162			pathToTest = tmpPath("ginkgo")163			otherPathToTest := tmpPath("other")164			copyIn(fixturePath("passing_ginkgo_tests"), pathToTest, false)165			copyIn(fixturePath("more_ginkgo_tests"), otherPathToTest, false)166		})167		It("should skip packages that match the regexp", func() {168			session := startGinkgo(tmpDir, "--noColor", "--randomizeSuites", "-r", "--seed=2")169			Eventually(session).Should(gexec.Exit(0))170			Ω(session).Should(gbytes.Say("More_ginkgo_tests Suite"))171			Ω(session).Should(gbytes.Say("Passing_ginkgo_tests Suite"))172			session = startGinkgo(tmpDir, "--noColor", "--randomizeSuites", "-r", "--seed=3")173			Eventually(session).Should(gexec.Exit(0))174			Ω(session).Should(gbytes.Say("Passing_ginkgo_tests Suite"))175			Ω(session).Should(gbytes.Say("More_ginkgo_tests Suite"))176		})177	})178	Context("when pointed at a package with xunit style tests", func() {179		BeforeEach(func() {180			pathToTest = tmpPath("xunit")181			copyIn(fixturePath("xunit_tests"), pathToTest, false)182		})183		It("should run the xunit style tests", func() {184			session := startGinkgo(pathToTest)185			Eventually(session).Should(gexec.Exit(0))186			output := string(session.Out.Contents())187			Ω(output).Should(ContainSubstring("--- PASS: TestAlwaysTrue"))188			Ω(output).Should(ContainSubstring("Test Suite Passed"))189		})190	})191	Context("when pointed at a package with no tests", func() {192		BeforeEach(func() {193			pathToTest = tmpPath("no_tests")194			copyIn(fixturePath("no_tests"), pathToTest, false)195		})196		It("should fail", func() {197			session := startGinkgo(pathToTest, "--noColor")198			Eventually(session).Should(gexec.Exit(1))199			Ω(session.Err.Contents()).Should(ContainSubstring("Found no test suites"))200		})201	})202	Context("when pointed at a package that fails to compile", func() {203		BeforeEach(func() {204			pathToTest = tmpPath("does_not_compile")205			copyIn(fixturePath("does_not_compile"), pathToTest, false)206		})207		It("should fail", func() {208			session := startGinkgo(pathToTest, "--noColor")209			Eventually(session).Should(gexec.Exit(1))210			output := string(session.Out.Contents())211			Ω(output).Should(ContainSubstring("Failed to compile"))212		})213	})214	Context("when running in parallel", func() {215		BeforeEach(func() {216			pathToTest = tmpPath("ginkgo")217			copyIn(fixturePath("passing_ginkgo_tests"), pathToTest, false)218		})219		Context("with a specific number of -nodes", func() {220			It("should use the specified number of nodes", func() {221				session := startGinkgo(pathToTest, "--noColor", "-succinct", "-nodes=2")222				Eventually(session).Should(gexec.Exit(0))223				output := string(session.Out.Contents())224				Ω(output).Should(MatchRegexp(`\[\d+\] Passing_ginkgo_tests Suite - 4 specs - 2 nodes [%s]{4} SUCCESS! \d+(\.\d+)?[muµ]s`, regexp.QuoteMeta(denoter)))225				Ω(output).Should(ContainSubstring("Test Suite Passed"))226			})227		})228		Context("with -p", func() {229			It("it should autocompute the number of nodes", func() {230				session := startGinkgo(pathToTest, "--noColor", "-succinct", "-p")231				Eventually(session).Should(gexec.Exit(0))232				output := string(session.Out.Contents())233				nodes := runtime.NumCPU()234				if nodes == 1 {235					Skip("Can't test parallel testings with 1 CPU")236				}237				if nodes > 4 {238					nodes = nodes - 1239				}240				Ω(output).Should(MatchRegexp(`\[\d+\] Passing_ginkgo_tests Suite - 4 specs - %d nodes [%s]{4} SUCCESS! \d+(\.\d+)?[muµ]?s`, nodes, regexp.QuoteMeta(denoter)))241				Ω(output).Should(ContainSubstring("Test Suite Passed"))242			})243		})244	})245	Context("when running in parallel with -debug", func() {246		BeforeEach(func() {247			pathToTest = tmpPath("ginkgo")248			copyIn(fixturePath("debug_parallel_fixture"), pathToTest, false)249		})250		Context("without -v", func() {251			It("should emit node output to files on disk", func() {252				session := startGinkgo(pathToTest, "--nodes=2", "--debug")253				Eventually(session).Should(gexec.Exit(0))254				f0, err := ioutil.ReadFile(pathToTest + "/ginkgo-node-1.log")255				Ω(err).ShouldNot(HaveOccurred())256				f1, err := ioutil.ReadFile(pathToTest + "/ginkgo-node-2.log")257				Ω(err).ShouldNot(HaveOccurred())258				content := string(append(f0, f1...))259				for i := 0; i < 10; i += 1 {260					Ω(content).Should(ContainSubstring("StdOut %d\n", i))261					Ω(content).Should(ContainSubstring("GinkgoWriter %d\n", i))262				}263			})264		})265		Context("without -v", func() {266			It("should emit node output to files on disk, without duplicating the GinkgoWriter output", func() {267				session := startGinkgo(pathToTest, "--nodes=2", "--debug", "-v")268				Eventually(session).Should(gexec.Exit(0))269				f0, err := ioutil.ReadFile(pathToTest + "/ginkgo-node-1.log")270				Ω(err).ShouldNot(HaveOccurred())271				f1, err := ioutil.ReadFile(pathToTest + "/ginkgo-node-2.log")272				Ω(err).ShouldNot(HaveOccurred())273				content := string(append(f0, f1...))274				out := strings.Split(content, "GinkgoWriter 2")275				Ω(out).Should(HaveLen(2))276			})277		})278	})279	Context("when streaming in parallel", func() {280		BeforeEach(func() {281			pathToTest = tmpPath("ginkgo")282			copyIn(fixturePath("passing_ginkgo_tests"), pathToTest, false)283		})284		It("should print output in realtime", func() {285			session := startGinkgo(pathToTest, "--noColor", "-stream", "-nodes=2")286			Eventually(session).Should(gexec.Exit(0))287			output := string(session.Out.Contents())288			Ω(output).Should(ContainSubstring(`[1] Parallel test node 1/2.`))289			Ω(output).Should(ContainSubstring(`[2] Parallel test node 2/2.`))290			Ω(output).Should(ContainSubstring(`[1] SUCCESS!`))291			Ω(output).Should(ContainSubstring(`[2] SUCCESS!`))292			Ω(output).Should(ContainSubstring("Test Suite Passed"))293		})294	})295	Context("when running recursively", func() {296		BeforeEach(func() {297			passingTest := tmpPath("A")298			otherPassingTest := tmpPath("E")299			copyIn(fixturePath("passing_ginkgo_tests"), passingTest, false)300			copyIn(fixturePath("more_ginkgo_tests"), otherPassingTest, false)301		})302		Context("when all the tests pass", func() {303			Context("with the -r flag", func() {304				It("should run all the tests (in succinct mode) and succeed", func() {305					session := startGinkgo(tmpDir, "--noColor", "-r", ".")306					Eventually(session).Should(gexec.Exit(0))307					output := string(session.Out.Contents())308					outputLines := strings.Split(output, "\n")309					Ω(outputLines[0]).Should(MatchRegexp(`\[\d+\] Passing_ginkgo_tests Suite - 4/4 specs [%s]{4} SUCCESS! \d+(\.\d+)?[muµ]s PASS`, regexp.QuoteMeta(denoter)))310					Ω(outputLines[1]).Should(MatchRegexp(`\[\d+\] More_ginkgo_tests Suite - 2/2 specs [%s]{2} SUCCESS! \d+(\.\d+)?[muµ]s PASS`, regexp.QuoteMeta(denoter)))311					Ω(output).Should(ContainSubstring("Test Suite Passed"))312				})313			})314			Context("with a trailing /...", func() {315				It("should run all the tests (in succinct mode) and succeed", func() {316					session := startGinkgo(tmpDir, "--noColor", "./...")317					Eventually(session).Should(gexec.Exit(0))318					output := string(session.Out.Contents())319					outputLines := strings.Split(output, "\n")320					Ω(outputLines[0]).Should(MatchRegexp(`\[\d+\] Passing_ginkgo_tests Suite - 4/4 specs [%s]{4} SUCCESS! \d+(\.\d+)?[muµ]s PASS`, regexp.QuoteMeta(denoter)))321					Ω(outputLines[1]).Should(MatchRegexp(`\[\d+\] More_ginkgo_tests Suite - 2/2 specs [%s]{2} SUCCESS! \d+(\.\d+)?[muµ]s PASS`, regexp.QuoteMeta(denoter)))322					Ω(output).Should(ContainSubstring("Test Suite Passed"))323				})324			})325		})326		Context("when one of the packages has a failing tests", func() {327			BeforeEach(func() {328				failingTest := tmpPath("C")329				copyIn(fixturePath("failing_ginkgo_tests"), failingTest, false)330			})331			It("should fail and stop running tests", func() {332				session := startGinkgo(tmpDir, "--noColor", "-r")333				Eventually(session).Should(gexec.Exit(1))334				output := string(session.Out.Contents())335				outputLines := strings.Split(output, "\n")336				Ω(outputLines[0]).Should(MatchRegexp(`\[\d+\] Passing_ginkgo_tests Suite - 4/4 specs [%s]{4} SUCCESS! \d+(\.\d+)?[muµ]s PASS`, regexp.QuoteMeta(denoter)))337				Ω(outputLines[1]).Should(MatchRegexp(`\[\d+\] Failing_ginkgo_tests Suite - 2/2 specs`))338				Ω(output).Should(ContainSubstring(fmt.Sprintf("%s Failure", denoter)))339				Ω(output).ShouldNot(ContainSubstring("More_ginkgo_tests Suite"))340				Ω(output).Should(ContainSubstring("Test Suite Failed"))341				Ω(output).Should(ContainSubstring("Summarizing 1 Failure:"))342				Ω(output).Should(ContainSubstring("[Fail] FailingGinkgoTests [It] should fail"))343			})344		})345		Context("when one of the packages fails to compile", func() {346			BeforeEach(func() {347				doesNotCompileTest := tmpPath("C")348				copyIn(fixturePath("does_not_compile"), doesNotCompileTest, false)349			})350			It("should fail and stop running tests", func() {351				session := startGinkgo(tmpDir, "--noColor", "-r")352				Eventually(session).Should(gexec.Exit(1))353				output := string(session.Out.Contents())354				outputLines := strings.Split(output, "\n")355				Ω(outputLines[0]).Should(MatchRegexp(`\[\d+\] Passing_ginkgo_tests Suite - 4/4 specs [%s]{4} SUCCESS! \d+(\.\d+)?[muµ]s PASS`, regexp.QuoteMeta(denoter)))356				Ω(outputLines[1]).Should(ContainSubstring("Failed to compile C:"))357				Ω(output).ShouldNot(ContainSubstring("More_ginkgo_tests Suite"))358				Ω(output).Should(ContainSubstring("Test Suite Failed"))359			})360		})361		Context("when either is the case, but the keepGoing flag is set", func() {362			BeforeEach(func() {363				doesNotCompileTest := tmpPath("B")364				copyIn(fixturePath("does_not_compile"), doesNotCompileTest, false)365				failingTest := tmpPath("C")366				copyIn(fixturePath("failing_ginkgo_tests"), failingTest, false)367			})368			It("should soldier on", func() {369				session := startGinkgo(tmpDir, "--noColor", "-r", "-keepGoing")370				Eventually(session).Should(gexec.Exit(1))371				output := string(session.Out.Contents())372				outputLines := strings.Split(output, "\n")373				Ω(outputLines[0]).Should(MatchRegexp(`\[\d+\] Passing_ginkgo_tests Suite - 4/4 specs [%s]{4} SUCCESS! \d+(\.\d+)?[muµ]s PASS`, regexp.QuoteMeta(denoter)))374				Ω(outputLines[1]).Should(ContainSubstring("Failed to compile B:"))375				Ω(output).Should(MatchRegexp(`\[\d+\] Failing_ginkgo_tests Suite - 2/2 specs`))376				Ω(output).Should(ContainSubstring(fmt.Sprintf("%s Failure", denoter)))377				Ω(output).Should(MatchRegexp(`\[\d+\] More_ginkgo_tests Suite - 2/2 specs [%s]{2} SUCCESS! \d+(\.\d+)?[muµ]s PASS`, regexp.QuoteMeta(denoter)))378				Ω(output).Should(ContainSubstring("Test Suite Failed"))379			})380		})381	})382	Context("when told to keep going --untilItFails", func() {383		BeforeEach(func() {384			copyIn(fixturePath("eventually_failing"), tmpDir, false)385		})386		It("should keep rerunning the tests, until a failure occurs", func() {387			session := startGinkgo(tmpDir, "--untilItFails", "--noColor")388			Eventually(session).Should(gexec.Exit(1))389			Ω(session).Should(gbytes.Say("This was attempt #1"))390			Ω(session).Should(gbytes.Say("This was attempt #2"))391			Ω(session).Should(gbytes.Say("Tests failed on attempt #3"))392			//it should change the random seed between each test393			lines := strings.Split(string(session.Out.Contents()), "\n")394			randomSeeds := []string{}395			for _, line := range lines {396				if strings.Contains(line, "Random Seed:") {397					randomSeeds = append(randomSeeds, strings.Split(line, ": ")[1])398				}399			}400			Ω(randomSeeds[0]).ShouldNot(Equal(randomSeeds[1]))401			Ω(randomSeeds[1]).ShouldNot(Equal(randomSeeds[2]))402			Ω(randomSeeds[0]).ShouldNot(Equal(randomSeeds[2]))403		})404	})405})...

Full Screen

Full Screen

filter_test.go

Source:filter_test.go Github

copy

Full Screen

1package server2import (3	"sync"4	"time"5	"github.com/goat-project/goat-os/resource"6	"github.com/gophercloud/gophercloud/openstack/compute/v2/servers"7	"github.com/goat-project/goat-os/constants"8	"github.com/spf13/viper"9	"github.com/onsi/ginkgo"10	"github.com/onsi/gomega"11)12var _ = ginkgo.Describe("Server Filter tests", func() {13	var (14		server *SFStruct15		wg     sync.WaitGroup16	)17	ginkgo.JustBeforeEach(func() {18		server = &SFStruct{Server: &servers.Server{Created: time.Unix(1540931164, 0)}}19		viper.SetDefault(constants.CfgRecordsFrom, time.Time{})20		viper.SetDefault(constants.CfgRecordsTo, time.Time{})21		viper.SetDefault(constants.CfgRecordsForPeriod, time.Time{})22	})23	ginkgo.Describe("create filter", func() {24		ginkgo.Context("when no values are set", func() {25			ginkgo.It("should create filter with no restrictions", func() {26				filter := CreateFilter()27				gomega.Expect(filter.recordsFrom).To(gomega.Equal(time.Time{}))28				gomega.Expect(filter.recordsTo).To(gomega.And(29					gomega.BeTemporally("<", time.Now().Add(time.Minute)),30					gomega.BeTemporally(">", time.Now().Add(-time.Minute))))31			})32		})33	})34	ginkgo.Describe("create filter", func() {35		ginkgo.Context("when time from is set", func() {36			ginkgo.It("should create filter", func() {37				dateFrom := time.Now().Add(-48 * time.Hour)38				viper.SetDefault(constants.CfgRecordsFrom, dateFrom)39				filter := CreateFilter()40				gomega.Expect(filter.recordsFrom).To(gomega.Equal(dateFrom))41				gomega.Expect(filter.recordsTo).To(gomega.And(42					gomega.BeTemporally("<", time.Now().Add(time.Minute)),43					gomega.BeTemporally(">", time.Now().Add(-time.Minute))))44			})45		})46	})47	ginkgo.Describe("create filter", func() {48		ginkgo.Context("when time from and to are set", func() {49			ginkgo.It("should create filter", func() {50				dateFrom := time.Now().Add(-48 * time.Hour)51				dateTo := time.Now().Add(-24 * time.Hour)52				viper.SetDefault(constants.CfgRecordsFrom, dateFrom)53				viper.SetDefault(constants.CfgRecordsTo, dateTo)54				filter := CreateFilter()55				gomega.Expect(filter.recordsFrom).To(gomega.Equal(dateFrom))56				gomega.Expect(filter.recordsTo).To(gomega.Equal(dateTo))57			})58		})59	})60	ginkgo.Describe("create filter", func() {61		ginkgo.Context("when time to is set", func() {62			ginkgo.It("should create filter", func() {63				dateTo := time.Now().Add(-48 * time.Hour)64				viper.SetDefault(constants.CfgRecordsTo, dateTo)65				filter := CreateFilter()66				gomega.Expect(filter.recordsFrom).To(gomega.Equal(time.Time{}))67				gomega.Expect(filter.recordsTo).To(gomega.Equal(dateTo))68			})69		})70	})71	ginkgo.Describe("create filter", func() {72		ginkgo.Context("when time from and to and period are set", func() {73			ginkgo.It("should not create filter", func() {74				dateFrom := time.Now().Add(-48 * time.Hour)75				dateTo := time.Now().Add(-24 * time.Hour)76				period := "1y"77				viper.SetDefault(constants.CfgRecordsFrom, dateFrom)78				viper.SetDefault(constants.CfgRecordsTo, dateTo)79				viper.SetDefault(constants.CfgRecordsForPeriod, period)80				// TODO test Fatal error81			})82		})83	})84	ginkgo.Describe("create filter", func() {85		ginkgo.Context("when period is set", func() {86			ginkgo.It("should create filter", func() {87				period := "1y"88				viper.SetDefault(constants.CfgRecordsForPeriod, period)89				filter := CreateFilter()90				// handle leap year91				days := 36592				if isLeapYear(time.Now().Year()) || (isLeapYear(time.Now().Year()-1) && time.Now().Month() < 3) {93					days = 36694				}95				expectation := time.Now().Add(-time.Duration(days) * 24 * time.Hour)96				gomega.Expect(filter.recordsFrom).To(gomega.And(97					gomega.BeTemporally("<", expectation.Add(time.Minute)),98					gomega.BeTemporally(">", expectation.Add(-time.Minute))))99				gomega.Expect(filter.recordsTo).To(gomega.And(100					gomega.BeTemporally("<", time.Now().Add(time.Minute)),101					gomega.BeTemporally(">", time.Now().Add(-time.Minute))))102			})103		})104	})105	ginkgo.Describe("create filter", func() {106		ginkgo.Context("when period and time to are set", func() {107			ginkgo.It("should create filter", func() {108				dateTo := time.Now().Add(-24 * time.Hour)109				period := "1y"110				viper.SetDefault(constants.CfgRecordsForPeriod, period)111				viper.SetDefault(constants.CfgRecordsTo, dateTo)112				// TODO test Fatal error113			})114		})115	})116	ginkgo.Describe("create filter", func() {117		ginkgo.Context("when period and time from are set", func() {118			ginkgo.It("should create filter", func() {119				dateFrom := time.Now().Add(-48 * time.Hour)120				period := "1y"121				viper.SetDefault(constants.CfgRecordsForPeriod, period)122				viper.SetDefault(constants.CfgRecordsFrom, dateFrom)123				// TODO test Fatal error124			})125		})126	})127	ginkgo.Describe("filter virtual machine", func() {128		ginkgo.Context("when channel is empty and resource correct", func() {129			ginkgo.It("should not post vm to the channel", func(done ginkgo.Done) {130				// res := resources.CreateVirtualMachineWithID(1)131				filtered := make(chan resource.Resource)132				filter := CreateFilter()133				wg.Add(1)134				go filter.Filtering(server, filtered, &wg)135				gomega.Expect(filtered).To(gomega.BeEmpty())136				close(done)137			}, 0.2)138		})139		ginkgo.Context("when channel is empty and resource is not correct", func() {140			ginkgo.It("should not post vm to the channel", func(done ginkgo.Done) {141				filtered := make(chan resource.Resource)142				filter := CreateFilter()143				wg.Add(1)144				go filter.Filtering(nil, filtered, &wg)145				gomega.Expect(filtered).To(gomega.BeEmpty())146				close(done)147			}, 0.2)148		})149		// TODO add test with full channel150		ginkgo.Context("when channel is empty and resource time is in range", func() {151			ginkgo.It("should post vm to the channel", func(done ginkgo.Done) {152				dateTo := time.Now().Add(-24 * time.Hour)153				viper.SetDefault(constants.CfgRecordsTo, dateTo)154				filter := CreateFilter()155				filtered := make(chan resource.Resource)156				wg.Add(1)157				go filter.Filtering(server, filtered, &wg)158				gomega.Expect(<-filtered).To(gomega.Equal(server))159				close(done)160			}, 0.2)161		})162		ginkgo.Context("when channel is empty and resource time is out of range", func() {163			ginkgo.It("should not post vm to the channel", func(done ginkgo.Done) {164				dateTo := time.Now().Add(-2 * 356 * 24 * time.Hour)165				viper.SetDefault(constants.CfgRecordsTo, dateTo)166				filter := CreateFilter()167				filtered := make(chan resource.Resource)168				wg.Add(1)169				go filter.Filtering(server, filtered, &wg)170				gomega.Expect(filtered).To(gomega.BeEmpty())171				close(done)172			}, 0.2)173		})174	})175})176func isLeapYear(y int) bool {177	// convert int to Time - use the last day of the year, which is 31st December178	year := time.Date(y, time.December, 31, 0, 0, 0, 0, time.Local)179	days := year.YearDay()180	return days > 365181}...

Full Screen

Full Screen

When

Using AI Code Generation

copy

Full Screen

1When("I login", func() {2    fmt.Println("I login")3})4When("I login", func() {5    fmt.Println("I login")6})7When("I login", func() {8    fmt.Println("I login")9})10When("I login", func() {11    fmt.Println("I login")12})13When("I login", func() {14    fmt.Println("I login")15})16When("I login", func() {17    fmt.Println("I login")18})19When("I login", func() {20    fmt.Println("I login")21})22When("I login", func() {23    fmt.Println("I login")24})25When("I login", func() {26    fmt.Println("I login")27})28When("I login", func() {29    fmt.Println("I login")30})31When("I login", func() {32    fmt.Println("I login")33})34When("I login", func() {35    fmt.Println("I login")36})37When("I login", func() {38    fmt.Println("I login")39})40When("I login", func() {41    fmt.Println("I login")42})43When("I login", func() {

Full Screen

Full Screen

When

Using AI Code Generation

copy

Full Screen

1When("I enter the username and password", func() {2})3And("I click on the login button", func() {4})5Then("I should be able to login successfully", func() {6})7Ginkgo is a BDD testing framework for Go. It is designed to make it easy to write tests in the style of Behavior-Driven Development (BDD). It is built on top of the Go testing package and the Gomega matcher library. Ginkgo is a testing framework that allows you to write tests that read like specifications. It is designed to make it easy to write tests in the style of Behavior-Driven Development (BDD), a

Full Screen

Full Screen

When

Using AI Code Generation

copy

Full Screen

1When("I enter {string} in the search field", func(arg1 string) {2})3When("I enter {string} in the search field", func(arg1 string) {4})5When("I enter {string} in the search field", func(arg1 string) {6})7When("I enter {string} in the search field", func(arg1 string) {8})9When("I enter {string} in the search field", func(arg1 string) {10})11When("I enter {string} in the search field", func(arg1 string) {12})13When("I enter {string} in the search field", func(arg1 string) {14})15When("I enter {string} in the search field", func(arg1 string) {16})17When("I enter {string} in the search field", func(arg1 string) {18})19When("I enter {string} in the search field", func(arg1 string) {20})21When("I enter {string} in the search field", func(arg1 string) {

Full Screen

Full Screen

When

Using AI Code Generation

copy

Full Screen

1func TestWhen(t *testing.T) {2    ginkgo.When("When code block", func() {3        ginkgo.It("It code block", func() {4            fmt.Println("When code block")5        })6    })7}8func TestDescribe(t *testing.T) {9    ginkgo.Describe("Describe code block", func() {10        ginkgo.It("It code block", func() {11            fmt.Println("Describe code block")12        })13    })14}15func TestContext(t *testing.T) {16    ginkgo.Context("Context code block", func() {17        ginkgo.It("It code block", func() {18            fmt.Println("Context code block")19        })20    })21}22func TestIt(t *testing.T) {23    ginkgo.It("It code block", func() {24        fmt.Println("It code block")25    })26}27func TestSpecify(t *testing.T) {28    ginkgo.Specify("Specify code block", func() {29        fmt.Println("Specify code block")30    })31}32func TestBy(t *testing.T) {33    ginkgo.It("It code block", func() {34        ginkgo.By("By code block")35        fmt.Println("It code block")36    })37}38func TestMeasure(t *testing.T) {39    ginkgo.Measure("Measure code block", func(b Benchmarker) {40        r := b.Time("runtime", func() {41            fmt.Println("Measure code block")42        })43        ginkgo.By("By code block")44        ginkgo.Expect(r.Seconds()).To(gomega.BeNumerically("<", 1.0))45    }, 1)46}47func TestBeforeEach(t *testing.T) {48    ginkgo.BeforeEach(func() {49        fmt.Println("BeforeEach code block

Full Screen

Full Screen

When

Using AI Code Generation

copy

Full Screen

1ginkgo.When("I am on the main page", func() {2    ginkgo.By("visiting the main page", func() {3        Expect(true).To(BeTrue())4    })5})6ginkgo.It("I am on the main page", func() {7    ginkgo.By("visiting the main page", func() {8        Expect(true).To(BeTrue())9    })10})11ginkgo.Specify("I am on the main page", func() {12    ginkgo.By("visiting the main page", func() {13        Expect(true).To(BeTrue())14    })15})16ginkgo.By("I am on the main page", func() {17    ginkgo.By("visiting the main page", func() {18        Expect(true).To(BeTrue())19    })20})21ginkgo.By("I am on the main page", func() {22    ginkgo.By("visiting the main page", func() {23        Expect(true).To(BeTrue())24    })25})26ginkgo.By("I am on the main page", func() {27    ginkgo.By("visiting the main page", func() {28        Expect(true).To(BeTrue())29    })30})31ginkgo.By("I am on the main page", func() {32    ginkgo.By("visiting the main page", func() {33        Expect(true).To(BeTrue())34    })35})36ginkgo.By("I am on the main page", func() {37    ginkgo.By("visiting the main page", func() {38        Expect(true).To(BeTrue())39    })40})41ginkgo.By("I am on the main page", func() {

Full Screen

Full Screen

When

Using AI Code Generation

copy

Full Screen

1Describe("Test", func() {2    Context("When the context is true", func() {3        It("should do something", func() {4            Expect(1).To(Equal(1))5        })6    })7})8Describe("Test", func() {9    When("the context is true", func() {10        It("should do something", func() {11            Expect(1).To(Equal(1))12        })13    })14})

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