// TestBox tests the box usage. func TestEventBox(t *testing.T) { assert := asserts.NewTestingAsserts(t, true) inbox := newBox() assert.Equal(inbox.len(), 0, "box is empty") inbox.push(EventMessage(EmptyPayload, "Event", 1)) inbox.push(EventMessage(EmptyPayload, "Event", 2)) inbox.push(EventMessage(EmptyPayload, "Event", 3)) assert.Equal(inbox.len(), 3, "box has right length") assert.Equal(inbox.pop().event.Topic(), Id("Event", 1), "first event") assert.Equal(inbox.pop().event.Topic(), Id("Event", 2), "second event") assert.Equal(inbox.pop().event.Topic(), Id("Event", 3), "third event") go func() { assert.Equal(inbox.pop().event.Topic(), Id("Event", 4), "fourth event") inbox.push(EventMessage(EmptyPayload, "Event", 5)) }() inbox.push(EventMessage(EmptyPayload, "Event", 4)) time.Sleep(100 * time.Millisecond) assert.Equal(inbox.pop().event.Topic(), Id("Event", 5), "fifth event") }
func TestHookRPC(t *testing.T) { assert := asserts.NewTestingAsserts(t, true) // Create the UI to test h := new(packer.MockHook) // Serve server := rpc.NewServer() RegisterHook(server, h) address := serveSingleConn(server) // Create the client over RPC and run some methods to verify it works client, err := rpc.Dial("tcp", address) assert.Nil(err, "should be able to connect") hClient := Hook(client) // Test Run ui := &testUi{} hClient.Run("foo", ui, nil, 42) assert.True(h.RunCalled, "run should be called") // Test Cancel hClient.Cancel() assert.True(h.CancelCalled, "cancel should be called") }
// Test of the ETM monitor. func TestEtmMonitor(t *testing.T) { assert := asserts.NewTestingAsserts(t, true) // Generate measurings. for i := 0; i < 500; i++ { n := rand.Intn(10) id := fmt.Sprintf("mp:task:%d", n) m := BeginMeasuring(id) work(n * 5000) m.EndMeasuring() } // Need some time to let that backend catch up queued mesurings. time.Sleep(1e7) // Asserts. mp, err := ReadMeasuringPoint("foo") assert.ErrorMatch(err, `measuring point "foo" does not exist`, "Reading non-existent measuring point.") mp, err = 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.") MeasuringPointsDo(func(mp *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.") }) }
func TestBlockDevice(t *testing.T) { assert := asserts.NewTestingAsserts(t, true) ec2Mapping := []ec2.BlockDeviceMapping{ ec2.BlockDeviceMapping{ DeviceName: "/dev/sdb", VirtualName: "ephemeral0", SnapshotId: "snap-1234", VolumeType: "standard", VolumeSize: 8, DeleteOnTermination: true, IOPS: 1000, }, } blockDevice := BlockDevice{ DeviceName: "/dev/sdb", VirtualName: "ephemeral0", SnapshotId: "snap-1234", VolumeType: "standard", VolumeSize: 8, DeleteOnTermination: true, IOPS: 1000, } blockDevices := BlockDevices{ AMIMappings: []BlockDevice{blockDevice}, LaunchMappings: []BlockDevice{blockDevice}, } assert.Equal(ec2Mapping, blockDevices.BuildAMIDevices(), "should match output") assert.Equal(ec2Mapping, blockDevices.BuildLaunchDevices(), "should match output") }
func TestProvisionerRPC(t *testing.T) { assert := asserts.NewTestingAsserts(t, true) // Create the interface to test p := new(testProvisioner) // Start the server server := rpc.NewServer() RegisterProvisioner(server, p) address := serveSingleConn(server) // Create the client over RPC and run some methods to verify it works client, err := rpc.Dial("tcp", address) assert.Nil(err, "should be able to connect") // Test Prepare config := 42 pClient := Provisioner(client) pClient.Prepare(config) assert.True(p.prepareCalled, "prepare should be called") assert.Equal(p.prepareConfigs, []interface{}{42}, "prepare should be called with right arg") // Test Provision ui := &testUi{} comm := new(packer.MockCommunicator) pClient.Provision(ui, comm) assert.True(p.provCalled, "provision should be called") p.provUi.Say("foo") assert.True(ui.sayCalled, "say should be called") }
// TestDuration tests time.Duration values. func TestDuration(t *testing.T) { assert := asserts.NewTestingAsserts(t, true) provider := config.NewMapConfigurationProvider() cfg := config.New(provider) cfg.Set("alpha", "0") cfg.Set("bravo", 5*time.Second) cfg.Set("charlie", "4711ms") // Successful gets. value, err := cfg.GetDuration("alpha") assert.Nil(err, "No error.") assert.Equal(value, 0*time.Second, "Right value 'alpha' returned.") value, err = cfg.GetDuration("bravo") assert.Nil(err, "No error.") assert.Equal(value, 5*time.Second, "Right value 'bravo' returned.") value, err = cfg.GetDuration("charlie") assert.Nil(err, "No error.") assert.Equal(value, 4711*time.Millisecond, "Right value 'charlie' returned.") // Illegal format. cfg.Set("illegal-format", true) _, err = cfg.GetDuration("illegal-format") assert.ErrorMatch(err, `invalid type "duration" for "true" (.*)`, "Right error returned.") // Non-existing key. _, err = cfg.GetDuration("non-existing-key") assert.ErrorMatch(err, `key "non-existing-key" does not exist`, "Right error returned.") // Non-existing key with default. value, err = cfg.GetDurationDefault("non-existing-key", 5*time.Hour) assert.Nil(err, "No error.") assert.Equal(value, 5*time.Hour, "Right value 'non-existing-key' returned.") }
// TestFloat64 tests float64 values. func TestFloat64(t *testing.T) { assert := asserts.NewTestingAsserts(t, true) provider := config.NewMapConfigurationProvider() cfg := config.New(provider) cfg.Set("alpha", 4711) cfg.Set("bravo", -47.11) cfg.Set("charlie", 0.0) // Successful gets. value, err := cfg.GetFloat64("alpha") assert.Nil(err, "No error.") assert.Equal(value, float64(4711), "Right value 'alpha' returned.") value, err = cfg.GetFloat64("bravo") assert.Nil(err, "No error.") assert.Equal(value, float64(-47.11), "Right value 'bravo' returned.") value, err = cfg.GetFloat64("charlie") assert.Nil(err, "No error.") assert.Equal(value, float64(0), "Right value 'charlie' returned.") // Illegal format. cfg.Set("illegal-format", true) _, err = cfg.GetFloat64("illegal-format") assert.ErrorMatch(err, `invalid type "float64" for "true" (.*)`, "Right error returned.") // Non-existing key. _, err = cfg.GetFloat64("non-existing-key") assert.ErrorMatch(err, `key "non-existing-key" does not exist`, "Right error returned.") // Non-existing key with default. value, err = cfg.GetFloat64Default("non-existing-key", 47.11) assert.Nil(err, "No error.") assert.Equal(value, float64(47.11), "Right value 'non-existing-key' returned.") }
// Test negative reading. func TestSMLNegativeReading(t *testing.T) { assert := asserts.NewTestingAsserts(t, true) sml := "{Foo {bar:1 Yadda {test} {} 1} {bar:2 Yadda 2}}" builder := markup.NewNodeBuilder() err := markup.ReadSML(strings.NewReader(sml), builder) assert.ErrorMatch(err, "invalid rune.*", "Invalid rune should be found.") }
// TestIntList tests the usage of int lists. func TestIntList(t *testing.T) { assert := asserts.NewTestingAsserts(t, true) values := worm.Ints{1, 5, 6, 2, 5, 2, 9} i := worm.NewIntList(values) // Test length. assert.Length(i, 7, "correct length") // Tast retrieving the values. values = i.Values() assert.Length(values, 7, "correct length") assert.Equal(values, worm.Ints{1, 5, 6, 2, 5, 2, 9}, "values are right") // Tast retrieving the values sorted. values = i.SortedValues() assert.Length(values, 7, "correct length") assert.Equal(values, worm.Ints{1, 2, 2, 5, 5, 6, 9}, "values are right") // Test containing test. // assert.True(i.Contains(), "emtpy values are ok") // assert.True(i.Contains(6, 5), "values detected") // assert.False(i.Contains(1, 2, 7), "invalid values recognized") // Test appending more values. av := worm.Ints{2, 6, 1001, 1010, 1005} ai := i.Append(av) assert.Length(ai, i.Len()+5, "five more values in the new list") }
func TestStripTags(t *testing.T) { assert := asserts.NewTestingAsserts(t, true) in := "<p>The quick brown <b>fox</b> jumps over the lazy <em>dog</em>.</p>" out, err := net.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 = net.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 = net.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 = net.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 = net.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.") }
// Test encoding and decoding a doc. func TestEncodeDecode(t *testing.T) { assert := asserts.NewTestingAsserts(t, true) a1 := &atom.Feed{ XMLNS: atom.XMLNS, Id: "http://tideland.biz/pkg/net/atom", Title: &atom.Text{"Test Encode/Decode", "", "text"}, Updated: atom.ComposeTime(time.Now()), Entries: []*atom.Entry{ { Id: "http://tideland.bi/pkg/net/atom/entry-1", Title: &atom.Text{"Entry 1", "", "text"}, Updated: atom.ComposeTime(time.Now()), }, { Id: "http://tideland.bi/pkg/net/atom/entry-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(b.String(), `<title type="text">Test Encode/Decode</title>`, "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.") }
// TestCounterBehavior tests the counting of events // by the counter behavior. func TestCounterBehavior(t *testing.T) { assert := asserts.NewTestingAsserts(t, true) cf := func(e Event) []string { return []string{e.Topic()} } env := NewEnvironment("counter-behavior") env.AddCell("counter", NewCounterBehaviorFactory(cf)) env.AddCell("collector", CollectorBehaviorFactory) env.Subscribe("counter", "collector") env.EmitSimple("counter", "a", true) env.EmitSimple("counter", "b", true) env.EmitSimple("counter", "c", true) env.EmitSimple("counter", "a", true) time.Sleep(100 * time.Millisecond) b, _ := env.CellBehavior("collector") collector := b.(EventCollector) events := collector.Events() assert.Equal(events[0].Payload().(int64), int64(1), "First result is ok.") assert.Equal(events[1].Payload().(int64), int64(1), "Second result is ok.") assert.Equal(events[2].Payload().(int64), int64(1), "Third result is ok.") assert.Equal(events[3].Payload().(int64), int64(2), "Fourth result is ok.") }
// TestFilterBehavior tests the filtering of events by the // filter behavior. func TestFilterBehavior(t *testing.T) { assert := asserts.NewTestingAsserts(t, true) ff := func(e Event) bool { if strings.Contains(e.Topic(), "yes") { return true } return false } env := NewEnvironment("filter-behavior") env.AddCell("filter", NewFilteredBroadcastBehaviorFactory(ff)) env.AddCell("collector", CollectorBehaviorFactory) env.Subscribe("filter", "collector") env.EmitSimple("filter", "yes", true) env.EmitSimple("filter", "no", true) env.EmitSimple("filter", "yes", true) time.Sleep(100 * time.Millisecond) b, _ := env.CellBehavior("collector") collector := b.(EventCollector) events := collector.Events() assert.Length(events, 2, "All events received") }
func TestUiRPC(t *testing.T) { assert := asserts.NewTestingAsserts(t, true) // Create the UI to test ui := new(testUi) // Start the RPC server server := rpc.NewServer() RegisterUi(server, ui) address := serveSingleConn(server) // Create the client over RPC and run some methods to verify it works client, err := rpc.Dial("tcp", address) if err != nil { panic(err) } uiClient := &Ui{client} // Basic error and say tests result, err := uiClient.Ask("query") assert.Nil(err, "should not error") assert.True(ui.askCalled, "ask should be called") assert.Equal(ui.askQuery, "query", "should be correct") assert.Equal(result, "foo", "should have correct result") uiClient.Error("message") assert.Equal(ui.errorMessage, "message", "message should be correct") uiClient.Message("message") assert.Equal(ui.messageMessage, "message", "message should be correct") uiClient.Say("message") assert.Equal(ui.sayMessage, "message", "message should be correct") }
// TestSimple tests simple value retrieved as string. func TestSimple(t *testing.T) { assert := asserts.NewTestingAsserts(t, true) provider := config.NewMapConfigurationProvider() cfg := config.New(provider) cfg.Set("alpha", "quick brown fox") cfg.Set("bravo", true) cfg.Set("charlie", 4711) cfg.Set("delta", 47.11) // Successful gets. value, err := cfg.Get("alpha") assert.Nil(err, "No error.") assert.Equal(value, "quick brown fox", "Right value 'alpha' returned.") value, err = cfg.Get("bravo") assert.Nil(err, "No error.") assert.Equal(value, "true", "Right value 'bravo' returned.") value, err = cfg.Get("charlie") assert.Nil(err, "No error.") assert.Equal(value, "4711", "Right value 'charlie' returned.") value, err = cfg.Get("delta") assert.Nil(err, "No error.") assert.Equal(value, "47.11", "Right value 'delta' returned.") // Non-existing key. _, err = cfg.Get("non-existing-key") assert.ErrorMatch(err, `key "non-existing-key" does not exist`, "Right error returned.") // Non-existing key with default. value, err = cfg.GetDefault("non-existing-key", "default value") assert.Nil(err, "No error.") assert.Equal(value, "default value", "Right value 'non-existing-key' returned.") }
// TestChildSupervisor tests a supervisor as a child. func TestChildSupervisor(t *testing.T) { assert := asserts.NewTestingAsserts(t, true) sup := supervisor.NewSupervisor("parent", supervisor.OneForAll, 3, time.Second) chsup, _ := sup.Supervisor("child", supervisor.OneForOne, 5, time.Second) st := newStarts() childA := func(h *supervisor.Handle) error { return methodChild(h, st) } childB := func(h *supervisor.Handle) error { return panicChild(h, st, shortWait) } sup.Go("alpha", childA) sup.Go("beta", childA) chsup.Go("gamma", childA) chsup.Go("delta", childA) chsup.Go("epsilon", childB) time.Sleep(2 * time.Second) err := sup.Stop() assert.Nil(err, "stopping parent of 'child-supervisor'") assert.Equal(st.count("alpha"), 4, "starts of 'alpha'") assert.Equal(st.count("beta"), 4, "starts of 'beta'") assert.Equal(st.count("gamma"), 4, "starts of 'gamma'") assert.Equal(st.count("delta"), 4, "starts of 'delta'") assert.True(st.count("epsilon") > 1, "starts of 'epsilon'") }
// TestTime tests time.Time values. func TestTime(t *testing.T) { assert := asserts.NewTestingAsserts(t, true) provider := config.NewMapConfigurationProvider() cfg := config.New(provider) now := time.Now() later := now.Add(12 * time.Hour) earlier := now.Add(-12 * time.Hour) cfg.Set("alpha", now) cfg.Set("bravo", later) // Successful gets. value, err := cfg.GetTime("alpha") assert.Nil(err, "No error.") assert.Equal(value, now, "Right value 'alpha' returned.") value, err = cfg.GetTime("bravo") assert.Nil(err, "No error.") assert.Equal(value, later, "Right value 'bravo' returned.") // Illegal format. cfg.Set("illegal-format", true) _, err = cfg.GetTime("illegal-format") assert.ErrorMatch(err, `invalid type "time" for "true" (.*)`, "Right error returned.") // Non-existing key. _, err = cfg.GetTime("non-existing-key") assert.ErrorMatch(err, `key "non-existing-key" does not exist`, "Right error returned.") // Non-existing key with default. value, err = cfg.GetTimeDefault("non-existing-key", earlier) assert.Nil(err, "No error.") assert.Equal(value, earlier, "Right value 'non-existing-key' returned.") }
func TestNewEnvironment_NoConfig(t *testing.T) { assert := asserts.NewTestingAsserts(t, true) env, err := NewEnvironment(nil) assert.Nil(env, "env should be nil") assert.NotNil(err, "should be an error") }
func TestBuildRPC(t *testing.T) { assert := asserts.NewTestingAsserts(t, true) // Create the interface to test b := new(testBuild) // Start the server server := rpc.NewServer() RegisterBuild(server, b) address := serveSingleConn(server) // Create the client over RPC and run some methods to verify it works client, err := rpc.Dial("tcp", address) assert.Nil(err, "should be able to connect") bClient := Build(client) // Test Name bClient.Name() assert.True(b.nameCalled, "name should be called") // Test Prepare bClient.Prepare() assert.True(b.prepareCalled, "prepare should be called") // Test Run cache := new(testCache) ui := new(testUi) artifacts, err := bClient.Run(ui, cache) assert.True(b.runCalled, "run should be called") assert.Nil(err, "should not error") assert.Equal(len(artifacts), 1, "should have one artifact") assert.Equal(artifacts[0].BuilderId(), "bid", "should have proper builder id") // Test the UI given to run, which should be fully functional if b.runCalled { b.runCache.Lock("foo") assert.True(cache.lockCalled, "lock should be called") b.runUi.Say("format") assert.True(ui.sayCalled, "say should be called") assert.Equal(ui.sayMessage, "format", "message should be correct") } // Test run with an error b.errRunResult = true _, err = bClient.Run(ui, cache) assert.NotNil(err, "should not nil") // Test SetDebug bClient.SetDebug(true) assert.True(b.setDebugCalled, "should be called") // Test SetForce bClient.SetForce(true) assert.True(b.setForceCalled, "should be called") // Test Cancel bClient.Cancel() assert.True(b.cancelCalled, "cancel should be called") }
// Test time containments. func TestTimeContainments(t *testing.T) { assert := asserts.NewTestingAsserts(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(YearInList(ts, years), "Go time in year list.") assert.True(YearInRange(ts, 2005, 2015), "Go time in year range.") assert.True(MonthInList(ts, months), "Go time in month list.") assert.True(MonthInRange(ts, 7, 12), "Go time in month range.") assert.True(DayInList(ts, days), "Go time in day list.") assert.True(DayInRange(ts, 5, 15), "Go time in day range .") assert.True(HourInList(ts, hours), "Go time in hour list.") assert.True(HourInRange(ts, 20, 31), "Go time in hour range .") assert.True(MinuteInList(ts, minutes), "Go time in minute list.") assert.True(MinuteInRange(ts, 0, 5), "Go time in minute range .") assert.True(SecondInList(ts, seconds), "Go time in second list.") assert.True(SecondInRange(ts, 0, 5), "Go time in second range .") assert.True(WeekdayInList(ts, weekdays), "Go time in weekday list.") assert.True(WeekdayInRange(ts, time.Monday, time.Friday), "Go time in weekday range .") }
func TestBuild_Prepare(t *testing.T) { assert := asserts.NewTestingAsserts(t, true) packerConfig := map[string]interface{}{ BuildNameConfigKey: "test", DebugConfigKey: false, ForceConfigKey: false, } build := testBuild() builder := build.builder.(*TestBuilder) build.Prepare() assert.True(builder.prepareCalled, "prepare should be called") assert.Equal(builder.prepareConfig, []interface{}{42, packerConfig}, "prepare config should be 42") coreProv := build.provisioners[0] prov := coreProv.provisioner.(*TestProvisioner) assert.True(prov.prepCalled, "prepare should be called") assert.Equal(prov.prepConfigs, []interface{}{42, packerConfig}, "prepare should be called with proper config") corePP := build.postProcessors[0][0] pp := corePP.processor.(*TestPostProcessor) assert.True(pp.configCalled, "config should be called") assert.Equal(pp.configVal, []interface{}{42, packerConfig}, "config should have right value") }
func TestBuild_Run(t *testing.T) { assert := asserts.NewTestingAsserts(t, true) cache := &TestCache{} ui := testUi() build := testBuild() build.Prepare(nil) artifacts, err := build.Run(ui, cache) assert.Nil(err, "should not error") assert.Equal(len(artifacts), 2, "should have two artifacts") // Verify builder was run builder := build.builder.(*TestBuilder) assert.True(builder.runCalled, "run should be called") // Verify hooks are disapatchable dispatchHook := builder.runHook dispatchHook.Run("foo", nil, nil, 42) hook := build.hooks["foo"][0].(*TestHook) assert.True(hook.runCalled, "run should be called") assert.Equal(hook.runData, 42, "should have correct data") // Verify provisioners run dispatchHook.Run(HookProvision, nil, nil, 42) prov := build.provisioners[0].provisioner.(*TestProvisioner) assert.True(prov.provCalled, "provision should be called") // Verify post-processor was run pp := build.postProcessors[0][0].processor.(*TestPostProcessor) assert.True(pp.ppCalled, "post processor should be called") }
func TestTemplate_BuildNames(t *testing.T) { assert := asserts.NewTestingAsserts(t, true) data := ` { "builders": [ { "name": "bob", "type": "amazon-ebs" }, { "name": "chris", "type": "another" } ] } ` result, err := ParseTemplate([]byte(data)) assert.Nil(err, "should not error") buildNames := result.BuildNames() sort.Strings(buildNames) assert.Equal(buildNames, []string{"bob", "chris"}, "should have proper builds") }
func TestTemplate_Build_NilBuilderFunc(t *testing.T) { assert := asserts.NewTestingAsserts(t, true) data := ` { "builders": [ { "name": "test1", "type": "test-builder" } ], "provisioners": [ { "type": "test-prov" } ] } ` template, err := ParseTemplate([]byte(data)) assert.Nil(err, "should not error") defer func() { p := recover() assert.NotNil(p, "should panic") if p != nil { assert.Equal(p.(string), "no builder function", "right panic") } }() template.Build("test1", &ComponentFinder{}) }
// Test a long run to check stopping and restarting redis. func TestLongRun(t *testing.T) { if testing.Short() { return } assert := asserts.NewTestingAsserts(t, true) db := Connect(Configuration{}) wait := make(chan bool) for i := 0; i < 100; i++ { go func(ii int) { for j := 0; j < 20; j++ { key := fmt.Sprintf("long-run:%d:%d", ii, j) applog.Debugf("key: %s", key) rs := db.Command("set", key, ii+j) if !rs.IsOK() { applog.Errorf("%v", rs.Error()) } time.Sleep(time.Second) if ii == 99 && j == 19 { wait <- true } } }(i) } <-wait rs := db.Command("exists", "long-run:99:19") exists, err := rs.ValueAsBool() assert.Nil(err, "No error after 'exists'.") assert.True(exists, "Wanted key exists.") }
func TestBlockingPop(t *testing.T) { assert := asserts.NewTestingAsserts(t, true) db := Connect(Configuration{}) db.Command("del", "queue") go func() { for i := 0; i < 10; i++ { time.Sleep(100 * time.Millisecond) rs := db.Command("lpush", "queue", i) assert.True(rs.IsOK(), "'lpush' into queue has been ok.") } }() for i := 0; i < 10; i++ { rs := db.Command("brpop", "queue", 5) assert.True(rs.IsOK(), "'brpop' from queue has been ok.") assert.Equal(rs.ValueAt(0).String(), "queue", "Right 'queue' has been returned.") v, err := rs.ValueAt(1).Int() assert.Nil(err, "No error retrieving the integer value.") assert.Equal(v, i, "Popped value has been right.") } rs := db.Command("brpop", "queue", 1) assert.ErrorMatch(rs.Error(), "redis: timeout after .*", "'brpop' timed out.") assert.Assignable(rs.Error(), &TimeoutError{}, "Error has correct type.") }
func TestMultiCommand(t *testing.T) { assert := asserts.NewTestingAsserts(t, true) db := Connect(Configuration{}) db.Command("del", "multi-command:1") db.Command("del", "multi-command:2") db.Command("del", "multi-command:3") db.Command("del", "multi-command:4") db.Command("del", "multi-command:5") rs := db.MultiCommand(func(mc *MultiCommand) { mc.Command("set", "multi-command:1", "1") mc.Command("set", "multi-command:1", "2") mc.Discard() mc.Command("set", "multi-command:1", "one") mc.Command("set", "multi-command:2", "two") mc.Command("set", "multi-command:3", "three") mc.Command("set", "multi-command:4", "four") mc.Command("set", "multi-command:5", "five") mc.Command("get", "multi-command:3") }) assert.True(rs.IsOK(), "Executing the multi-command has been ok.") assert.Equal(rs.ResultSetCount(), 6, "Multi-command returned 6 result sets.") assert.Equal(rs.ResultSetAt(5).ValueAsString(), "three", "Sixth result set contained right value 'three'.") }
func TestArtifact_Implements(t *testing.T) { assert := asserts.NewTestingAsserts(t, true) var r packer.Artifact a := Artifact(nil) assert.Implementor(a, &r, "should be an Artifact") }
func TestConnection(t *testing.T) { assert := asserts.NewTestingAsserts(t, true) db := Connect(Configuration{}) // Connection commands. assert.Equal(db.Command("echo", "Hello, World!").ValueAsString(), "Hello, World!", "Echo of a string.") assert.Equal(db.Command("ping").ValueAsString(), "PONG", "Playing ping pong.") }
func TestProvisioner_Implements(t *testing.T) { assert := asserts.NewTestingAsserts(t, true) var r packer.Provisioner p := Provisioner(nil) assert.Implementor(p, &r, "should be a provisioner") }