コード例 #1
0
func TestInstanceAdmin(t *testing.T) {
	client, server := test.AdminClient(instanceAdminResponse)
	defer server.Close()
	want :=
		RestartResponse{
			XMLName: xml.Name{Space: "http://marklogic.com/manage", Local: "restart"},
			LastStartup: LastStartupElement{
				XMLName: xml.Name{Space: "http://marklogic.com/manage", Local: "last-startup"},
				Value:   "2013-04-01T10:35:19.09913-07:00",
				HostID:  "13544732455686476949",
			},
			Link: LinkElement{
				XMLName: xml.Name{Space: "http://marklogic.com/manage", Local: "link"},
				KindRef: "timestamp",
				URIRef:  "/admin/v1/timestamp",
			},
			Message: "Check for new timestamp to verify host restart.",
		}
	// Using Basic Auth for test so initial call isn't actually made
	respHandle := RestartResponseHandle{Format: handle.XML}
	err := instanceAdmin(client, "admin", "password", "public", &respHandle)
	resp := respHandle.Get()
	if err != nil {
		t.Errorf("Error = %v", err)
	} else if resp == nil {
		t.Errorf("No response found")
	} else if !reflect.DeepEqual(want.LastStartup, resp.LastStartup) {
		t.Errorf("InstanceAdmin LastStartup = %+v, Want = %+v", spew.Sdump(resp.LastStartup), spew.Sdump(want.LastStartup))
	} else if !reflect.DeepEqual(resp.Link, want.Link) {
		t.Errorf("InstanceAdmin Link = %+v, Want = %+v", spew.Sdump(resp.Link), spew.Sdump(want.Link))
	} else if !reflect.DeepEqual(*resp, want) {
		t.Errorf("InstanceAdmin Response = %+v, Want = %+v", spew.Sdump(*resp), spew.Sdump(want))
	}
}
コード例 #2
0
ファイル: interface_test.go プロジェクト: rahulxkrishna/btcd
// testFetchTxBySha ensures FetchTxBySha conforms to the interface contract.
func testFetchTxBySha(tc *testContext) bool {
	for i, tx := range tc.block.Transactions() {
		txHash := tx.Sha()
		txReplyList, err := tc.db.FetchTxBySha(txHash)
		if err != nil {
			tc.t.Errorf("FetchTxBySha (%s): block #%d (%s) "+
				"tx #%d (%s) err: %v", tc.dbType, tc.blockHeight,
				tc.blockHash, i, txHash, err)
			return false
		}
		if len(txReplyList) == 0 {
			tc.t.Errorf("FetchTxBySha (%s): block #%d (%s) "+
				"tx #%d (%s) did not return reply data",
				tc.dbType, tc.blockHeight, tc.blockHash, i,
				txHash)
			return false
		}
		txFromDb := txReplyList[len(txReplyList)-1].Tx
		if !reflect.DeepEqual(tx.MsgTx(), txFromDb) {
			tc.t.Errorf("FetchTxBySha (%s): block #%d (%s) "+
				"tx #%d (%s) does not match stored tx\n"+
				"got: %v\nwant: %v", tc.dbType, tc.blockHeight,
				tc.blockHash, i, txHash, spew.Sdump(txFromDb),
				spew.Sdump(tx.MsgTx()))
			return false
		}
	}

	return true
}
コード例 #3
0
ファイル: assertions.go プロジェクト: 2722/lantern
// Equal asserts that two objects are equal.
//
//    assert.Equal(t, 123, 123, "123 and 123 should be equal")
//
// Returns whether the assertion was successful (true) or not (false).
func Equal(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool {

	if !ObjectsAreEqual(expected, actual) {
		var msg string
		tp := reflect.TypeOf(expected)
		k := tp.Kind()
		if k == reflect.Ptr {
			tp = tp.Elem()
			k = tp.Kind()
		}
		if k == reflect.Struct || k == reflect.Map || k == reflect.Slice || k == reflect.Array {
			msg = fmt.Sprintf("Not equal:\n"+
				"---- Expected ----\n%s\n--------------\n"+
				"---- Actual ------\n%s\n--------------",
				spew.Sdump(expected),
				spew.Sdump(actual))
		} else {
			msg = fmt.Sprintf("Not equal: %#v (expected)\n"+
				"        != %#v (actual)", expected, actual)
		}
		return Fail(t, msg, msgAndArgs...)
	}

	return true

}
コード例 #4
0
func TestSphinxEncodeDecode(t *testing.T) {
	// Create some test data with a randomly populated, yet valid onion
	// forwarding message.
	_, fwdMsg, err := newTestRoute(5)
	if err != nil {
		t.Fatalf("unable to create random onion packet: %v", err)
	}

	// Encode the created onion packet into an empty buffer. This should
	// succeeed without any errors.
	var b bytes.Buffer
	if err := fwdMsg.Encode(&b); err != nil {
		t.Fatalf("unable to encode message: %v", err)
	}

	// Now decode the bytes encoded above. Again, this should succeeed
	// without any errors.
	newFwdMsg := &OnionPacket{}
	if err := newFwdMsg.Decode(&b); err != nil {
		t.Fatalf("unable to decode message: %v", err)
	}

	// The two forwarding messages should now be identical.
	if !reflect.DeepEqual(fwdMsg, newFwdMsg) {
		t.Fatalf("forwarding messages don't match, %v vs %v",
			spew.Sdump(fwdMsg), spew.Sdump(newFwdMsg))
	}
}
コード例 #5
0
ファイル: genesis_test.go プロジェクト: jcvernaleo/btcnet
// TestTestNet3GenesisBlock tests the genesis block of the test network (version
// 3) for validity by checking the encoded bytes and hashes.
func TestTestNet3GenesisBlock(t *testing.T) {
	// Encode the genesis block to raw bytes.
	var buf bytes.Buffer
	err := btcnet.TestNet3Params.GenesisBlock.Serialize(&buf)
	if err != nil {
		t.Fatalf("TestTestNet3GenesisBlock: %v", err)
	}

	// Ensure the encoded block matches the expected bytes.
	if !bytes.Equal(buf.Bytes(), testNet3GenesisBlockBytes) {
		t.Fatalf("TestTestNet3GenesisBlock: Genesis block does not "+
			"appear valid - got %v, want %v",
			spew.Sdump(buf.Bytes()),
			spew.Sdump(testNet3GenesisBlockBytes))
	}

	// Check hash of the block against expected hash.
	hash, err := btcnet.TestNet3Params.GenesisBlock.BlockSha()
	if err != nil {
		t.Fatalf("BlockSha: %v", err)
	}
	if !btcnet.TestNet3Params.GenesisHash.IsEqual(&hash) {
		t.Fatalf("TestTestNet3GenesisBlock: Genesis block hash does "+
			"not appear valid - got %v, want %v", spew.Sdump(hash),
			spew.Sdump(btcnet.TestNet3Params.GenesisHash))
	}
}
コード例 #6
0
ファイル: addrcache_test.go プロジェクト: Codzart/go-ethereum
func TestWatchNewFile(t *testing.T) {
	t.Parallel()

	dir, am := tmpManager(t, false)
	defer os.RemoveAll(dir)

	// Ensure the watcher is started before adding any files.
	am.Accounts()
	time.Sleep(200 * time.Millisecond)

	// Move in the files.
	wantAccounts := make([]Account, len(cachetestAccounts))
	for i := range cachetestAccounts {
		a := cachetestAccounts[i]
		a.File = filepath.Join(dir, filepath.Base(a.File))
		wantAccounts[i] = a
		if err := cp.CopyFile(a.File, cachetestAccounts[i].File); err != nil {
			t.Fatal(err)
		}
	}

	// am should see the accounts.
	var list []Account
	for d := 200 * time.Millisecond; d < 5*time.Second; d *= 2 {
		list = am.Accounts()
		if reflect.DeepEqual(list, wantAccounts) {
			return
		}
		time.Sleep(d)
	}
	t.Errorf("got %s, want %s", spew.Sdump(list), spew.Sdump(wantAccounts))
}
コード例 #7
0
ファイル: assertions.go プロジェクト: ClearcodeHQ/Go-Forward
// diff returns a diff of both values as long as both are of the same type and
// are a struct, map, slice or array. Otherwise it returns an empty string.
func diff(expected interface{}, actual interface{}) string {
	if expected == nil || actual == nil {
		return ""
	}

	et, ek := typeAndKind(expected)
	at, _ := typeAndKind(actual)

	if et != at {
		return ""
	}

	if ek != reflect.Struct && ek != reflect.Map && ek != reflect.Slice && ek != reflect.Array {
		return ""
	}

	e := spew.Sdump(expected)
	a := spew.Sdump(actual)

	diff, _ := difflib.GetUnifiedDiffString(difflib.UnifiedDiff{
		A:        difflib.SplitLines(e),
		B:        difflib.SplitLines(a),
		FromFile: "Expected",
		FromDate: "",
		ToFile:   "Actual",
		ToDate:   "",
		Context:  1,
	})

	return "\n\nDiff:\n" + diff
}
コード例 #8
0
ファイル: cursor_test.go プロジェクト: skia-dev/influxdb
// Ensure a cursor with a single ref value can be converted into an iterator.
func TestFloatCursorIterator_SingleValue(t *testing.T) {
	cur := NewCursor([]CursorItem{
		{Key: 0, Value: float64(100)},
		{Key: 3, Value: float64(200)},
	}, true)

	opt := influxql.IteratorOptions{
		Expr:      &influxql.VarRef{Val: "value"},
		Ascending: true,
		StartTime: influxql.MinTime,
		EndTime:   influxql.MaxTime,
	}
	itr := tsdb.NewFloatCursorIterator("series0", map[string]string{"host": "serverA"}, cur, opt)
	defer itr.Close()

	if p := itr.Next(); !deep.Equal(p, &influxql.FloatPoint{
		Name:  "series0",
		Time:  0,
		Value: float64(100),
	}) {
		t.Fatalf("unexpected point(0): %s", spew.Sdump(p))
	}

	if p := itr.Next(); !deep.Equal(p, &influxql.FloatPoint{
		Name:  "series0",
		Time:  3,
		Value: float64(200),
	}) {
		t.Fatalf("unexpected point(1): %s", spew.Sdump(p))
	}

	if p := itr.Next(); p != nil {
		t.Fatalf("expected eof, got: %s", spew.Sdump(p))
	}
}
コード例 #9
0
ファイル: cursor_test.go プロジェクト: skia-dev/influxdb
// Ensure a cursor iterator does not go past the end time.
func TestFloatCursorIterator_EndTime(t *testing.T) {
	cur := NewCursor([]CursorItem{
		{Key: 0, Value: float64(100)},
		{Key: 3, Value: float64(200)},
		{Key: 4, Value: float64(300)},
	}, true)

	itr := tsdb.NewFloatCursorIterator("x", nil, cur, influxql.IteratorOptions{
		Expr:      &influxql.VarRef{Val: "value"},
		Ascending: true,
		EndTime:   3,
	})
	defer itr.Close()

	// Verify that only two points are emitted.
	if p := itr.Next(); p == nil || p.Time != 0 {
		t.Fatalf("unexpected point(0): %s", spew.Sdump(p))
	}
	if p := itr.Next(); p == nil || p.Time != 3 {
		t.Fatalf("unexpected point(1): %s", spew.Sdump(p))
	}
	if p := itr.Next(); p != nil {
		t.Fatalf("expected eof, got: %s", spew.Sdump(p))
	}
}
コード例 #10
0
ファイル: node_test.go プロジェクト: albrow/calc
func TestAddChild(t *testing.T) {
	parent := New()
	children := []Node{
		&Number{
			Value: "1",
		},
		&Number{
			Value: "2",
		},
		&Number{
			Value: "3",
		},
	}
	for _, child := range children {
		parent.AddChild(child)
	}
	if gotChildren := parent.Children(); !reflect.DeepEqual(gotChildren, children) {
		t.Fatalf(
			"Expected: %s\n  but got: %s",
			spew.Sdump(children),
			spew.Sdump(gotChildren),
		)
	}
	for _, child := range children {
		if gotParent := child.Parent(); !reflect.DeepEqual(gotParent, parent) {
			t.Fatalf(
				"Expected: %s\n  but got: %s",
				spew.Sdump(parent),
				spew.Sdump(gotParent),
			)
		}
	}
}
コード例 #11
0
ファイル: snmp.go プロジェクト: kortschak/gosnmp
func (ctxt *snmpContext) processOutboundQueue() {
	defer func() {
		ctxt.outboundDied <- true
		ctxt.conn.Close() // make sure that receive side shuts down too.
	}()
	ctxt.Debugf("Ctxt %s: outbound flow controller initializing", ctxt.name)
	for {
		select {
		case msg := <-ctxt.outboundFlowControlQueue:
			encodedMsg, err := msg.encode(ctxt.berEncoderFactory)
			if err != nil {
				ctxt.Debugf("Couldn't encode message: err: %s. Message:\n%s", err, spew.Sdump(msg))
				continue
			}
			ctxt.Debugf("Ctxt %s: Sending message:\n%s", ctxt.name, spew.Sdump(msg))
			if n, err := ctxt.conn.WriteToUDP(encodedMsg, msg.getAddress()); err != nil || n != len(encodedMsg) {
				if strings.HasSuffix(err.Error(), "closed network connection") {
					ctxt.Debugf("Ctxt %s: outbound flow controller shutting down due to closed connection", ctxt.name)
					ctxt.incrementStat(StatType_OUTBOUND_CONNECTION_CLOSE)
				} else {
					ctxt.Errorf("Ctxt %s: UDP write failed, err: %s, numWritten: %d, expected: %d", ctxt.name, err, n, len(encodedMsg))
					ctxt.incrementStat(StatType_OUTBOUND_CONNECTION_DEATH)
				}
				return
			}
			ctxt.incrementStat(StatType_OUTBOUND_MESSAGES_SENT)
		case <-ctxt.outboundFlowControlShutdown:
			ctxt.Debugf("Ctxt %s: outbound flow controller shutting down due to shutdown message", ctxt.name)
			return
		case <-ctxt.internalShutdownNotification:
			ctxt.Debugf("Ctxt %s: outbound flow controller shutting down due to snmpContext shutdown", ctxt.name)
			return
		}
	}
}
コード例 #12
0
ファイル: emitter_test.go プロジェクト: jmptrader/agora
func TestEmit(t *testing.T) {
	// Arrange
	e := new(Emitter)
	for i, c := range emitcases {
		if isolateEmitCase >= 0 && isolateEmitCase != i {
			continue
		}
		if testing.Verbose() {
			fmt.Printf("testing emitter case %d...\n", i)
		}

		// Act
		f, err := e.Emit("", c.src, nil)

		// Assert
		if (err != nil) != c.err {
			if err == nil {
				t.Errorf("[%d] - expected an error, got none", i)
			} else {
				t.Errorf("[%d] - expected no error, got `%s`", i, err)
			}
		}
		if c.exp != nil {
			if !equal(i, f, c.exp) {
				t.Errorf("[%d] - expected\n", i)
				t.Error(spew.Sdump(c.exp))
				t.Error("got\n")
				t.Error(spew.Sdump(f))
			}
		}
		if !c.err && c.exp == nil {
			t.Errorf("[%d] - no assertion", i)
		}
	}
}
コード例 #13
0
ファイル: supervisor_test.go プロジェクト: NetSys/quilt
func TestNone(t *testing.T) {
	ctx := initTest()

	if len(ctx.fd.running()) > 0 {
		t.Errorf("fd.running = %s; want <empty>", spew.Sdump(ctx.fd.running()))
	}

	if len(ctx.execs) > 0 {
		t.Errorf("exec = %s; want <empty>", spew.Sdump(ctx.execs))
	}

	ctx.conn.Transact(func(view db.Database) error {
		m, _ := view.MinionSelf()
		e := view.SelectFromEtcd(nil)[0]
		m.PrivateIP = "1.2.3.4"
		e.Leader = false
		e.LeaderIP = "5.6.7.8"
		view.Commit(m)
		view.Commit(e)
		return nil
	})
	ctx.run()

	if len(ctx.fd.running()) > 0 {
		t.Errorf("fd.running = %s; want <none>", spew.Sdump(ctx.fd.running()))
	}

	if len(ctx.execs) > 0 {
		t.Errorf("exec = %s; want <empty>", spew.Sdump(ctx.execs))
	}
}
コード例 #14
0
ファイル: peer.go プロジェクト: kazcw/btcd
// writeMessage sends a bitcoin Message to the peer with logging.
func (p *peer) writeMessage(msg btcwire.Message) {
	// Don't do anything if we're disconnecting.
	if atomic.LoadInt32(&p.disconnect) != 0 {
		return
	}

	log.Debugf("[PEER] Sending command [%v] to %s", msg.Command(),
		p.addr)

	// Use closures to log expensive operations so they are only run when the
	// logging level requires it.
	log.Tracef("%v", newLogClosure(func() string {
		return "[PEER] msg" + spew.Sdump(msg)
	}))
	log.Tracef("%v", newLogClosure(func() string {
		var buf bytes.Buffer
		err := btcwire.WriteMessage(&buf, msg, p.protocolVersion, p.btcnet)
		if err != nil {
			return err.Error()
		}
		return "[PEER] " + spew.Sdump(buf.Bytes())
	}))

	// Write the message to the peer.
	err := btcwire.WriteMessage(p.conn, msg, p.protocolVersion, p.btcnet)
	if err != nil {
		p.Disconnect()
		p.logError("[PEER] Can't send message: %v", err)
		return
	}
}
コード例 #15
0
ファイル: stitch_test.go プロジェクト: NetSys/quilt
func checkJavascript(t *testing.T, code string, exp interface{}) {
	resultKey := "result"

	vm, err := newVM(ImportGetter{
		Path: ".",
	})
	if err != nil {
		t.Errorf(`Unexpected error: "%s".`, err.Error())
		return
	}

	exec := fmt.Sprintf(`exports.%s = %s;`, resultKey, code)
	moduleVal, err := runSpec(vm, "<test_code>", exec)
	if err != nil {
		t.Errorf(`Unexpected error: "%s".`, err.Error())
		return
	}

	actualVal, err := moduleVal.Object().Get(resultKey)
	if err != nil {
		t.Errorf(`Unexpected error retrieving result from VM: "%s".`,
			err.Error())
		return
	}

	actual, _ := actualVal.Export()
	if !reflect.DeepEqual(actual, exp) {
		t.Errorf("Bad javascript code: Expected %s, got %s.",
			spew.Sdump(exp), spew.Sdump(actual))
	}
}
コード例 #16
0
func testAppArmorNode() {
	BeforeEach(func() {
		By("Loading AppArmor profiles for testing")
		framework.ExpectNoError(loadTestProfiles(), "Could not load AppArmor test profiles")
	})
	Context("when running with AppArmor", func() {
		f := framework.NewDefaultFramework("apparmor-test")

		It("should reject an unloaded profile", func() {
			status := runAppArmorTest(f, "localhost/"+"non-existant-profile")
			Expect(status.Phase).To(Equal(api.PodFailed), "PodStatus: %+v", status)
			Expect(status.Reason).To(Equal("AppArmor"), "PodStatus: %+v", status)
		})
		It("should enforce a profile blocking writes", func() {
			status := runAppArmorTest(f, "localhost/"+apparmorProfilePrefix+"deny-write")
			if len(status.ContainerStatuses) == 0 {
				framework.Failf("Unexpected pod status: %s", spew.Sdump(status))
				return
			}
			state := status.ContainerStatuses[0].State.Terminated
			Expect(state.ExitCode).To(Not(BeZero()), "ContainerStateTerminated: %+v", state)

		})
		It("should enforce a permissive profile", func() {
			status := runAppArmorTest(f, "localhost/"+apparmorProfilePrefix+"audit-write")
			if len(status.ContainerStatuses) == 0 {
				framework.Failf("Unexpected pod status: %s", spew.Sdump(status))
				return
			}
			state := status.ContainerStatuses[0].State.Terminated
			Expect(state.ExitCode).To(BeZero(), "ContainerStateTerminated: %+v", state)
		})
	})
}
コード例 #17
0
ファイル: addrcache_test.go プロジェクト: Codzart/go-ethereum
func TestCacheInitialReload(t *testing.T) {
	cache := newAddrCache(cachetestDir)
	accounts := cache.accounts()
	if !reflect.DeepEqual(accounts, cachetestAccounts) {
		t.Fatalf("got initial accounts: %swant %s", spew.Sdump(accounts), spew.Sdump(cachetestAccounts))
	}
}
コード例 #18
0
ファイル: peer.go プロジェクト: Belxjander/btcd
// readMessage reads the next bitcoin message from the peer with logging.
func (p *peer) readMessage() (msg btcwire.Message, buf []byte, err error) {
	msg, buf, err = btcwire.ReadMessage(p.conn, p.protocolVersion, p.btcnet)
	if err != nil {
		return
	}

	// Use closures to log expensive operations so they are only run when
	// the logging level requires it.
	log.Debugf("%v", newLogClosure(func() string {
		// Debug summary of message.
		summary := messageSummary(msg)
		if len(summary) > 0 {
			summary = " (" + summary + ")"
		}
		return fmt.Sprintf("PEER: Received %v%s from %s",
			msg.Command(), summary, p.addr)
	}))
	log.Tracef("%v", newLogClosure(func() string {
		return "PEER: " + spew.Sdump(msg)
	}))
	log.Tracef("%v", newLogClosure(func() string {
		return "PEER: " + spew.Sdump(buf)
	}))

	return
}
コード例 #19
0
func testInterpolate(
	t *testing.T, i *Interpolater,
	scope *InterpolationScope,
	n string, expectedVar ast.Variable) {
	v, err := config.NewInterpolatedVariable(n)
	if err != nil {
		t.Fatalf("err: %s", err)
	}

	actual, err := i.Values(scope, map[string]config.InterpolatedVariable{
		"foo": v,
	})
	if err != nil {
		t.Fatalf("err: %s", err)
	}

	expected := map[string]ast.Variable{
		"foo": expectedVar,
	}
	if !reflect.DeepEqual(actual, expected) {
		spew.Config.DisableMethods = true
		t.Fatalf("%q:\n\n  actual: %#v\nexpected: %#v\n\n%s\n\n%s\n\n", n, actual, expected,
			spew.Sdump(actual), spew.Sdump(expected))
	}
}
コード例 #20
0
ファイル: state_test.go プロジェクト: srikalyan/terraform
func TestReadUpgradeStateV1toV2_outputs(t *testing.T) {
	// ReadState should transparently detect the old version but will upgrade
	// it on Write.
	actual, err := ReadState(strings.NewReader(testV1StateWithOutputs))
	if err != nil {
		t.Fatalf("err: %s", err)
	}

	buf := new(bytes.Buffer)
	if err := WriteState(actual, buf); err != nil {
		t.Fatalf("err: %s", err)
	}

	if actual.Version != 2 {
		t.Fatalf("bad: State version not incremented; is %d", actual.Version)
	}

	roundTripped, err := ReadState(buf)
	if err != nil {
		t.Fatalf("err: %s", err)
	}

	if !reflect.DeepEqual(actual, roundTripped) {
		spew.Config.DisableMethods = true
		t.Fatalf("bad:\n%s\n\nround tripped:\n%s\n", spew.Sdump(actual), spew.Sdump(roundTripped))
		spew.Config.DisableMethods = false
	}
}
コード例 #21
0
ファイル: block_test.go プロジェクト: hsk81/btcutil
// TestNewBlockFromBlockAndBytes tests creation of a Block from a MsgBlock and
// raw bytes.
func TestNewBlockFromBlockAndBytes(t *testing.T) {
	// Serialize the test block.
	var block100000Buf bytes.Buffer
	err := Block100000.Serialize(&block100000Buf)
	if err != nil {
		t.Errorf("Serialize: %v", err)
	}
	block100000Bytes := block100000Buf.Bytes()

	// Create a new block from the serialized bytes.
	b := btcutil.NewBlockFromBlockAndBytes(&Block100000, block100000Bytes)

	// Ensure we get the same data back out.
	serializedBytes, err := b.Bytes()
	if err != nil {
		t.Errorf("Bytes: %v", err)
		return
	}
	if !bytes.Equal(serializedBytes, block100000Bytes) {
		t.Errorf("Bytes: wrong bytes - got %v, want %v",
			spew.Sdump(serializedBytes),
			spew.Sdump(block100000Bytes))
	}
	if msgBlock := b.MsgBlock(); !reflect.DeepEqual(msgBlock, &Block100000) {
		t.Errorf("MsgBlock: mismatched MsgBlock - got %v, want %v",
			spew.Sdump(msgBlock), spew.Sdump(&Block100000))
	}
}
コード例 #22
0
func TestBuildParameters(t *testing.T) {
	want := "?uri=%2Ftest%2F1.json&uri=%2Ftest%2F2.json&category=metadata&" +
		"category=content&collection=docs&perm:user=read&prop:date=2015-05-01&" +
		"transform=my-transform&trans:param1=val1"
	transform := &util.Transform{
		Name: "my-transform",
		Parameters: map[string]string{
			"param1": "val1",
		},
	}
	result := buildParameters(
		[]string{"/test/1.json", "/test/2.json"},
		[]string{"metadata", "content"},
		[]string{"docs"},
		map[string]string{
			"user": "******",
		},
		map[string]string{
			"date": "2015-05-01",
		},
		transform,
	)
	if want != result {
		t.Errorf("Build Parameters Results = %+v, Want = %+v", spew.Sdump(result), spew.Sdump(want))
	}
}
コード例 #23
0
ファイル: genesis_test.go プロジェクト: kingctan/btcwire
// TestGenesisBlock tests the genesis block of the main network for validity by
// checking the encoded bytes and hashes.
func TestGenesisBlock(t *testing.T) {
	// Encode the genesis block to raw bytes.
	var buf bytes.Buffer
	err := btcwire.GenesisBlock.Serialize(&buf)
	if err != nil {
		t.Errorf("TestGenesisBlock: %v", err)
		return
	}

	// Ensure the encoded block matches the expected bytes.
	if !bytes.Equal(buf.Bytes(), genesisBlockBytes) {
		t.Errorf("TestGenesisBlock: Genesis block does not appear valid - "+
			"got %v, want %v", spew.Sdump(buf.Bytes()),
			spew.Sdump(genesisBlockBytes))
		return
	}

	// Check hash of the block against expected hash.
	hash, err := btcwire.GenesisBlock.BlockSha()
	if err != nil {
		t.Errorf("BlockSha: %v", err)
	}
	if !btcwire.GenesisHash.IsEqual(&hash) {
		t.Errorf("TestGenesisBlock: Genesis block hash does not appear valid - "+
			"got %v, want %v", spew.Sdump(hash),
			spew.Sdump(btcwire.GenesisHash))
		return
	}
}
コード例 #24
0
ファイル: functions_test.go プロジェクト: RomainVabre/origin
func TestReduceDistinct(t *testing.T) {
	v1 := distinctValues{
		"2",
		"1",
		float64(2.0),
		float64(1),
		uint64(2),
		uint64(1),
		true,
		false,
	}

	expect := distinctValues{
		uint64(1),
		float64(1),
		uint64(2),
		float64(2),
		false,
		true,
		"1",
		"2",
	}

	got := ReduceDistinct([]interface{}{v1, v1, expect})

	if !reflect.DeepEqual(got, expect) {
		t.Errorf("Wrong values. exp %v got %v", spew.Sdump(expect), spew.Sdump(got))
	}
}
コード例 #25
0
ファイル: msgtx_test.go プロジェクト: kac-/btcwire
// TestTxSerialize tests MsgTx serialize and deserialize.
func TestTxSerialize(t *testing.T) {
	noTx := btcwire.NewMsgTx()
	noTx.Version = 1
	noTxEncoded := []byte{
		0x01, 0x00, 0x00, 0x00, // Version
		0x00,                   // Varint for number of input transactions
		0x00,                   // Varint for number of output transactions
		0x00, 0x00, 0x00, 0x00, // Lock time
	}

	tests := []struct {
		in  *btcwire.MsgTx // Message to encode
		out *btcwire.MsgTx // Expected decoded message
		buf []byte         // Serialized data
	}{
		// No transactions.
		{
			noTx,
			noTx,
			noTxEncoded,
		},

		// Multiple transactions.
		{
			multiTx,
			multiTx,
			multiTxEncoded,
		},
	}

	t.Logf("Running %d tests", len(tests))
	for i, test := range tests {
		// Serialize the transaction.
		var buf bytes.Buffer
		err := test.in.Serialize(&buf)
		if err != nil {
			t.Errorf("Serialize #%d error %v", i, err)
			continue
		}
		if !bytes.Equal(buf.Bytes(), test.buf) {
			t.Errorf("Serialize #%d\n got: %s want: %s", i,
				spew.Sdump(buf.Bytes()), spew.Sdump(test.buf))
			continue
		}

		// Deserialize the transaction.
		var tx btcwire.MsgTx
		rbuf := bytes.NewReader(test.buf)
		err = tx.Deserialize(rbuf)
		if err != nil {
			t.Errorf("Deserialize #%d error %v", i, err)
			continue
		}
		if !reflect.DeepEqual(&tx, test.out) {
			t.Errorf("Deserialize #%d\n got: %s want: %s", i,
				spew.Sdump(&tx), spew.Sdump(test.out))
			continue
		}
	}
}
コード例 #26
0
ファイル: functions_test.go プロジェクト: RomainVabre/origin
func Test_distinctValues_Sort(t *testing.T) {
	values := distinctValues{
		"2",
		"1",
		float64(2.0),
		float64(1),
		uint64(2),
		uint64(1),
		true,
		false,
	}

	expect := distinctValues{
		uint64(1),
		float64(1),
		uint64(2),
		float64(2),
		false,
		true,
		"1",
		"2",
	}

	sort.Sort(values)

	if !reflect.DeepEqual(values, expect) {
		t.Errorf("Wrong values. exp %v got %v", spew.Sdump(expect), spew.Sdump(values))
	}
}
コード例 #27
0
ファイル: tx_test.go プロジェクト: conseweb/coinutil
// TestTx tests the API for Tx.
func TestTx(t *testing.T) {
	testTx := Block100000.Transactions[0]
	tx := coinutil.NewTx(testTx)

	// Ensure we get the same data back out.
	if msgTx := tx.MsgTx(); !reflect.DeepEqual(msgTx, testTx) {
		t.Errorf("MsgTx: mismatched MsgTx - got %v, want %v",
			spew.Sdump(msgTx), spew.Sdump(testTx))
	}

	// Ensure transaction index set and get work properly.
	wantIndex := 0
	tx.SetIndex(0)
	if gotIndex := tx.Index(); gotIndex != wantIndex {
		t.Errorf("Index: mismatched index - got %v, want %v",
			gotIndex, wantIndex)
	}

	// Hash for block 100,000 transaction 0.
	wantShaStr := "8c14f0db3df150123e6f3dbbf30f8b955a8249b62ac1d1ff16284aefa3d06d87"
	wantSha, err := wire.NewShaHashFromStr(wantShaStr)
	if err != nil {
		t.Errorf("NewShaHashFromStr: %v", err)
	}

	// Request the sha multiple times to test generation and caching.
	for i := 0; i < 2; i++ {
		sha := tx.Sha()
		if !sha.IsEqual(wantSha) {
			t.Errorf("Sha #%d mismatched sha - got %v, want %v", i,
				sha, wantSha)
		}
	}
}
コード例 #28
0
ファイル: functions_test.go プロジェクト: RomainVabre/origin
func TestReduceCountDistinct(t *testing.T) {
	v1 := map[interface{}]struct{}{
		"2":          struct{}{},
		"1":          struct{}{},
		float64(2.0): struct{}{},
		float64(1):   struct{}{},
		uint64(2):    struct{}{},
		uint64(1):    struct{}{},
		true:         struct{}{},
		false:        struct{}{},
	}

	v2 := map[interface{}]struct{}{
		uint64(1):  struct{}{},
		float64(1): struct{}{},
		uint64(2):  struct{}{},
		float64(2): struct{}{},
		false:      struct{}{},
		true:       struct{}{},
		"1":        struct{}{},
		"2":        struct{}{},
	}

	exp := 8
	got := ReduceCountDistinct([]interface{}{v1, v1, v2})

	if !reflect.DeepEqual(got, exp) {
		t.Errorf("Wrong values. exp %v got %v", spew.Sdump(exp), spew.Sdump(got))
	}
}
コード例 #29
0
ファイル: dial_test.go プロジェクト: Cisko-Rijken/go-expanse
func runDialTest(t *testing.T, test dialtest) {
	var (
		vtime   time.Time
		running int
	)
	pm := func(ps []*Peer) map[discover.NodeID]*Peer {
		m := make(map[discover.NodeID]*Peer)
		for _, p := range ps {
			m[p.rw.id] = p
		}
		return m
	}
	for i, round := range test.rounds {
		for _, task := range round.done {
			running--
			if running < 0 {
				panic("running task counter underflow")
			}
			test.init.taskDone(task, vtime)
		}

		new := test.init.newTasks(running, pm(round.peers), vtime)
		if !sametasks(new, round.new) {
			t.Errorf("round %d: new tasks mismatch:\ngot %v\nwant %v\nstate: %v\nrunning: %v\n",
				i, spew.Sdump(new), spew.Sdump(round.new), spew.Sdump(test.init), spew.Sdump(running))
		}

		// Time advances by 16 seconds on every round.
		vtime = vtime.Add(16 * time.Second)
		running += len(new)
	}
}
コード例 #30
0
ファイル: script.go プロジェクト: hsk81/btcscript
// Execute will execute all script in the script engine and return either nil
// for successful validation or an error if one occurred.
func (s *Script) Execute() (err error) {
	done := false
	for done != true {
		log.Tracef("%v", newLogClosure(func() string {
			dis, err := s.DisasmPC()
			if err != nil {
				return fmt.Sprintf("stepping (%v)", err)
			}
			return fmt.Sprintf("stepping %v", dis)
		}))

		done, err = s.Step()
		if err != nil {
			return err
		}
		log.Tracef("%v", newLogClosure(func() string {
			var dstr, astr string

			// if we're tracing, dump the stacks.
			if s.dstack.Depth() != 0 {
				dstr = "Stack\n" + spew.Sdump(s.dstack)
			}
			if s.astack.Depth() != 0 {
				astr = "AltStack\n" + spew.Sdump(s.astack)
			}

			return dstr + astr
		}))
	}

	return s.CheckErrorCondition()
}