Exemplo n.º 1
0
func TestSysGenerateRootAttempt_Status(t *testing.T) {
	core, _, token := vault.TestCoreUnsealed(t)
	ln, addr := TestServer(t, core)
	defer ln.Close()
	TestServerAuth(t, addr, token)

	resp, err := http.Get(addr + "/v1/sys/generate-root/attempt")
	if err != nil {
		t.Fatalf("err: %s", err)
	}

	var actual map[string]interface{}
	expected := map[string]interface{}{
		"started":            false,
		"progress":           json.Number("0"),
		"required":           json.Number("1"),
		"complete":           false,
		"encoded_root_token": "",
		"pgp_fingerprint":    "",
		"nonce":              "",
	}
	testResponseStatus(t, resp, 200)
	testResponseBody(t, resp, &actual)
	if !reflect.DeepEqual(actual, expected) {
		t.Fatalf("\nexpected: %#v\nactual: %#v", expected, actual)
	}
}
Exemplo n.º 2
0
func (s *RethinkSuite) TestSelectJSONNumbers(c *test.C) {
	session, err := Connect(ConnectOpts{
		Address:       url,
		UseJSONNumber: true,
	})
	c.Assert(err, test.IsNil)
	defer session.Close()
	// Ensure table + database exist
	DBCreate("test").Exec(session)
	DB("test").TableCreate("Table1").Exec(session)

	// Insert rows
	DB("test").Table("Table1").Insert(objList).Exec(session)

	// Test query
	var response interface{}
	query := DB("test").Table("Table1").Get(6)
	res, err := query.Run(session)
	c.Assert(err, test.IsNil)

	err = res.One(&response)

	c.Assert(err, test.IsNil)
	c.Assert(response, jsonEquals, map[string]interface{}{"id": json.Number("6"), "g1": json.Number("1"), "g2": json.Number("1"), "num": json.Number("15")})

	res.Close()
}
Exemplo n.º 3
0
func TestSysGenerateRootAttempt_Setup_PGP(t *testing.T) {
	core, _, token := vault.TestCoreUnsealed(t)
	ln, addr := TestServer(t, core)
	defer ln.Close()
	TestServerAuth(t, addr, token)

	resp := testHttpPut(t, token, addr+"/v1/sys/generate-root/attempt", map[string]interface{}{
		"pgp_key": pgpkeys.TestPubKey1,
	})
	testResponseStatus(t, resp, 200)

	resp = testHttpGet(t, token, addr+"/v1/sys/generate-root/attempt")

	var actual map[string]interface{}
	expected := map[string]interface{}{
		"started":            true,
		"progress":           json.Number("0"),
		"required":           json.Number("1"),
		"complete":           false,
		"encoded_root_token": "",
		"pgp_fingerprint":    "816938b8a29146fbe245dd29e7cbaf8e011db793",
	}
	testResponseStatus(t, resp, 200)
	testResponseBody(t, resp, &actual)
	if actual["nonce"].(string) == "" {
		t.Fatalf("nonce was empty")
	}
	expected["nonce"] = actual["nonce"]
	if !reflect.DeepEqual(actual, expected) {
		t.Fatalf("\nexpected: %#v\nactual: %#v", expected, actual)
	}
}
Exemplo n.º 4
0
// MarshalJSON implements the "encoding/json".Marshaler interface for
// ValueList.
func (vl *ValueList) MarshalJSON() ([]byte, error) {
	jvl := jsonValueList{
		Values:         make([]json.Number, len(vl.Values)),
		DSTypes:        make([]string, len(vl.Values)),
		DSNames:        make([]string, len(vl.Values)),
		Time:           cdtime.New(vl.Time),
		Interval:       cdtime.NewDuration(vl.Interval),
		Host:           vl.Host,
		Plugin:         vl.Plugin,
		PluginInstance: vl.PluginInstance,
		Type:           vl.Type,
		TypeInstance:   vl.TypeInstance,
	}

	for i, v := range vl.Values {
		switch v := v.(type) {
		case Gauge:
			jvl.Values[i] = json.Number(fmt.Sprintf("%.15g", v))
		case Derive:
			jvl.Values[i] = json.Number(fmt.Sprintf("%d", v))
		case Counter:
			jvl.Values[i] = json.Number(fmt.Sprintf("%d", v))
		default:
			return nil, fmt.Errorf("unexpected data source type: %T", v)
		}
		jvl.DSTypes[i] = v.Type()
		jvl.DSNames[i] = vl.DSName(i)
	}

	return json.Marshal(jvl)
}
Exemplo n.º 5
0
func TestSysRekeyInit_Status(t *testing.T) {
	core, _, token := vault.TestCoreUnsealed(t)
	ln, addr := TestServer(t, core)
	defer ln.Close()
	TestServerAuth(t, addr, token)

	resp, err := http.Get(addr + "/v1/sys/rekey/init")
	if err != nil {
		t.Fatalf("err: %s", err)
	}

	var actual map[string]interface{}
	expected := map[string]interface{}{
		"started":          false,
		"t":                json.Number("0"),
		"n":                json.Number("0"),
		"progress":         json.Number("0"),
		"required":         json.Number("1"),
		"pgp_fingerprints": interface{}(nil),
		"backup":           false,
		"nonce":            "",
	}
	testResponseStatus(t, resp, 200)
	testResponseBody(t, resp, &actual)
	if !reflect.DeepEqual(actual, expected) {
		t.Fatalf("\nexpected: %#v\nactual: %#v", expected, actual)
	}
}
func TestJsonParametersGetter(t *testing.T) {
	p := &JsonParametersGetter{
		values: map[string]interface{}{
			"int": json.Number("3"),
			"nested": map[string]interface{}{
				"b": true,
			},
			"slice_in_slice": []interface{}{
				[]interface{}{json.Number("1"), json.Number("2"), json.Number("3")},
			},
		},
	}
	if !p.IsExists(nil, "int") {
		t.Fatal("'int' not found")
	}
	if v, err := p.GetInt(nil, "int"); err != nil || v != 3 {
		t.Fatalf("'int'(%d) != 3, error: %v", v, err)
	}
	if !p.IsExists([]string{"nested"}, "b") {
		t.Fatal("'nested.b' not found")
	}
	if v, err := p.GetBool([]string{"nested"}, "b"); err != nil || v != true {
		t.Fatalf("'nested.b'(%z) != true, error: %v", v, err)
	}
	if v, err := p.GetInt([]string{"slice_in_slice", "0"}, "1"); err != nil || v != 2 {
		t.Fatalf("'slice_in_slice[0][1]'(%d) != 2, error: %v", v, err)
	}
}
Exemplo n.º 7
0
func TestIndicesBuild(t *testing.T) {

	tests := []struct {
		note     string
		ref      string
		value    interface{}
		expected string
	}{
		{"single var", "data.a[i]", json.Number("2"), `[{"i": 1}]`},
		{"two var", "data.d[x][y]", "baz", `[{"x": "e", "y": 1}]`},
		{"partial ground", `data.c[i]["y"][j]`, nil, `[{"i": 0, "j": 0}]`},
		{"multiple bindings", "data.g[x][y]", json.Number("0"), `[
			{"x": "a", "y": 1},
			{"x": "a", "y": 2},
			{"x": "a", "y": 3},
			{"x": "b", "y": 0},
			{"x": "b", "y": 2},
			{"x": "b", "y": 3},
			{"x": "c", "y": 0},
			{"x": "c", "y": 1},
			{"x": "c", "y": 2}
		]`},
	}

	for i, tc := range tests {
		runIndexBuildTestCase(t, i+1, tc.note, tc.ref, tc.expected, tc.value)
	}

}
func buildMonitorStruct(d *schema.ResourceData) *datadog.Monitor {

	var thresholds datadog.ThresholdCount

	if r, ok := d.GetOk("thresholds.ok"); ok {
		thresholds.Ok = json.Number(r.(string))
	}
	if r, ok := d.GetOk("thresholds.warning"); ok {
		thresholds.Warning = json.Number(r.(string))
	}
	if r, ok := d.GetOk("thresholds.critical"); ok {
		thresholds.Critical = json.Number(r.(string))
	}

	o := datadog.Options{
		Thresholds: thresholds,
	}
	if attr, ok := d.GetOk("silenced"); ok {
		s := make(map[string]int)
		// TODO: this is not very defensive, test if we can fail on non int input
		for k, v := range attr.(map[string]interface{}) {
			s[k], _ = strconv.Atoi(v.(string))
		}
		o.Silenced = s
	}
	if attr, ok := d.GetOk("notify_data"); ok {
		o.NotifyNoData = attr.(bool)
	}
	if attr, ok := d.GetOk("no_data_timeframe"); ok {
		o.NoDataTimeframe = attr.(int)
	}
	if attr, ok := d.GetOk("renotify_interval"); ok {
		o.RenotifyInterval = attr.(int)
	}
	if attr, ok := d.GetOk("notify_audit"); ok {
		o.NotifyAudit = attr.(bool)
	}
	if attr, ok := d.GetOk("timeout_h"); ok {
		o.TimeoutH = attr.(int)
	}
	if attr, ok := d.GetOk("escalation_message"); ok {
		o.EscalationMessage = attr.(string)
	}
	if attr, ok := d.GetOk("escalation_message"); ok {
		o.EscalationMessage = attr.(string)
	}
	if attr, ok := d.GetOk("include_tags"); ok {
		o.IncludeTags = attr.(bool)
	}

	m := datadog.Monitor{
		Type:    d.Get("type").(string),
		Query:   d.Get("query").(string),
		Name:    d.Get("name").(string),
		Message: d.Get("message").(string),
		Options: o,
	}

	return &m
}
Exemplo n.º 9
0
func TestEvalBodyCompileError(t *testing.T) {
	ctx := context.Background()
	store := newTestStore()
	var buffer bytes.Buffer
	repl := newRepl(store, &buffer)
	repl.outputFormat = "json"
	err := repl.OneShot(ctx, "x = 1, y > x")
	if _, ok := err.(ast.Errors); !ok {
		t.Fatalf("Expected error message in output but got`: %v", buffer.String())
	}
	buffer.Reset()
	repl.OneShot(ctx, "x = 1, y = 2, y > x")
	var result2 []interface{}
	err = util.UnmarshalJSON(buffer.Bytes(), &result2)
	if err != nil {
		t.Errorf("Expected valid JSON output but got: %v", buffer.String())
		return
	}
	expected2 := []interface{}{
		map[string]interface{}{
			"x": json.Number("1"),
			"y": json.Number("2"),
		},
	}
	if !reflect.DeepEqual(expected2, result2) {
		t.Errorf(`Expected [{"x": 1, "y": 2}] but got: %v"`, result2)
		return
	}
}
Exemplo n.º 10
0
func TestSysGenerateRootAttempt_Cancel(t *testing.T) {
	core, _, token := vault.TestCoreUnsealed(t)
	ln, addr := TestServer(t, core)
	defer ln.Close()
	TestServerAuth(t, addr, token)

	otpBytes, err := vault.GenerateRandBytes(16)
	if err != nil {
		t.Fatal(err)
	}
	otp := base64.StdEncoding.EncodeToString(otpBytes)

	resp := testHttpPut(t, token, addr+"/v1/sys/generate-root/attempt", map[string]interface{}{
		"otp": otp,
	})

	var actual map[string]interface{}
	expected := map[string]interface{}{
		"started":            true,
		"progress":           json.Number("0"),
		"required":           json.Number("1"),
		"complete":           false,
		"encoded_root_token": "",
		"pgp_fingerprint":    "",
	}
	testResponseStatus(t, resp, 200)
	testResponseBody(t, resp, &actual)
	if actual["nonce"].(string) == "" {
		t.Fatalf("nonce was empty")
	}
	expected["nonce"] = actual["nonce"]
	if !reflect.DeepEqual(actual, expected) {
		t.Fatalf("\nexpected: %#v\nactual: %#v", expected, actual)
	}

	resp = testHttpDelete(t, token, addr+"/v1/sys/generate-root/attempt")
	testResponseStatus(t, resp, 204)

	resp, err = http.Get(addr + "/v1/sys/generate-root/attempt")
	if err != nil {
		t.Fatalf("err: %s", err)
	}

	actual = map[string]interface{}{}
	expected = map[string]interface{}{
		"started":            false,
		"progress":           json.Number("0"),
		"required":           json.Number("1"),
		"complete":           false,
		"encoded_root_token": "",
		"pgp_fingerprint":    "",
		"nonce":              "",
	}
	testResponseStatus(t, resp, 200)
	testResponseBody(t, resp, &actual)
	if !reflect.DeepEqual(actual, expected) {
		t.Fatalf("\nexpected: %#v\nactual: %#v", expected, actual)
	}
}
Exemplo n.º 11
0
// Less compares two statements for sort.Sort
// Implements a natural sort to keep array indexes in order
func (ss statements) Less(a, b int) bool {

	diffStart := -1
	for i := range ss[a] {

		if len(ss[b]) < i+1 {
			// b must be shorter than a, so it
			// should come first
			return false
		}

		// The tokens match, so just carry on
		if ss[a][i] == ss[b][i] {
			continue
		}

		// We've found a difference
		diffStart = i
		break
	}

	// If diffStart is still -1 then the only difference must be
	// that string B is longer than A, so A should come first
	if diffStart == -1 {
		return true
	}

	// Get the tokens that differ
	ta := ss[a][diffStart]
	tb := ss[b][diffStart]

	// An equals always comes first
	if ta.typ == typEquals {
		return true
	}
	if tb.typ == typEquals {
		return false
	}

	// If both tokens are numeric keys do an integer comparison
	if ta.typ == typNumericKey && tb.typ == typNumericKey {
		ia, _ := strconv.Atoi(ta.text)
		ib, _ := strconv.Atoi(tb.text)
		return ia < ib
	}

	// If neither token is a number, just do a string comparison
	if ta.typ != typNumber || tb.typ != typNumber {
		return ta.text < tb.text
	}

	// We have two numbers to compare so turn them into json.Number
	// for comparison
	na, _ := json.Number(ta.text).Float64()
	nb, _ := json.Number(tb.text).Float64()
	return na < nb

}
Exemplo n.º 12
0
// AnalyseData decides if the monitor is statistically up or down and creates / resolves an incident
func (monitor *Monitor) AnalyseData() {
	// look at the past few incidents
	numDown := 0
	for _, wasUp := range monitor.History {
		if wasUp == false {
			numDown++
		}
	}

	t := (float32(numDown) / float32(len(monitor.History))) * 100
	Logger.Printf("%s %.2f%% Down at %v. Threshold: %.2f%%\n", monitor.URL, t, time.Now().UnixNano()/int64(time.Second), monitor.Threshold)

	if len(monitor.History) != 10 {
		// not enough data
		return
	}

	if t > monitor.Threshold && monitor.Incident == nil {
		// is down, create an incident
		Logger.Println("Creating incident...")

		component_id := json.Number(strconv.Itoa(*monitor.ComponentID))
		monitor.Incident = &Incident{
			Name:        monitor.Name + " - " + Config.SystemName,
			Message:     monitor.Name + " check failed",
			ComponentID: &component_id,
		}

		if monitor.LastFailReason != nil {
			monitor.Incident.Message += "\n\n - " + *monitor.LastFailReason
		}

		// set investigating status
		monitor.Incident.SetInvestigating()

		// create/update incident
		monitor.Incident.Send()
		monitor.Incident.UpdateComponent()
	} else if t < monitor.Threshold && monitor.Incident != nil {
		// was down, created an incident, its now ok, make it resolved.
		Logger.Println("Updating incident to resolved...")

		component_id := json.Number(strconv.Itoa(*monitor.ComponentID))
		monitor.Incident = &Incident{
			Name:        monitor.Incident.Name,
			Message:     monitor.Name + " check succeeded",
			ComponentID: &component_id,
		}

		monitor.Incident.SetFixed()
		monitor.Incident.Send()
		monitor.Incident.UpdateComponent()

		monitor.Incident = nil
	}
}
Exemplo n.º 13
0
func TestSysDisableAuth(t *testing.T) {
	core, _, token := vault.TestCoreUnsealed(t)
	ln, addr := TestServer(t, core)
	defer ln.Close()
	TestServerAuth(t, addr, token)

	resp := testHttpPost(t, token, addr+"/v1/sys/auth/foo", map[string]interface{}{
		"type":        "noop",
		"description": "foo",
	})
	testResponseStatus(t, resp, 204)

	resp = testHttpDelete(t, token, addr+"/v1/sys/auth/foo")
	testResponseStatus(t, resp, 204)

	resp = testHttpGet(t, token, addr+"/v1/sys/auth")

	var actual map[string]interface{}
	expected := map[string]interface{}{
		"lease_id":       "",
		"renewable":      false,
		"lease_duration": json.Number("0"),
		"wrap_info":      nil,
		"warnings":       nil,
		"auth":           nil,
		"data": map[string]interface{}{
			"token/": map[string]interface{}{
				"config": map[string]interface{}{
					"default_lease_ttl": json.Number("0"),
					"max_lease_ttl":     json.Number("0"),
				},
				"description": "token based credentials",
				"type":        "token",
			},
		},
		"token/": map[string]interface{}{
			"config": map[string]interface{}{
				"default_lease_ttl": json.Number("0"),
				"max_lease_ttl":     json.Number("0"),
			},
			"description": "token based credentials",
			"type":        "token",
		},
	}
	testResponseStatus(t, resp, 200)
	testResponseBody(t, resp, &actual)

	expected["request_id"] = actual["request_id"]

	if !reflect.DeepEqual(actual, expected) {
		t.Fatalf("bad: expected:%#v\nactual:%#v", expected, actual)
	}
}
Exemplo n.º 14
0
// We use this test to verify header auth wrapping
func TestSysMounts_headerAuth_Wrapped(t *testing.T) {
	core, _, token := vault.TestCoreUnsealed(t)
	ln, addr := TestServer(t, core)
	defer ln.Close()

	req, err := http.NewRequest("GET", addr+"/v1/sys/mounts", nil)
	if err != nil {
		t.Fatalf("err: %s", err)
	}
	req.Header.Set(AuthHeaderName, token)
	req.Header.Set(WrapTTLHeaderName, "60s")

	client := cleanhttp.DefaultClient()
	resp, err := client.Do(req)
	if err != nil {
		t.Fatalf("err: %s", err)
	}

	var actual map[string]interface{}
	expected := map[string]interface{}{
		"request_id":     "",
		"lease_id":       "",
		"renewable":      false,
		"lease_duration": json.Number("0"),
		"data":           nil,
		"wrap_info": map[string]interface{}{
			"ttl": json.Number("60"),
		},
		"warnings": nil,
		"auth":     nil,
	}

	testResponseStatus(t, resp, 200)
	testResponseBody(t, resp, &actual)

	actualToken, ok := actual["wrap_info"].(map[string]interface{})["token"]
	if !ok || actualToken == "" {
		t.Fatal("token missing in wrap info")
	}
	expected["wrap_info"].(map[string]interface{})["token"] = actualToken

	actualCreationTime, ok := actual["wrap_info"].(map[string]interface{})["creation_time"]
	if !ok || actualCreationTime == "" {
		t.Fatal("creation_time missing in wrap info")
	}
	expected["wrap_info"].(map[string]interface{})["creation_time"] = actualCreationTime

	if !reflect.DeepEqual(actual, expected) {
		t.Fatalf("bad:\nExpected: %#v\nActual: %#v\n%T %T", expected, actual, actual["warnings"], actual["data"])
	}
}
Exemplo n.º 15
0
func TestDataStoreGet(t *testing.T) {

	data := loadSmallTestData()

	var tests = []struct {
		path     string
		expected interface{}
	}{
		{"/a/0", json.Number("1")},
		{"/a/3", json.Number("4")},
		{"/b/v1", "hello"},
		{"/b/v2", "goodbye"},
		{"/c/0/x/1", false},
		{"/c/0/y/0", nil},
		{"/c/0/y/1", json.Number("3.14159")},
		{"/d/e/1", "baz"},
		{"/d/e", []interface{}{"bar", "baz"}},
		{"/c/0/z", map[string]interface{}{"p": true, "q": false}},
		{"/d/100", notFoundError(MustParsePath("/d/100"), doesNotExistMsg)},
		{"/dead/beef", notFoundError(MustParsePath("/dead/beef"), doesNotExistMsg)},
		{"/a/str", notFoundError(MustParsePath("/a/str"), arrayIndexTypeMsg)},
		{"/a/100", notFoundError(MustParsePath("/a/100"), outOfRangeMsg)},
		{"/a/-1", notFoundError(MustParsePath("/a/-1"), outOfRangeMsg)},
		{"/b/vdeadbeef", notFoundError(MustParsePath("/b/vdeadbeef"), doesNotExistMsg)},
	}

	ds := NewDataStoreFromJSONObject(data)

	for idx, tc := range tests {
		result, err := ds.Read(context.Background(), nil, MustParsePath(tc.path))
		switch e := tc.expected.(type) {
		case error:
			if err == nil {
				t.Errorf("Test case %d: expected error for %v but got %v", idx+1, tc.path, result)
			} else if !reflect.DeepEqual(err, tc.expected) {
				t.Errorf("Test case %d: unexpected error for %v: %v, expected: %v", idx+1, tc.path, err, e)
			}
		default:
			if err != nil {
				t.Errorf("Test case %d: expected success for %v but got %v", idx+1, tc.path, err)
			}
			if !reflect.DeepEqual(result, tc.expected) {
				t.Errorf("Test case %d: expected %f but got %f", idx+1, tc.expected, result)
			}
		}
	}

}
Exemplo n.º 16
0
Arquivo: type_test.go Projeto: knq/jwt
func TestClaimsMarshalUnmarshal(t *testing.T) {
	tm := time.Now().Add(14 * time.Hour)
	expr := json.Number(strconv.FormatInt(tm.Unix(), 10))
	c := Claims{Issuer: "issuer", Expiration: expr}

	buf, err := json.Marshal(&c)
	if err != nil {
		t.Fatalf("expected no error, got: %v", err)
	}

	c0 := Claims{}
	err = json.Unmarshal(buf, &c0)
	if err != nil {
		t.Fatalf("expected no error, got: %v", err)
	}
	if expr != c0.Expiration {
		t.Errorf("expr and c0.Expiration should equal -- %v / %v", expr, c0.Expiration)
	}

	if "issuer" != c0.Issuer {
		t.Errorf("c0.Issuer should be 'issuer'")
	}

	c1 := Claims{}
	err = json.Unmarshal([]byte(`{ "nbf": [] }`), &c1)
	if err == nil {
		t.Errorf("expected error, got nil")
	}
}
Exemplo n.º 17
0
func (p *JsonParametersGetter) getNumber(path []string, name string) (json.Number, error) {
	v, _ := p.get(path, name)
	if n, ok := v.(json.Number); ok {
		return n, nil
	}
	return json.Number(""), errors.New(`Wrong value of param "` + name + `". It must be number`)
}
Exemplo n.º 18
0
func TestJSONMarshaller(t *testing.T) {
	var m Marshaller = NewJSON()
	assert.Equal(t, m.Mime(), "application/json")
	data := map[string]interface{}{
		"key1": 1,
		"key2": "str",
	}
	buf := bytes.NewBuffer(nil)
	err := m.Marshal(buf)
	assert.Equal(t, err, nil, "error: %s", err)
	assert.Equal(t, buf.String(), "")
	err = m.Marshal(buf, data, nil)
	assert.Equal(t, err, nil, "error: %s", err)
	assert.Equal(t, buf.String(), "{\"key1\":1,\"key2\":\"str\"}\n")
	data = nil
	err = m.Unmarshal(buf)
	assert.Equal(t, err, nil, "error: %s", err)
	err = m.Unmarshal(buf, &data)
	assert.Equal(t, err, nil, "error: %s", err)
	assert.Equal(t, data, map[string]interface{}{"key1": json.Number("1"), "key2": "str"})

	data["f"] = TestJSONMarshaller
	err = m.Marshal(buf, data)
	assert.NotEqual(t, err, nil)
	buf = bytes.NewBufferString("abc")
	err = m.Unmarshal(buf, &data)
	assert.NotEqual(t, err, nil)
}
Exemplo n.º 19
0
func TestSysReadPolicy(t *testing.T) {
	core, _, token := vault.TestCoreUnsealed(t)
	ln, addr := TestServer(t, core)
	defer ln.Close()
	TestServerAuth(t, addr, token)

	resp := testHttpGet(t, token, addr+"/v1/sys/policy/root")

	var actual map[string]interface{}
	expected := map[string]interface{}{
		"lease_id":       "",
		"renewable":      false,
		"lease_duration": json.Number("0"),
		"wrap_info":      nil,
		"warnings":       nil,
		"auth":           nil,
		"data": map[string]interface{}{
			"name":  "root",
			"rules": "",
		},
		"name":  "root",
		"rules": "",
	}
	testResponseStatus(t, resp, 200)
	testResponseBody(t, resp, &actual)
	expected["request_id"] = actual["request_id"]
	if !reflect.DeepEqual(actual, expected) {
		t.Fatalf("bad: got\n%#v\nexpected\n%#v\n", actual, expected)
	}
}
Exemplo n.º 20
0
// If the property has been set at least once, returns all values joined
// as a space separated string. Returns true if the propery has been set
// at least once.
func (s RawSection) GetPropertyNumber(property string) (json.Number, bool) {
	vs, ok := s[property]
	if !ok {
		return "", false
	}
	return json.Number(strings.Join(vs, " ")), true
}
Exemplo n.º 21
0
Arquivo: term.go Projeto: tsandall/opa
// Hash returns the hash code for the Value.
func (num Number) Hash() int {
	f, err := json.Number(num).Float64()
	if err != nil {
		panic("illegal value")
	}
	return int(f)
}
func appendConditionalFormats(datadogRequest *datadog.GraphDefinitionRequest, terraformFormats *[]interface{}) {
	for _, t_ := range *terraformFormats {
		t := t_.(map[string]interface{})
		d := datadog.DashboardConditionalFormat{
			Comparator: t["comparator"].(string),
		}

		if palette, ok := t["palette"]; ok {
			d.Palette = palette.(string)
		}

		if customBgColor, ok := t["custom_bg_color"]; ok {
			d.CustomBgColor = customBgColor.(string)
		}

		if customFgColor, ok := t["custom_fg_color"]; ok {
			d.CustomFgColor = customFgColor.(string)
		}

		if value, ok := t["value"]; ok {
			d.Value = json.Number(value.(string))
		}

		datadogRequest.ConditionalFormats = append(datadogRequest.ConditionalFormats, d)
	}
}
Exemplo n.º 23
0
Arquivo: term.go Projeto: tsandall/opa
// Int returns the int representation of num if possible.
func (num Number) Int() (int, bool) {
	i, err := json.Number(num).Int64()
	if err != nil {
		return 0, false
	}
	return int(i), true
}
Exemplo n.º 24
0
func Test_MarshalJSON(t *testing.T) {
	expected := NewSetFromSlice(
		[]interface{}{
			json.Number("1"),
			"test",
		},
	)

	b, err := json.Marshal(
		NewSetFromSlice(
			[]interface{}{
				1,
				"test",
			},
		),
	)
	if err != nil {
		t.Errorf("Error should be nil: %v", err)
	}

	actual := NewSet()
	err = json.Unmarshal(b, actual)
	if err != nil {
		t.Errorf("Error should be nil: %v", err)
	}

	if !expected.Equal(actual) {
		t.Errorf("Expected no difference, got: %v", expected.Difference(actual))
	}
}
Exemplo n.º 25
0
func (f *Field) MarshalJSON() ([]byte, error) {
	aux := map[string]interface{}{
		"name":        f.Name,
		"label":       f.Label,
		"table":       f.Table.Name,
		"description": f.Description,
		"required":    f.Required,
		"type":        f.Type,
		"length":      json.Number(f.Length),
		"precision":   json.Number(f.Precision),
		"scale":       json.Number(f.Scale),
		"default":     f.Default,
	}

	return json.Marshal(aux)
}
Exemplo n.º 26
0
func TestSysRekeyInit_Setup(t *testing.T) {
	core, _, token := vault.TestCoreUnsealed(t)
	ln, addr := TestServer(t, core)
	defer ln.Close()
	TestServerAuth(t, addr, token)

	resp := testHttpPut(t, token, addr+"/v1/sys/rekey/init", map[string]interface{}{
		"secret_shares":    5,
		"secret_threshold": 3,
	})
	testResponseStatus(t, resp, 200)

	var actual map[string]interface{}
	expected := map[string]interface{}{
		"started":          true,
		"t":                json.Number("3"),
		"n":                json.Number("5"),
		"progress":         json.Number("0"),
		"required":         json.Number("1"),
		"pgp_fingerprints": interface{}(nil),
		"backup":           false,
	}
	testResponseStatus(t, resp, 200)
	testResponseBody(t, resp, &actual)
	if actual["nonce"].(string) == "" {
		t.Fatalf("nonce was empty")
	}
	expected["nonce"] = actual["nonce"]
	if !reflect.DeepEqual(actual, expected) {
		t.Fatalf("\nexpected: %#v\nactual: %#v", expected, actual)
	}

	resp = testHttpGet(t, token, addr+"/v1/sys/rekey/init")

	actual = map[string]interface{}{}
	expected = map[string]interface{}{
		"started":          true,
		"t":                json.Number("3"),
		"n":                json.Number("5"),
		"progress":         json.Number("0"),
		"required":         json.Number("1"),
		"pgp_fingerprints": interface{}(nil),
		"backup":           false,
	}
	testResponseStatus(t, resp, 200)
	testResponseBody(t, resp, &actual)
	if actual["nonce"].(string) == "" {
		t.Fatalf("nonce was empty")
	}
	if actual["nonce"].(string) == "" {
		t.Fatalf("nonce was empty")
	}
	expected["nonce"] = actual["nonce"]
	if !reflect.DeepEqual(actual, expected) {
		t.Fatalf("\nexpected: %#v\nactual: %#v", expected, actual)
	}
}
Exemplo n.º 27
0
func TestLogstashFormatter(t *testing.T) {
	assert := assert.New(t)

	lf := Formatter{Type: "abc"}

	fields := logrus.Fields{
		"message":      "def",
		"level":        "ijk",
		"type":         "lmn",
		"one":          1,
		"pi":           3.14,
		"bool":         true,
		"custom_error": errors.New("test custom error"),
	}

	entry := logrus.WithFields(fields).WithError(errors.New("test error"))
	entry.Message = "msg"
	entry.Level = logrus.InfoLevel

	b, _ := lf.Format(entry)

	var data map[string]interface{}
	dec := json.NewDecoder(bytes.NewReader(b))
	dec.UseNumber()
	_ = dec.Decode(&data)

	// base fields
	assert.Equal(json.Number("1"), data["@version"])
	assert.NotEmpty(data["@timestamp"])
	assert.Equal("abc", data["type"])
	assert.Equal("msg", data["message"])
	assert.Equal("info", data["level"])

	// error fields
	assert.Equal("test error", data[logrus.ErrorKey])
	assert.Equal("test custom error", data["custom_error"])

	// substituted fields
	assert.Equal("def", data["fields.message"])
	assert.Equal("ijk", data["fields.level"])
	assert.Equal("lmn", data["fields.type"])

	// formats
	assert.Equal(json.Number("1"), data["one"])
	assert.Equal(json.Number("3.14"), data["pi"])
	assert.Equal(true, data["bool"])
}
Exemplo n.º 28
0
func TestToInt(t *testing.T) {
	assert(t, 2, (&EasyInterface{int(2)}).ToInt())
	assert(t, 2, (&EasyInterface{float32(2)}).ToInt())
	assert(t, 2, (&EasyInterface{float64(2)}).ToInt())
	assert(t, 2, (&EasyInterface{"2"}).ToInt())
	assert(t, 2, (&EasyInterface{json.Number("2")}).ToInt())
	assert(t, 0, (&EasyInterface{[]byte(`hello`)}).ToInt())
}
Exemplo n.º 29
0
func TestPostJson(t *testing.T) {
	c := new(http.Client)
	req := NewRequest(c)
	req.Json = []int{1, 2, 3}
	url := "http://httpbin.org/post"
	resp, _ := req.Post(url)
	d, _ := resp.Json()
	defer resp.Body.Close()

	assert.Equal(t, resp.Ok(), true)
	v := []interface{}{
		json.Number("1"),
		json.Number("2"),
		json.Number("3"),
	}
	assert.Equal(t, d.Get("json").MustArray(), v)
}
Exemplo n.º 30
0
func (p *LogDoc) Numeric(value string) interface{} {
	n := json.Number(value)
	if i64, err := n.Int64(); err == nil {
		return i64
	}
	f64, _ := n.Float64()
	return f64
}