// TestPutGOB tests the PUT command with a GOB payload and result. func TestPutGOB(t *testing.T) { assert := audit.NewTestingAssertion(t, true) // Setup the test server. mux, ts, err := web.StartTestServer() assert.Nil(err) defer ts.Close() err = mux.Register("test", "gob", NewTestHandler("putgob", assert)) assert.Nil(err) // Perform test requests. reqData := TestCounterData{"test", 4711} reqBuf := new(bytes.Buffer) err = gob.NewEncoder(reqBuf).Encode(reqData) assert.Nil(err, "GOB encode.") t.Logf("%q", reqBuf.String()) resp, err := web.DoTestRequest(ts, &web.TestRequest{ Method: "POST", Path: "/test/gob", Header: web.TestSettings{"Content-Type": "application/vnd.tideland.gob"}, Body: reqBuf.Bytes(), }) var respData TestCounterData err = gob.NewDecoder(bytes.NewBuffer(resp.Body)).Decode(&respData) assert.Nil(err, "GOB decode.") assert.Equal(respData.ID, "test", "GOB decoded 'id'.") assert.Equal(respData.Count, int64(4711), "GOB decoded 'count'.") }
// TestCleanupNoError tests the cleanup of props with // no errors. func TestCleanupNoError(t *testing.T) { assert := audit.NewTestingAssertion(t, false) cleanups := make(map[string]interface{}) cleanup := func(key string, prop interface{}) error { cleanups[key] = prop return nil } scn := scene.Start() err := scn.StoreClean("foo", 4711, cleanup) assert.Nil(err) err = scn.StoreClean("bar", "yadda", cleanup) assert.Nil(err) foo, err := scn.Dispose("foo") assert.Nil(err) assert.Equal(foo, 4711) err = scn.Stop() assert.Nil(err) assert.Length(cleanups, 2) assert.Equal(cleanups["foo"], 4711) assert.Equal(cleanups["bar"], "yadda") }
// TestEnvironmentSubscribersDo tests the iteration over // the subscribers. func TestEnvironmentSubscribersDo(t *testing.T) { assert := audit.NewTestingAssertion(t, true) env := cells.NewEnvironment("subscribers-do") defer env.Stop() err := env.StartCell("foo", newCollectBehavior()) assert.Nil(err) err = env.StartCell("bar", newCollectBehavior()) assert.Nil(err) err = env.StartCell("baz", newCollectBehavior()) assert.Nil(err) err = env.Subscribe("foo", "bar", "baz") assert.Nil(err) err = env.EmitNew("foo", iterateTopic, nil, nil) assert.Nil(err) time.Sleep(200 * time.Millisecond) collected, err := env.Request("bar", cells.ProcessedTopic, nil, nil, cells.DefaultTimeout) assert.Nil(err) assert.Length(collected, 1) assert.Contents(`<topic: "love" / payload: <"default": foo loves bar>>`, collected) collected, err = env.Request("baz", cells.ProcessedTopic, nil, nil, cells.DefaultTimeout) assert.Nil(err) assert.Length(collected, 1) assert.Contents(`<topic: "love" / payload: <"default": foo loves baz>>`, collected) }
// TestSimpleInactivityTimeout tests a simple scene usage // with inactivity timeout. func TestSimpleInactivityTimeout(t *testing.T) { assert := audit.NewTestingAssertion(t, false) scn := scene.StartLimited(100*time.Millisecond, 0) err := scn.Store("foo", 4711) assert.Nil(err) for i := 0; i < 5; i++ { foo, err := scn.Fetch("foo") assert.Nil(err) assert.Equal(foo, 4711) time.Sleep(50) } time.Sleep(100 * time.Millisecond) foo, err := scn.Fetch("foo") assert.True(scene.IsTimeoutError(err)) assert.Nil(foo) status, err := scn.Status() assert.True(scene.IsTimeoutError(err)) assert.Equal(status, scene.Over) err = scn.Stop() assert.True(scene.IsTimeoutError(err)) }
// TestEarlyFlag tests the signaling before a waiting. func TestEarlyFlag(t *testing.T) { assert := audit.NewTestingAssertion(t, false) scn := scene.Start() err := scn.Flag("foo") assert.Nil(err) go func() { err := scn.WaitFlag("foo") assert.Nil(err) err = scn.Store("foo-a", true) assert.Nil(err) }() go func() { err := scn.WaitFlag("foo") assert.Nil(err) err = scn.Store("foo-b", true) assert.Nil(err) }() time.Sleep(100 * time.Millisecond) fooA, err := scn.Fetch("foo-a") assert.Nil(err) assert.Equal(fooA, true) fooB, err := scn.Fetch("foo-b") assert.Nil(err) assert.Equal(fooB, true) err = scn.Stop() assert.Nil(err) }
// Test time containments. func TestTimeContainments(t *testing.T) { assert := audit.NewTestingAssertion(t, true) // Create some test data. ts := time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC) years := []int{2008, 2009, 2010} months := []time.Month{10, 11, 12} days := []int{10, 11, 12, 13, 14} hours := []int{20, 21, 22, 23} minutes := []int{0, 5, 10, 15, 20, 25} seconds := []int{0, 15, 30, 45} weekdays := []time.Weekday{time.Monday, time.Tuesday, time.Wednesday} assert.True(timex.YearInList(ts, years), "Go time in year list.") assert.True(timex.YearInRange(ts, 2005, 2015), "Go time in year range.") assert.True(timex.MonthInList(ts, months), "Go time in month list.") assert.True(timex.MonthInRange(ts, 7, 12), "Go time in month range.") assert.True(timex.DayInList(ts, days), "Go time in day list.") assert.True(timex.DayInRange(ts, 5, 15), "Go time in day range .") assert.True(timex.HourInList(ts, hours), "Go time in hour list.") assert.True(timex.HourInRange(ts, 20, 31), "Go time in hour range .") assert.True(timex.MinuteInList(ts, minutes), "Go time in minute list.") assert.True(timex.MinuteInRange(ts, 0, 5), "Go time in minute range .") assert.True(timex.SecondInList(ts, seconds), "Go time in second list.") assert.True(timex.SecondInRange(ts, 0, 5), "Go time in second range .") assert.True(timex.WeekdayInList(ts, weekdays), "Go time in weekday list.") assert.True(timex.WeekdayInRange(ts, time.Monday, time.Friday), "Go time in weekday range .") }
// TestRingBufferPop tests the popping of values. func TestRingBufferPop(t *testing.T) { assert := audit.NewTestingAssertion(t, true) rb := collections.NewRingBuffer(10) assert.Equal(rb.Cap(), 10) assert.Length(rb, 0) rb.Push(1, "alpha", nil, true) assert.Length(rb, 4) assert.Equal(rb.String(), "[1]->[alpha]->[<nil>]->[true]") tests := []struct { value interface{} ok bool length int }{ {1, true, 3}, {"alpha", true, 2}, {nil, true, 1}, {true, true, 0}, {nil, false, 0}, } for _, test := range tests { v, ok := rb.Pop() assert.Equal(v, test.value) assert.Equal(ok, test.ok) assert.Length(rb, test.length) } rb.Push(2, "beta") assert.Equal(rb.Cap(), 10) assert.Length(rb, 2) }
func TestSScan(t *testing.T) { assert := audit.NewTestingAssertion(t, true) conn, restore := connectDatabase(assert) defer restore() for i := 97; i < 123; i++ { for j := 97; j < 123; j++ { value := string([]byte{byte(i), byte(j)}) conn.Do("sadd", "scan-set", value) } } cursor, result, err := conn.DoScan("sscan", "scan-set", 0, "match", "*", "count", 5) assert.Nil(err) assert.True(cursor != 0) assert.True(result.Len() > 0) loopCursor := 0 loopCount := 0 valueCount := 0 for { cursor, result, err := conn.DoScan("sscan", "scan-set", loopCursor, "match", "*", "count", 5) assert.Nil(err) loopCount += 1 valueCount += result.Len() if cursor == 0 { break } loopCursor = cursor } assert.True(loopCount > 1) assert.Equal(valueCount, 26*26) }
// TestTreeDo tests the iteration over the tree nodes. func TestTreeDo(t *testing.T) { assert := audit.NewTestingAssertion(t, true) tree := collections.NewTree("root", true) err := tree.At("root").Add("alpha") assert.Nil(err) err = tree.At("root").Add("bravo") assert.Nil(err) err = tree.At("root", "bravo").Add("foo") assert.Nil(err) err = tree.At("root", "bravo").Add("bar") assert.Nil(err) err = tree.At("root").Add("bravo") assert.Nil(err) err = tree.At("root").Add("charlie") assert.Nil(err) err = tree.Create("root", "delta", 1).Add(true) assert.Nil(err) err = tree.Create("root", "delta", 2).Add(false) assert.Nil(err) // Test iteration. var values []interface{} err = tree.DoAll(func(v interface{}) error { values = append(values, v) return nil }) assert.Nil(err) assert.Length(values, 12) err = tree.DoAll(func(v interface{}) error { return errors.New("ouch") }) assert.ErrorMatch(err, ".* cannot perform function on all nodes: ouch") }
// TestAsFloat64 checks the access of float64 values. func TestAsFloat64(t *testing.T) { assert := audit.NewTestingAssertion(t, true) maxFloat64S := strconv.FormatFloat(math.MaxFloat64, 'e', -1, 64) minFloat64S := strconv.FormatFloat(-1*math.MaxFloat64, 'e', -1, 64) d := stringex.NewDefaulter("AsFloat4", true) tests := []struct { v valuer dv float64 expected float64 }{ {valuer{"0.0", false}, 0.0, 0.0}, {valuer{"1.0", false}, 0.0, 1.0}, {valuer{"-1.0", false}, 0.0, -1.0}, {valuer{maxFloat64S, false}, 0.0, math.MaxFloat64}, {valuer{minFloat64S, false}, 0.0, math.MaxFloat64 * -1.0}, {valuer{"9e+999", false}, 1.0, 1.0}, {valuer{"-9e+999", false}, 1.0, 1.0}, {valuer{"one.two", false}, 1.0, 1.0}, {valuer{"1.0", true}, 2.0, 2.0}, {valuer{"-1.0", true}, -2.0, -2.0}, } for i, test := range tests { assert.Logf("test %v %d: %v and default %v", d, i, test.v, test.dv) bv := d.AsFloat64(test.v, test.dv) assert.Equal(bv, test.expected) } }
// TestAsStringMap checks the access of string map values. func TestAsStringMap(t *testing.T) { assert := audit.NewTestingAssertion(t, true) d := stringex.NewDefaulter("AsStringMap", true) tests := []struct { v valuer rsep string kvsep string dv map[string]string expected map[string]string }{ {valuer{"a:1/b:2", false}, "/", ":", map[string]string{"a": "1"}, map[string]string{"a": "1", "b": "2"}}, {valuer{"a:1/b:2", true}, "/", ":", map[string]string{"a": "1"}, map[string]string{"a": "1"}}, {valuer{"a:1/b:2", false}, "/", ":", nil, map[string]string{"a": "1", "b": "2"}}, {valuer{"a:1/b:2", true}, "/", ":", nil, nil}, {valuer{"", false}, "/", ":", nil, map[string]string{"": ""}}, {valuer{"", true}, "/", ":", map[string]string{"a": "1"}, map[string]string{"a": "1"}}, {valuer{"a:1/b:2", false}, "|", "=", nil, map[string]string{"a:1/b:2": "a:1/b:2"}}, } for i, test := range tests { assert.Logf("test %v %d: %v and default %v", d, i, test.v, test.dv) sv := d.AsStringMap(test.v, test.rsep, test.kvsep, test.dv) assert.Equal(sv, test.expected) } }
// TestAsInt64 checks the access of int64 values. func TestAsInt64(t *testing.T) { assert := audit.NewTestingAssertion(t, true) maxInt64S := strconv.FormatInt(math.MaxInt64, 10) minInt64S := strconv.FormatInt(math.MinInt64, 10) d := stringex.NewDefaulter("AsInt64", true) tests := []struct { v valuer dv int64 expected int64 }{ {valuer{"0", false}, 0, 0}, {valuer{"1", false}, 0, 1}, {valuer{"-1", false}, 0, -1}, {valuer{maxInt64S, false}, 0, math.MaxInt64}, {valuer{minInt64S, false}, 0, math.MinInt64}, {valuer{"999999999999999999999", false}, 1, 1}, {valuer{"-999999999999999999999", false}, 1, 1}, {valuer{"one two three", false}, 1, 1}, {valuer{"1", true}, 2, 2}, {valuer{"-1", true}, -2, -2}, } for i, test := range tests { assert.Logf("test %v %d: %v and default %v", d, i, test.v, test.dv) bv := d.AsInt64(test.v, test.dv) assert.Equal(bv, test.expected) } }
// TestAsBool checks the access of bool values. func TestAsBool(t *testing.T) { assert := audit.NewTestingAssertion(t, true) d := stringex.NewDefaulter("AsBool", true) tests := []struct { v valuer dv bool expected bool }{ {valuer{"1", false}, false, true}, {valuer{"t", false}, false, true}, {valuer{"T", false}, false, true}, {valuer{"TRUE", false}, false, true}, {valuer{"true", false}, false, true}, {valuer{"True", false}, false, true}, {valuer{"wahr", false}, true, true}, {valuer{"", true}, true, true}, {valuer{"0", false}, true, false}, {valuer{"f", false}, true, false}, {valuer{"F", false}, true, false}, {valuer{"FALSE", false}, true, false}, {valuer{"false", false}, true, false}, {valuer{"False", false}, true, false}, {valuer{"falsch", false}, false, false}, {valuer{"", true}, false, false}, } for i, test := range tests { assert.Logf("test %v %d: %v and default %v", d, i, test.v, test.dv) bv := d.AsBool(test.v, test.dv) assert.Equal(bv, test.expected) } }
// TestRouterBehavior tests the router behavior. func TestRouterBehavior(t *testing.T) { assert := audit.NewTestingAssertion(t, true) env := cells.NewEnvironment("router-behavior") defer env.Stop() rf := func(emitterID, subscriberID string, event cells.Event) (bool, error) { ok := strings.Contains(event.Topic(), subscriberID) return ok, nil } env.StartCell("router", behaviors.NewRouterBehavior(rf)) env.StartCell("test-1", behaviors.NewCollectorBehavior(10)) env.StartCell("test-2", behaviors.NewCollectorBehavior(10)) env.StartCell("test-3", behaviors.NewCollectorBehavior(10)) env.StartCell("test-4", behaviors.NewCollectorBehavior(10)) env.StartCell("test-5", behaviors.NewCollectorBehavior(10)) env.Subscribe("router", "test-1", "test-2", "test-3", "test-4", "test-5") env.EmitNew("router", "test-1:test-2", "a") env.EmitNew("router", "test-1:test-2:test-3", "b") env.EmitNew("router", "test-3:test-4:test-5", "c") time.Sleep(100 * time.Millisecond) test := func(id string, length int) { collected, err := env.Request(id, cells.CollectedTopic, nil, cells.DefaultTimeout) assert.Nil(err) assert.Length(collected, length) } test("test-1", 2) test("test-2", 2) test("test-3", 2) test("test-4", 1) test("test-5", 1) }
// TestText tests the generation of text. func TestText(t *testing.T) { assert := audit.NewTestingAssertion(t, true) gen := audit.NewGenerator(audit.SimpleRand()) for i := 0; i < 10000; i++ { s := gen.Sentence() ws := strings.Split(s, " ") lws := len(ws) assert.True(2 <= lws && lws <= 15, info("SL: %d", lws)) assert.True('A' <= s[0] && s[0] <= 'Z', info("SUC: %v", s[0])) } for i := 0; i < 10000; i++ { p := gen.Paragraph() ss := strings.Split(p, ". ") lss := len(ss) assert.True(2 <= lss && lss <= 10, info("PL: %d", lss)) for _, s := range ss { ws := strings.Split(s, " ") lws := len(ws) assert.True(2 <= lws && lws <= 15, info("PSL: %d", lws)) assert.True('A' <= s[0] && s[0] <= 'Z', info("PSUC: %v", s[0])) } } }
// Test the MapReduce function with a scenario, where orders are analyzed // and a list of the analyzed articles will be returned func TestMapReduce(t *testing.T) { assert := audit.NewTestingAssertion(t, true) // Create MapReducer and let the show begin. mr := &OrderMapReducer{200000, make(map[int][]*OrderItem), make(map[string]*OrderItemAnalysis), assert} err := mapreduce.MapReduce(mr) // Asserts. assert.Nil(err) assert.Equal(len(mr.items), len(mr.analyses), "all items are analyzed") for _, analysis := range mr.analyses { quantity := 0 amount := 0.0 discount := 0.0 items := mr.items[analysis.ArticleNo] for _, item := range items { unitDiscount := (item.UnitPrice / 100.0) * item.DiscountPerc totalDiscount := unitDiscount * float64(item.Count) totalAmount := (item.UnitPrice - unitDiscount) * float64(item.Count) quantity += item.Count amount += totalAmount discount += totalDiscount } assert.Equal(quantity, analysis.Quantity, "quantity per article") assert.About(amount, analysis.Amount, 0.01, "amount per article") assert.About(discount, analysis.Discount, 0.01, "discount per article") } }
// TestConfigurationRead tests the successful reading of a configuration. func TestConfigurationRead(t *testing.T) { assert := audit.NewTestingAssertion(t, true) env := cells.NewEnvironment("configuration-read") defer env.Stop() tempDir, filename := createConfigurationFile(assert, "{etc {foo 42}}") defer tempDir.Restore() sigc := audit.MakeSigChan() spf := func(c cells.Cell, event cells.Event) error { if event.Topic() == behaviors.ConfigurationTopic { cfg := behaviors.Configuration(event) v := cfg.ValueAsString("foo", "0815") assert.Equal(v, "42") sigc <- true } return nil } env.StartCell("configurator", behaviors.NewConfiguratorBehavior(nil)) env.StartCell("simple", behaviors.NewSimpleProcessorBehavior(spf)) env.Subscribe("configurator", "simple") pvs := cells.PayloadValues{ behaviors.ConfigurationFilenamePayload: filename, } env.EmitNew("configurator", behaviors.ReadConfigurationTopic, pvs) assert.Wait(sigc, true, 100*time.Millisecond) }
// TestFileServeHandler tests the serving of files. func TestFileServeHandler(t *testing.T) { assert := audit.NewTestingAssertion(t, true) // Setup the test file. dir, err := ioutil.TempDir("", "gont-web") assert.Nil(err) defer os.RemoveAll(dir) filename := filepath.Join(dir, "foo.txt") f, err := os.Create(filename) assert.Nil(err) _, err = f.WriteString("Been there, done that!") assert.Nil(err) assert.Logf("written %s", f.Name()) err = f.Close() assert.Nil(err) // Setup the test server. mux, ts, err := web.StartTestServer() assert.Nil(err) defer ts.Close() err = mux.Register("test", "files", web.NewFileServeHandler("files", dir)) assert.Nil(err) // Perform test requests. resp, err := web.DoTestRequest(ts, &web.TestRequest{ Method: "GET", Path: "/test/files/foo.txt", }) assert.Nil(err) assert.Equal(string(resp.Body), "Been there, done that!") resp, err = web.DoTestRequest(ts, &web.TestRequest{ Method: "GET", Path: "/test/files/does.not.exist", }) assert.Nil(err) assert.Equal(string(resp.Body), "404 page not found\n") }
// Test polynomial function differentiation. func TestPolynomialFunctionDifferentiation(t *testing.T) { assert := audit.NewTestingAssertion(t, true) p := NewPolynomialFunction([]float64{1.0, 2.0, 1.0, 3.0}) dp := p.Differentiate() // Asserts. assert.Equal(dp.String(), "f(x) := 9x^2+2x+2") }
// TestRateBehavior tests the event rate behavior. func TestRateBehavior(t *testing.T) { assert := audit.NewTestingAssertion(t, true) env := cells.NewEnvironment("rate-behavior") defer env.Stop() matches := func(event cells.Event) bool { return event.Topic() == "now" } topics := []string{"a", "b", "c", "d", "e", "f", "g", "h", "i", "now"} env.StartCell("rater", behaviors.NewRateBehavior(matches, 5)) env.StartCell("collector", behaviors.NewCollectorBehavior(1000)) env.Subscribe("rater", "collector") for i := 0; i < 1000; i++ { topic := topics[rand.Intn(len(topics))] env.EmitNew("rater", topic, nil) time.Sleep(time.Duration(rand.Intn(3)) * time.Millisecond) } collected, err := env.Request("collector", cells.CollectedTopic, nil, cells.DefaultTimeout) assert.Nil(err) events := collected.([]behaviors.EventData) assert.True(len(events) <= 1000) for _, event := range events { assert.Equal(event.Topic, "event-rate!") _, ok := event.Payload.GetDuration(behaviors.EventRateAveragePayload) assert.True(ok) _, ok = event.Payload.GetDuration(behaviors.EventRateAveragePayload) assert.True(ok) _, ok = event.Payload.GetDuration(behaviors.EventRateLowPayload) assert.True(ok) } }
// TestFilterBehavior tests the filter behavior. func TestFilterBehavior(t *testing.T) { assert := audit.NewTestingAssertion(t, true) env := cells.NewEnvironment("filter-behavior") defer env.Stop() ff := func(id string, event cells.Event) bool { dp, ok := event.Payload().Get(cells.DefaultPayload) if !ok { return false } payload := dp.(string) return event.Topic() == payload } env.StartCell("filter", behaviors.NewFilterBehavior(ff)) env.StartCell("collector", behaviors.NewCollectorBehavior(10)) env.Subscribe("filter", "collector") env.EmitNew("filter", "a", "a", nil) env.EmitNew("filter", "a", "b", nil) env.EmitNew("filter", "b", "b", nil) time.Sleep(100 * time.Millisecond) collected, err := env.Request("collector", cells.CollectedTopic, nil, nil, cells.DefaultTimeout) assert.Nil(err) assert.Length(collected, 2, "two collected events") }
// Test encoding and decoding a doc. func TestEncodeDecode(t *testing.T) { assert := audit.NewTestingAssertion(t, true) a1 := &atom.Feed{ XMLNS: atom.XMLNS, Id: "http://tideland.biz/feed/atom", Title: &atom.Text{"Test Encode/Decode", "", "text"}, Updated: atom.ComposeTime(time.Now()), Entries: []*atom.Entry{ { Id: "http://tideland.biz/feed/atom/1", Title: &atom.Text{"Entry 1", "", "text"}, Updated: atom.ComposeTime(time.Now()), }, { Id: "http://tideland.biz/feed/atom/2", Title: &atom.Text{"Entry 2", "", "text"}, Updated: atom.ComposeTime(time.Now()), }, }, } b := &bytes.Buffer{} err := atom.Encode(b, a1) assert.Nil(err, "Encoding returns no error.") assert.Substring(`<title type="text">Test Encode/Decode</title>`, b.String(), "Title has been encoded correctly.") a2, err := atom.Decode(b) assert.Nil(err, "Decoding returns no error.") assert.Equal(a2.Title.Text, "Test Encode/Decode", "Title has been decoded correctly.") assert.Length(a2.Entries, 2, "Decoded feed has the right number of items.") }
// TestSimpleNoTimeout tests a simple scene usage without // any timeout. func TestSimpleNoTimeout(t *testing.T) { assert := audit.NewTestingAssertion(t, false) scn := scene.Start() id := scn.ID() assert.Length(id, 16) err := scn.Store("foo", 4711) assert.Nil(err) foo, err := scn.Fetch("foo") assert.Nil(err) assert.Equal(foo, 4711) _, err = scn.Fetch("bar") assert.True(scene.IsPropNotFoundError(err)) err = scn.Store("foo", "bar") assert.True(scene.IsPropAlreadyExistError(err)) _, err = scn.Dispose("bar") assert.True(scene.IsPropNotFoundError(err)) foo, err = scn.Dispose("foo") assert.Nil(err) assert.Equal(foo, 4711) _, err = scn.Fetch("foo") assert.True(scene.IsPropNotFoundError(err)) status, err := scn.Status() assert.Nil(err) assert.Equal(status, scene.Active) err = scn.Stop() assert.Nil(err) status, err = scn.Status() assert.Nil(err) assert.Equal(status, scene.Over) }
// Test of the ETM monitor. func TestEtmMonitor(t *testing.T) { assert := audit.NewTestingAssertion(t, true) // Generate measurings. for i := 0; i < 500; i++ { n := rand.Intn(10) id := fmt.Sprintf("mp:task:%d", n) m := monitoring.BeginMeasuring(id) work(n * 5000) m.EndMeasuring() } // Need some time to let that backend catch up queued mesurings. time.Sleep(time.Millisecond) // Asserts. mp, err := monitoring.ReadMeasuringPoint("foo") assert.ErrorMatch(err, `.* measuring point "foo" does not exist`) mp, err = monitoring.ReadMeasuringPoint("mp:task:5") assert.Nil(err, "No error expected.") assert.Equal(mp.Id, "mp:task:5", "should get the right one") assert.True(mp.Count > 0, "should be measured several times") assert.Match(mp.String(), `Measuring Point "mp:task:5" \(.*\)`, "string representation should look fine") monitoring.MeasuringPointsDo(func(mp *monitoring.MeasuringPoint) { assert.Match(mp.Id, "mp:task:[0-9]", "id has to match the pattern") assert.True(mp.MinDuration <= mp.AvgDuration && mp.AvgDuration <= mp.MaxDuration, "avg should be somewhere between min and max") }) }
// TestFlagTimeout tests the waiting for a signal with // a timeout. func TestFlagTimeout(t *testing.T) { assert := audit.NewTestingAssertion(t, false) scn := scene.Start() go func() { err := scn.WaitFlag("foo") assert.Nil(err) err = scn.Store("foo-a", true) assert.Nil(err) }() go func() { err := scn.WaitFlagLimited("foo", 50*time.Millisecond) assert.True(scene.IsWaitedTooLongError(err)) err = scn.Store("foo-b", true) assert.Nil(err) }() time.Sleep(100 * time.Millisecond) err := scn.Flag("foo") assert.Nil(err) fooA, err := scn.Fetch("foo-a") assert.Nil(err) assert.Equal(fooA, true) fooB, err := scn.Fetch("foo-b") assert.Nil(err) assert.Equal(fooB, true) err = scn.Stop() assert.Nil(err) }
func TestStripTags(t *testing.T) { assert := audit.NewTestingAssertion(t, true) in := "<p>The quick brown <b>fox</b> jumps over the lazy <em>dog</em>.</p>" out, err := utils.StripTags(in, true, false) assert.Nil(err, "No error during stripping.") assert.Equal(out, "The quick brown fox jumps over the lazy dog .", "Tags have been removed.") in = "<p>The quick brown <b>fox</b> jumps over the lazy <em>dog.</p>" out, err = utils.StripTags(in, true, false) assert.ErrorMatch(err, `XML syntax error on line 1.*`, "Error in document detected.") in = "<p>The quick brown <b>fox</b> jumps over the lazy <em>dog.</p>" out, err = utils.StripTags(in, false, false) assert.Nil(err, "No error during stripping.") assert.Equal(out, "The quick brown fox jumps over the lazy dog.", "Tags have been removed.") in = "<p>The quick brown <b>fox & goose</b> jump over the lazy <em>dog</em>.</p>" out, err = utils.StripTags(in, true, false) assert.Nil(err, "No error during stripping.") assert.Equal(out, "The quick brown fox & goose jump over the lazy <em>dog</em>.", "Tags have been removed.") in = "<p>The quick brown <b>fox &amp; goose</b> jump over the lazy <em>dog</em>.</p>" out, err = utils.StripTags(in, true, true) assert.Nil(err, "No error during stripping.") assert.Equal(out, "The quick brown fox & goose jump over the lazy dog .", "Tags have been removed.") }
// TestCallbackBehavior tests the callback behavior. func TestCallbackBehavior(t *testing.T) { assert := audit.NewTestingAssertion(t, true) env := cells.NewEnvironment("callback-behavior") defer env.Stop() cbdA := []string{} cbfA := func(topic string, payload cells.Payload) error { cbdA = append(cbdA, topic) return nil } cbdB := 0 cbfB := func(topic string, payload cells.Payload) error { cbdB++ return nil } sigc := audit.MakeSigChan() cbfC := func(topic string, payload cells.Payload) error { if topic == "baz" { sigc <- true } return nil } env.StartCell("callback", behaviors.NewCallbackBehavior(cbfA, cbfB, cbfC)) env.EmitNew("callback", "foo", nil, nil) env.EmitNew("callback", "bar", nil, nil) env.EmitNew("callback", "baz", nil, nil) assert.Wait(sigc, true, time.Second) assert.Equal(cbdA, []string{"foo", "bar", "baz"}) assert.Equal(cbdB, 3) }
// TestPattern tests the generation based on patterns. func TestPattern(t *testing.T) { assert := audit.NewTestingAssertion(t, true) gen := audit.NewGenerator(audit.SimpleRand()) assertPattern := func(pattern, runes string) { set := make(map[rune]bool) for _, r := range runes { set[r] = true } for i := 0; i < 10; i++ { result := gen.Pattern(pattern) for _, r := range result { assert.True(set[r], pattern, result, runes) } } } assertPattern("^^", "^") assertPattern("^0^0^0^0^0", "0123456789") assertPattern("^1^1^1^1^1", "123456789") assertPattern("^o^o^o^o^o", "01234567") assertPattern("^h^h^h^h^h", "0123456789abcdef") assertPattern("^H^H^H^H^H", "0123456789ABCDEF") assertPattern("^a^a^a^a^a", "abcdefghijklmnopqrstuvwxyz") assertPattern("^A^A^A^A^A", "ABCDEFGHIJKLMNOPQRSTUVWXYZ") assertPattern("^c^c^c^c^c", "bcdfghjklmnpqrstvwxyz") assertPattern("^C^C^C^C^C", "BCDFGHJKLMNPQRSTVWXYZ") assertPattern("^v^v^v^v^v", "aeiou") assertPattern("^V^V^V^V^V", "AEIOU") assertPattern("^z^z^z^z^z", "abcdefghijklmnopqrstuvwxyz0123456789") assertPattern("^Z^Z^Z^Z^Z", "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789") assertPattern("^1^0.^0^0^0,^0^0 €", "0123456789 .,€") }
// TestEnvironmentScenario tests creating and using the // environment in a simple way. func TestEnvironmentScenario(t *testing.T) { assert := audit.NewTestingAssertion(t, true) env := cells.NewEnvironment("scenario") defer env.Stop() err := env.StartCell("foo", newCollectBehavior()) assert.Nil(err) err = env.StartCell("bar", newCollectBehavior()) assert.Nil(err) err = env.StartCell("collector", newCollectBehavior()) assert.Nil(err) err = env.Subscribe("foo", "bar") assert.Nil(err) err = env.Subscribe("bar", "collector") assert.Nil(err) err = env.EmitNew("foo", "lorem", 4711, nil) assert.Nil(err) err = env.EmitNew("foo", "ipsum", 1234, nil) assert.Nil(err) response, err := env.Request("foo", cells.PingTopic, nil, nil, cells.DefaultTimeout) assert.Nil(err) assert.Equal(response, cells.PongResponse) time.Sleep(200 * time.Millisecond) collected, err := env.Request("collector", cells.ProcessedTopic, nil, nil, cells.DefaultTimeout) assert.Nil(err) assert.Length(collected, 2, "two collected events") assert.Contents(`<topic: "lorem" / payload: <"default": 4711>>`, collected) assert.Contents(`<topic: "ipsum" / payload: <"default": 1234>>`, collected) }
// TestSML2XML checks the conversion from SML to XML. func TestSML2XML(t *testing.T) { assert := audit.NewTestingAssertion(t, true) in := `{html {head {title A test document}} {body {h1:title A test document} {p:intro:preface The is a simple sentence with an {em emphasized} and a {strong strong} text. We'll see how it renders.} {ul {li:1 It should be nice.} {li:2 It should be error free.} {li:3 It should be fast.} } {! for foo := 0; foo < 42; foo++ { println(foo) } !} }}` builder := sml.NewNodeBuilder() err := sml.ReadSML(strings.NewReader(in), builder) assert.Nil(err) root, err := builder.Root() assert.Nil(err) buf := bytes.NewBufferString("") ctx := sml.NewWriterContext(sml.NewXMLWriter("pre"), buf, true, " ") ctx.Register("li", newLIWriter()) sml.WriteSML(root, ctx) assert.Logf("===== XML =====") assert.Logf(buf.String()) assert.Logf("===== DONE =====") }