Пример #1
0
func ExampleDec_QuoExact_ok() {
	// 1 / 25 is a finite decimal; it has exact Dec representation
	x, y := inf.NewDec(1, 0), inf.NewDec(25, 0)
	z := new(inf.Dec).QuoExact(x, y)
	fmt.Println(z)
	// Output: 0.04
}
Пример #2
0
func ExampleDec_QuoExact_fail() {
	// 1 / 3 is an infinite decimal; it has no exact Dec representation
	x, y := inf.NewDec(1, 0), inf.NewDec(3, 0)
	z := new(inf.Dec).QuoExact(x, y)
	fmt.Println(z)
	// Output: <nil>
}
Пример #3
0
func TestDecScan(t *testing.T) {
	tmp := new(inf.Dec)
	for i, test := range decStringTests {
		if test.scale < 0 {
			// SetString only supports scale >= 0
			continue
		}
		// initialize to a non-zero value so that issues with parsing
		// 0 are detected
		tmp.Set(inf.NewDec(1234567890, 123))
		n1, n2 := new(inf.Dec), tmp
		nn1, err1 := fmt.Sscan(test.in, n1)
		nn2, err2 := fmt.Sscan(test.in, n2)
		if !test.scanOk {
			if err1 == nil || err2 == nil {
				t.Errorf("#%d (input '%s') ok incorrect, should be %t", i, test.in, test.scanOk)
			}
			continue
		}
		expected := inf.NewDec(test.val, test.scale)
		if nn1 != 1 || err1 != nil || nn2 != 1 || err2 != nil {
			t.Errorf("#%d (input '%s') error %d %v, %d %v", i, test.in, nn1, err1, nn2, err2)
			continue
		}
		if n1.Cmp(expected) != 0 {
			t.Errorf("#%d (input '%s') got: %s want: %d", i, test.in, n1, test.val)
		}
		if n2.Cmp(expected) != 0 {
			t.Errorf("#%d (input '%s') got: %s want: %d", i, test.in, n2, test.val)
		}
	}
}
Пример #4
0
// test mesos.GetNodeResources
func Test_GetNodeResources(t *testing.T) {
	defer log.Flush()
	md := FakeMasterDetector{}
	httpServer, httpClient, httpTransport := makeHttpMocks()
	defer httpServer.Close()
	cacheTTL := 500 * time.Millisecond
	mesosClient, err := createMesosClient(md, httpClient, httpTransport, cacheTTL)
	mesosCloud := &MesosCloud{client: mesosClient, config: createDefaultConfig()}

	resources, err := mesosCloud.GetNodeResources("mesos1.internal.company.com")

	if err != nil {
		t.Fatalf("GetNodeResources does not yield an error: %#v", err)
	}

	expectedCpu := inf.NewDec(8, 0)
	expectedMem := inf.NewDec(15360, 0)

	actualCpu := resources.Capacity["cpu"].Amount
	actualMem := resources.Capacity["memory"].Amount

	if actualCpu.Cmp(expectedCpu) != 0 {
		t.Fatalf("GetNodeResources should return the expected amount of cpu: (expected: %#v, vactual: %#v)", expectedCpu, actualCpu)
	}

	if actualMem.Cmp(expectedMem) != 0 {
		t.Fatalf("GetNodeResources should return the expected amount of memory: (expected: %#v, vactual: %#v)", expectedMem, actualMem)
	}

}
Пример #5
0
// newClusterResourceOverride returns an admission controller for containers that
// configurably overrides container resource request/limits
func newClusterResourceOverride(client clientset.Interface, config io.Reader) (admission.Interface, error) {
	parsed, err := ReadConfig(config)
	if err != nil {
		glog.V(5).Infof("%s admission controller loaded with error: (%T) %[2]v", api.PluginName, err)
		return nil, err
	}
	if errs := validation.Validate(parsed); len(errs) > 0 {
		return nil, errs.ToAggregate()
	}
	glog.V(5).Infof("%s admission controller loaded with config: %v", api.PluginName, parsed)
	var internal *internalConfig
	if parsed != nil {
		internal = &internalConfig{
			limitCPUToMemoryRatio:     inf.NewDec(parsed.LimitCPUToMemoryPercent, 2),
			cpuRequestToLimitRatio:    inf.NewDec(parsed.CPURequestToLimitPercent, 2),
			memoryRequestToLimitRatio: inf.NewDec(parsed.MemoryRequestToLimitPercent, 2),
		}
	}

	limitRanger, err := limitranger.NewLimitRanger(client, wrapLimit)
	if err != nil {
		return nil, err
	}

	return &clusterResourceOverridePlugin{
		Handler:     admission.NewHandler(admission.Create),
		config:      internal,
		LimitRanger: limitRanger,
	}, nil
}
Пример #6
0
func ExampleDec_QuoRound_scale2RoundCeil() {
	// -42 / 400 is an finite decimal with 3 digits beyond the decimal point
	x, y := inf.NewDec(-42, 0), inf.NewDec(400, 0)
	// use 2 digits beyond decimal point, round towards positive infinity
	z := new(inf.Dec).QuoRound(x, y, 2, inf.RoundCeil)
	fmt.Println(z)
	// Output: -0.10
}
Пример #7
0
func ExampleDec_QuoRound_scale2RoundDown() {
	// 10 / 3 is an infinite decimal; it has no exact Dec representation
	x, y := inf.NewDec(10, 0), inf.NewDec(3, 0)
	// use 2 digits beyond the decimal point, round towards 0
	z := new(inf.Dec).QuoRound(x, y, 2, inf.RoundDown)
	fmt.Println(z)
	// Output: 3.33
}
Пример #8
0
// checkResource determines whether a specific resource needs to be over-written.
func checkResource(threshold int64, actual, expected api.ResourceList, res api.ResourceName) bool {
	val, ok := actual[res]
	expVal, expOk := expected[res]
	if ok != expOk {
		return true
	}
	if !ok && !expOk {
		return false
	}
	q := new(inf.Dec).QuoRound(val.Amount, expVal.Amount, 2, inf.RoundDown)
	lower := inf.NewDec(100-threshold, 2)
	upper := inf.NewDec(100+threshold, 2)
	if q.Cmp(lower) == -1 || q.Cmp(upper) == 1 {
		return true
	}
	return false
}
Пример #9
0
// TODO this will need to update when we have pod requests/limits
func (a *clusterResourceOverridePlugin) Admit(attr admission.Attributes) error {
	glog.V(6).Infof("%s admission controller is invoked", api.PluginName)
	if a.config == nil || attr.GetResource() != kapi.Resource("pods") || attr.GetSubresource() != "" {
		return nil // not applicable
	}
	pod, ok := attr.GetObject().(*kapi.Pod)
	if !ok {
		return admission.NewForbidden(attr, fmt.Errorf("unexpected object: %#v", attr.GetObject()))
	}
	glog.V(5).Infof("%s is looking at creating pod %s in project %s", api.PluginName, pod.Name, attr.GetNamespace())

	// allow annotations on project to override
	if ns, err := a.ProjectCache.GetNamespace(attr.GetNamespace()); err != nil {
		glog.Warningf("%s got an error retrieving namespace: %v", api.PluginName, err)
		return admission.NewForbidden(attr, err) // this should not happen though
	} else {
		projectEnabledPlugin, exists := ns.Annotations[clusterResourceOverrideAnnotation]
		if exists && projectEnabledPlugin != "true" {
			glog.V(5).Infof("%s is disabled for project %s", api.PluginName, attr.GetNamespace())
			return nil // disabled for this project, do nothing
		}
	}

	// Reuse LimitRanger logic to apply limit/req defaults from the project. Ignore validation
	// errors, assume that LimitRanger will run after this plugin to validate.
	glog.V(5).Infof("%s: initial pod limits are: %#v", api.PluginName, pod.Spec.Containers[0].Resources)
	if err := a.LimitRanger.Admit(attr); err != nil {
		glog.V(5).Infof("%s: error from LimitRanger: %#v", api.PluginName, err)
	}
	glog.V(5).Infof("%s: pod limits after LimitRanger are: %#v", api.PluginName, pod.Spec.Containers[0].Resources)
	for _, container := range pod.Spec.Containers {
		resources := container.Resources
		memLimit, memFound := resources.Limits[kapi.ResourceMemory]
		if memFound && a.config.memoryRequestToLimitRatio.Cmp(zeroDec) != 0 {
			resources.Requests[kapi.ResourceMemory] = resource.Quantity{
				Amount: multiply(memLimit.Amount, a.config.memoryRequestToLimitRatio),
				Format: resource.BinarySI,
			}
		}
		if memFound && a.config.limitCPUToMemoryRatio.Cmp(zeroDec) != 0 {
			resources.Limits[kapi.ResourceCPU] = resource.Quantity{
				// float math is necessary here as there is no way to create an inf.Dec to represent cpuBaseScaleFactor < 0.001
				Amount: multiply(inf.NewDec(int64(float64(memLimit.Value())*cpuBaseScaleFactor), 3), a.config.limitCPUToMemoryRatio),
				Format: resource.DecimalSI,
			}
		}
		cpuLimit, cpuFound := resources.Limits[kapi.ResourceCPU]
		if cpuFound && a.config.cpuRequestToLimitRatio.Cmp(zeroDec) != 0 {
			resources.Requests[kapi.ResourceCPU] = resource.Quantity{
				Amount: multiply(cpuLimit.Amount, a.config.cpuRequestToLimitRatio),
				Format: resource.DecimalSI,
			}
		}
	}
	glog.V(5).Infof("%s: pod limits after overrides are: %#v", api.PluginName, pod.Spec.Containers[0].Resources)
	return nil
}
Пример #10
0
// newClusterResourceOverride returns an admission controller for containers that
// configurably overrides container resource request/limits
func newClusterResourceOverride(client clientset.Interface, config *api.ClusterResourceOverrideConfig) (admission.Interface, error) {
	glog.V(2).Infof("%s admission controller loaded with config: %v", api.PluginName, config)
	var internal *internalConfig
	if config != nil {
		internal = &internalConfig{
			limitCPUToMemoryRatio:     inf.NewDec(config.LimitCPUToMemoryPercent, 2),
			cpuRequestToLimitRatio:    inf.NewDec(config.CPURequestToLimitPercent, 2),
			memoryRequestToLimitRatio: inf.NewDec(config.MemoryRequestToLimitPercent, 2),
		}
	}

	limitRanger, err := limitranger.NewLimitRanger(client, &limitRangerActions{})
	if err != nil {
		return nil, err
	}

	return &clusterResourceOverridePlugin{
		Handler:     admission.NewHandler(admission.Create),
		config:      internal,
		LimitRanger: limitRanger,
	}, nil
}
Пример #11
0
func TestSemantic(t *testing.T) {
	table := []struct {
		a, b        interface{}
		shouldEqual bool
	}{
		{resource.MustParse("0"), resource.Quantity{}, true},
		{resource.Quantity{}, resource.MustParse("0"), true},
		{resource.Quantity{}, resource.MustParse("1m"), false},
		{
			resource.Quantity{inf.NewDec(5, 0), resource.BinarySI},
			resource.Quantity{inf.NewDec(5, 0), resource.DecimalSI},
			true,
		},
		{resource.MustParse("2m"), resource.MustParse("1m"), false},
	}

	for index, item := range table {
		if e, a := item.shouldEqual, Semantic.DeepEqual(item.a, item.b); e != a {
			t.Errorf("case[%d], expected %v, got %v.", index, e, a)
		}
	}
}
Пример #12
0
func TestDecSetString(t *testing.T) {
	tmp := new(inf.Dec)
	for i, test := range decStringTests {
		if test.scale < 0 {
			// SetString only supports scale >= 0
			continue
		}
		// initialize to a non-zero value so that issues with parsing
		// 0 are detected
		tmp.Set(inf.NewDec(1234567890, 123))
		n1, ok1 := new(inf.Dec).SetString(test.in)
		n2, ok2 := tmp.SetString(test.in)
		expected := inf.NewDec(test.val, test.scale)
		if ok1 != test.ok || ok2 != test.ok {
			t.Errorf("#%d (input '%s') ok incorrect (should be %t)", i, test.in, test.ok)
			continue
		}
		if !ok1 {
			if n1 != nil {
				t.Errorf("#%d (input '%s') n1 != nil", i, test.in)
			}
			continue
		}
		if !ok2 {
			if n2 != nil {
				t.Errorf("#%d (input '%s') n2 != nil", i, test.in)
			}
			continue
		}

		if n1.Cmp(expected) != 0 {
			t.Errorf("#%d (input '%s') got: %s want: %d", i, test.in, n1, test.val)
		}
		if n2.Cmp(expected) != 0 {
			t.Errorf("#%d (input '%s') got: %s want: %d", i, test.in, n2, test.val)
		}
	}
}
Пример #13
0
func TestRowBinding(t *testing.T) {
	header := []string{"n", "d", "c", "r"}
	row := []string{"foo", "2014-04-06 10:02:21", "4459813", "1.55"}
	input := [][]string{header, row}
	s := make(map[string]string)
	s["n"] = "Name"
	s["d"] = "Date"
	s["c"] = "Counter"
	s["r"] = "Rating"
	d := Destination{
		Name:    "foo",
		Counter: 4459813,
		Date:    time.Date(2014, 4, 6, 10, 02, 21, 0, time.UTC),
		Rating:  inf.NewDec(155, 2),
	}
	runScenario(t, input, s, d)
}
Пример #14
0
func (e LinearEstimator) scaleWithNodes(numNodes uint64) *api.ResourceRequirements {
	limits := make(api.ResourceList)
	requests := make(api.ResourceList)
	for _, r := range e.Resources {
		num := inf.NewDec(int64(numNodes), 0)
		num.Mul(num, r.ExtraPerNode.Amount)
		num.Add(num, r.Base.Amount)
		limits[r.Name] = resource.Quantity{
			Amount: num,
			Format: r.Base.Format,
		}
		requests[r.Name] = resource.Quantity{
			Amount: num,
			Format: r.Base.Format,
		}
	}
	return &api.ResourceRequirements{
		Limits:   limits,
		Requests: requests,
	}
}
Пример #15
0
type Page struct {
	Title       string
	RevId       UUID
	Body        string
	Views       int64
	Protected   bool
	Modified    time.Time
	Rating      *inf.Dec
	Tags        []string
	Attachments map[string]Attachment
}

type Attachment []byte

var rating, _ = inf.NewDec(0, 0).SetString("0.131")

var pageTestData = []*Page{
	&Page{
		Title:    "Frontpage",
		RevId:    TimeUUID(),
		Body:     "Welcome to this wiki page!",
		Rating:   rating,
		Modified: time.Date(2013, time.August, 13, 9, 52, 3, 0, time.UTC),
		Tags:     []string{"start", "important", "test"},
		Attachments: map[string]Attachment{
			"logo":    Attachment("\x00company logo\x00"),
			"favicon": Attachment("favicon.ico"),
		},
	},
	&Page{
Пример #16
0
func multiply(x *inf.Dec, y *inf.Dec) *inf.Dec {
	return inf.NewDec(0, 0).Mul(x, y)
}
Пример #17
0
	"k8s.io/kubernetes/pkg/api/resource"
	clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset"
	"k8s.io/kubernetes/pkg/runtime"
	"k8s.io/kubernetes/plugin/pkg/admission/limitranger"

	"github.com/golang/glog"
	"speter.net/go/exp/math/dec/inf"
)

const (
	clusterResourceOverrideAnnotation = "quota.openshift.io/cluster-resource-override-enabled"
	cpuBaseScaleFactor                = 1000.0 / (1024.0 * 1024.0 * 1024.0) // 1000 milliCores per 1GiB
)

var (
	zeroDec = inf.NewDec(0, 0)
)

func init() {
	admission.RegisterPlugin(api.PluginName, func(client clientset.Interface, config io.Reader) (admission.Interface, error) {
		return newClusterResourceOverride(client, config)
	})
}

type internalConfig struct {
	limitCPUToMemoryRatio     *inf.Dec
	cpuRequestToLimitRatio    *inf.Dec
	memoryRequestToLimitRatio *inf.Dec
}
type clusterResourceOverridePlugin struct {
	*admission.Handler
Пример #18
0
func main() {

	session := integration.TestSession("127.0.0.1", "cqlc")
	integration.Truncate(session, BASIC)

	result := "FAILED"

	ctx := cqlc.NewContext()

	basic := Basic{
		Id:              "x",
		Int32Column:     111,
		Int64Column:     1 << 32,
		AsciiColumn:     "ABC",
		TimestampColumn: time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC), // Keep it simple for reflect.DeepEqual
		BooleanColumn:   true,
		TextColumn:      "foo",
		VarcharColumn:   "bar",
		FloatColumn:     math.MaxFloat32,
		DoubleColumn:    math.MaxFloat64,
		DecimalColumn:   inf.NewDec(1, 3),
		TimeuuidColumn:  gocql.TimeUUID(),
		MapColumn:       map[string]string{"baz": "quux"},
		ArrayColumn:     []string{"baz", "quux"},
	}

	create(ctx, session, basic)

	iter, err := ctx.Select(
		BASIC.ID,
		BASIC.ASCII_COLUMN,
		BASIC.INT32_COLUMN,
		BASIC.INT64_COLUMN,
		BASIC.FLOAT_COLUMN,
		BASIC.DOUBLE_COLUMN,
		BASIC.DECIMAL_COLUMN,
		BASIC.TIMESTAMP_COLUMN,
		BASIC.TIMEUUID_COLUMN,
		BASIC.BOOLEAN_COLUMN,
		BASIC.TEXT_COLUMN,
		BASIC.VARCHAR_COLUMN,
		BASIC.MAP_COLUMN,
		BASIC.ARRAY_COLUMN).
		From(BASIC).
		Where(BASIC.ID.Eq("x")).
		Fetch(session)

	if err != nil {
		log.Fatalf("Could not bind data: %v", err)
		os.Exit(1)
	}

	result, _ = checkBasics(iter, basic)

	iter, err = ctx.Select(
		BASIC.ID,
		BASIC.ASCII_COLUMN,
		BASIC.INT32_COLUMN,
		BASIC.INT64_COLUMN,
		BASIC.FLOAT_COLUMN,
		BASIC.DOUBLE_COLUMN,
		BASIC.DECIMAL_COLUMN,
		BASIC.TIMESTAMP_COLUMN,
		BASIC.TIMEUUID_COLUMN,
		BASIC.BOOLEAN_COLUMN,
		BASIC.TEXT_COLUMN,
		BASIC.VARCHAR_COLUMN,
		BASIC.MAP_COLUMN,
		BASIC.ARRAY_COLUMN).
		From(BASIC).
		Fetch(session)

	if err != nil {
		log.Fatalf("Could not bind data: %v", err)
		os.Exit(1)
	}

	result, _ = checkBasics(iter, basic)

	// TODO write test case for a non-matching WHERE clause

	os.Stdout.WriteString(result)
}
Пример #19
0
func dec(i int64, exponent int) *inf.Dec {
	// See the below test-- scale is the negative of an exponent.
	return inf.NewDec(i, inf.Scale(-exponent))
}
Пример #20
0
func divide(x *inf.Dec, y *inf.Dec, s inf.Scale, r inf.Rounder) *inf.Dec {
	return inf.NewDec(0, 0).QuoRound(x, y, s, r)
}
Пример #21
0
package gocql

import (
	"bytes"
	"math"
	"reflect"
	"speter.net/go/exp/math/dec/inf"
	"strings"
	"testing"
	"time"
)

var quarter, _ = inf.NewDec(0, 0).SetString("0.25")

var marshalTests = []struct {
	Info  *TypeInfo
	Data  []byte
	Value interface{}
}{
	{
		&TypeInfo{Type: TypeVarchar},
		[]byte("hello world"),
		[]byte("hello world"),
	},
	{
		&TypeInfo{Type: TypeVarchar},
		[]byte("hello world"),
		"hello world",
	},
	{
		&TypeInfo{Type: TypeVarchar},
Пример #22
0
func main() {

	session := integration.TestSession("127.0.0.1", "cqlc")
	integration.Truncate(session, BASIC)

	result := "FAILED"

	ctx := cqlc.NewContext()

	basic := Basic{
		Id:              "x",
		Int32Column:     999,
		Int64Column:     1 << 55,
		AsciiColumn:     "do-re-me",
		TimestampColumn: time.Date(1999, time.December, 31, 23, 59, 59, 59, time.UTC), // Keep it simple for reflect.DeepEqual
		BooleanColumn:   true,
		TextColumn:      "ipso",
		VarcharColumn:   "lorem",
		FloatColumn:     math.MaxFloat32,
		DoubleColumn:    math.MaxFloat64,
		DecimalColumn:   inf.NewDec(1, 9),
		TimeuuidColumn:  gocql.TimeUUID(),
		MapColumn:       map[string]string{"baz": "quux"},
		ArrayColumn:     []string{"baz", "quux"},
	}

	err := ctx.Store(BASIC.Bind(basic)).Exec(session)

	if err != nil {
		log.Fatalf("Could not bind data: %v", err)
		os.Exit(1)
	}

	var int32Column int32
	var decimalColumn *inf.Dec

	found, err := ctx.Select().
		From(BASIC).
		Where(BASIC.ID.Eq("x")).
		Bind(BASIC.INT32_COLUMN.To(&int32Column), BASIC.DECIMAL_COLUMN.To(&decimalColumn)).
		FetchOne(session)

	if err != nil {
		log.Fatalf("Could not bind data: %v", err)
		os.Exit(1)
	}

	if err != nil {
		log.Fatalf("Could not bind data: %v", err)
		os.Exit(1)
	}

	if int32Column == 999 && reflect.DeepEqual(decimalColumn, basic.DecimalColumn) && found {

		found, err := ctx.Select().
			From(BASIC).
			Where(BASIC.ID.Eq("y")).
			Bind(BASIC.INT32_COLUMN.To(&int32Column), BASIC.DECIMAL_COLUMN.To(&decimalColumn)).
			FetchOne(session)

		if err != nil {
			log.Fatalf("Could not bind data: %v", err)
			os.Exit(1)
		}

		if !found {
			result = "PASSED"
		}

	} else {
		result = fmt.Sprintf("int32Column: %d, decimalColumn %v", int32Column, decimalColumn)
	}

	os.Stdout.WriteString(result)

}
Пример #23
0
	"k8s.io/kubernetes/pkg/api/resource"
	clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset"
	"k8s.io/kubernetes/pkg/runtime"
	"k8s.io/kubernetes/plugin/pkg/admission/limitranger"

	"github.com/golang/glog"
	"speter.net/go/exp/math/dec/inf"
)

const (
	clusterResourceOverrideAnnotation = "quota.openshift.io/cluster-resource-override-enabled"
	cpuBaseScaleFactor                = 1000.0 / (1024.0 * 1024.0 * 1024.0) // 1000 milliCores per 1GiB
)

var (
	zeroDec  = inf.NewDec(0, 0)
	miDec    = inf.NewDec(1024*1024, 0)
	cpuFloor = resource.MustParse("1m")
	memFloor = resource.MustParse("1Mi")
)

func init() {
	admission.RegisterPlugin(api.PluginName, func(client clientset.Interface, config io.Reader) (admission.Interface, error) {
		pluginConfig, err := ReadConfig(config)
		if err != nil {
			return nil, err
		}
		if pluginConfig == nil {
			glog.Infof("Admission plugin %q is not configured so it will be disabled.", api.PluginName)
			return nil, nil
		}
func TestSliceMap(t *testing.T) {
	session := createSession(t)
	defer session.Close()
	if err := createTable(session, `CREATE TABLE slice_map_table (
			testuuid       timeuuid PRIMARY KEY,
			testtimestamp  timestamp,
			testvarchar    varchar,
			testbigint     bigint,
			testblob       blob,
			testbool       boolean,
			testfloat      float,
			testdouble     double,
			testint        int,
			testdecimal    decimal,
			testlist       list<text>,
			testset        set<int>,
			testmap        map<varchar, varchar>,
			testvarint     varint,
			testinet			 inet
		)`); err != nil {
		t.Fatal("create table:", err)
	}
	m := make(map[string]interface{})

	bigInt := new(big.Int)
	if _, ok := bigInt.SetString("830169365738487321165427203929228", 10); !ok {
		t.Fatal("Failed setting bigint by string")
	}

	m["testuuid"] = TimeUUID()
	m["testvarchar"] = "Test VarChar"
	m["testbigint"] = time.Now().Unix()
	m["testtimestamp"] = time.Now().Truncate(time.Millisecond).UTC()
	m["testblob"] = []byte("test blob")
	m["testbool"] = true
	m["testfloat"] = float32(4.564)
	m["testdouble"] = float64(4.815162342)
	m["testint"] = 2343
	m["testdecimal"] = inf.NewDec(100, 0)
	m["testlist"] = []string{"quux", "foo", "bar", "baz", "quux"}
	m["testset"] = []int{1, 2, 3, 4, 5, 6, 7, 8, 9}
	m["testmap"] = map[string]string{"field1": "val1", "field2": "val2", "field3": "val3"}
	m["testvarint"] = bigInt
	m["testinet"] = "213.212.2.19"
	sliceMap := []map[string]interface{}{m}
	if err := session.Query(`INSERT INTO slice_map_table (testuuid, testtimestamp, testvarchar, testbigint, testblob, testbool, testfloat, testdouble, testint, testdecimal, testlist, testset, testmap, testvarint, testinet) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
		m["testuuid"], m["testtimestamp"], m["testvarchar"], m["testbigint"], m["testblob"], m["testbool"], m["testfloat"], m["testdouble"], m["testint"], m["testdecimal"], m["testlist"], m["testset"], m["testmap"], m["testvarint"], m["testinet"]).Exec(); err != nil {
		t.Fatal("insert:", err)
	}
	if returned, retErr := session.Query(`SELECT * FROM slice_map_table`).Iter().SliceMap(); retErr != nil {
		t.Fatal("select:", retErr)
	} else {
		if sliceMap[0]["testuuid"] != returned[0]["testuuid"] {
			t.Fatal("returned testuuid did not match")
		}
		if sliceMap[0]["testtimestamp"] != returned[0]["testtimestamp"] {
			t.Fatalf("returned testtimestamp did not match: %v %v", sliceMap[0]["testtimestamp"], returned[0]["testtimestamp"])
		}
		if sliceMap[0]["testvarchar"] != returned[0]["testvarchar"] {
			t.Fatal("returned testvarchar did not match")
		}
		if sliceMap[0]["testbigint"] != returned[0]["testbigint"] {
			t.Fatal("returned testbigint did not match")
		}
		if !reflect.DeepEqual(sliceMap[0]["testblob"], returned[0]["testblob"]) {
			t.Fatal("returned testblob did not match")
		}
		if sliceMap[0]["testbool"] != returned[0]["testbool"] {
			t.Fatal("returned testbool did not match")
		}
		if sliceMap[0]["testfloat"] != returned[0]["testfloat"] {
			t.Fatal("returned testfloat did not match")
		}
		if sliceMap[0]["testdouble"] != returned[0]["testdouble"] {
			t.Fatal("returned testdouble did not match")
		}
		if sliceMap[0]["testint"] != returned[0]["testint"] {
			t.Fatal("returned testint did not match")
		}

		expectedDecimal := sliceMap[0]["testdecimal"].(*inf.Dec)
		returnedDecimal := returned[0]["testdecimal"].(*inf.Dec)

		if expectedDecimal.Cmp(returnedDecimal) != 0 {
			t.Fatal("returned testdecimal did not match")
		}
		if !reflect.DeepEqual(sliceMap[0]["testlist"], returned[0]["testlist"]) {
			t.Fatal("returned testlist did not match")
		}
		if !reflect.DeepEqual(sliceMap[0]["testset"], returned[0]["testset"]) {
			t.Fatal("returned testset did not match")
		}
		if !reflect.DeepEqual(sliceMap[0]["testmap"], returned[0]["testmap"]) {
			t.Fatal("returned testmap did not match")
		}

		expectedBigInt := sliceMap[0]["testvarint"].(*big.Int)
		returnedBigInt := returned[0]["testvarint"].(*big.Int)
		if expectedBigInt.Cmp(returnedBigInt) != 0 {
			t.Fatal("returned testvarint did not match")
		}

		if sliceMap[0]["testinet"] != returned[0]["testinet"] {
			t.Fatal("returned testinet did not match")
		}
	}

	// Test for MapScan()
	testMap := make(map[string]interface{})
	if !session.Query(`SELECT * FROM slice_map_table`).Iter().MapScan(testMap) {
		t.Fatal("MapScan failed to work with one row")
	}
	if sliceMap[0]["testuuid"] != testMap["testuuid"] {
		t.Fatal("returned testuuid did not match")
	}
	if sliceMap[0]["testtimestamp"] != testMap["testtimestamp"] {
		t.Fatal("returned testtimestamp did not match")
	}
	if sliceMap[0]["testvarchar"] != testMap["testvarchar"] {
		t.Fatal("returned testvarchar did not match")
	}
	if sliceMap[0]["testbigint"] != testMap["testbigint"] {
		t.Fatal("returned testbigint did not match")
	}
	if !reflect.DeepEqual(sliceMap[0]["testblob"], testMap["testblob"]) {
		t.Fatal("returned testblob did not match")
	}
	if sliceMap[0]["testbool"] != testMap["testbool"] {
		t.Fatal("returned testbool did not match")
	}
	if sliceMap[0]["testfloat"] != testMap["testfloat"] {
		t.Fatal("returned testfloat did not match")
	}
	if sliceMap[0]["testdouble"] != testMap["testdouble"] {
		t.Fatal("returned testdouble did not match")
	}
	if sliceMap[0]["testinet"] != testMap["testinet"] {
		t.Fatal("returned testinet did not match")
	}

	expectedDecimal := sliceMap[0]["testdecimal"].(*inf.Dec)
	returnedDecimal := testMap["testdecimal"].(*inf.Dec)

	if expectedDecimal.Cmp(returnedDecimal) != 0 {
		t.Fatal("returned testdecimal did not match")
	}

	if !reflect.DeepEqual(sliceMap[0]["testlist"], testMap["testlist"]) {
		t.Fatal("returned testlist did not match")
	}
	if !reflect.DeepEqual(sliceMap[0]["testset"], testMap["testset"]) {
		t.Fatal("returned testset did not match")
	}
	if !reflect.DeepEqual(sliceMap[0]["testmap"], testMap["testmap"]) {
		t.Fatal("returned testmap did not match")
	}
	if sliceMap[0]["testint"] != testMap["testint"] {
		t.Fatal("returned testint did not match")
	}
}
Пример #25
0
		true,
	},
	{
		&TypeInfo{Type: TypeFloat},
		[]byte("\x40\x49\x0f\xdb"),
		float32(3.14159265),
	},
	{
		&TypeInfo{Type: TypeDouble},
		[]byte("\x40\x09\x21\xfb\x53\xc8\xd4\xf1"),
		float64(3.14159265),
	},
	{
		&TypeInfo{Type: TypeDecimal},
		[]byte("\x00\x00\x00\x00\x00"),
		inf.NewDec(0, 0),
	},
	{
		&TypeInfo{Type: TypeDecimal},
		[]byte("\x00\x00\x00\x00\x64"),
		inf.NewDec(100, 0),
	},
	{
		&TypeInfo{Type: TypeDecimal},
		[]byte("\x00\x00\x00\x02\x19"),
		decimalize("0.25"),
	},
	{
		&TypeInfo{Type: TypeDecimal},
		[]byte("\x00\x00\x00\x13\xD5\a;\x20\x14\xA2\x91"),
		decimalize("-0.0012095473475870063"), // From the iconara/cql-rb test suite
Пример #26
0
// NewScaledQuantity returns a new Quantity representing the given
// value * 10^scale in DecimalSI format.
func NewScaledQuantity(value int64, scale Scale) *Quantity {
	return &Quantity{
		Amount: inf.NewDec(value, scale.infScale()),
		Format: DecimalSI,
	}
}
Пример #27
0
	splitRE = regexp.MustCompile(splitREString)

	// Errors that could happen while parsing a string.
	ErrFormatWrong = errors.New("quantities must match the regular expression '" + splitREString + "'")
	ErrNumeric     = errors.New("unable to parse numeric part of quantity")
	ErrSuffix      = errors.New("unable to parse quantity's suffix")

	// Commonly needed big.Int values-- treat as read only!
	bigTen      = big.NewInt(10)
	bigZero     = big.NewInt(0)
	bigOne      = big.NewInt(1)
	bigThousand = big.NewInt(1000)
	big1024     = big.NewInt(1024)

	// Commonly needed inf.Dec values-- treat as read only!
	decZero      = inf.NewDec(0, 0)
	decOne       = inf.NewDec(1, 0)
	decMinusOne  = inf.NewDec(-1, 0)
	decThousand  = inf.NewDec(1000, 0)
	dec1024      = inf.NewDec(1024, 0)
	decMinus1024 = inf.NewDec(-1024, 0)

	// Largest (in magnitude) number allowed.
	maxAllowed = inf.NewDec((1<<63)-1, 0) // == max int64

	// The maximum value we can represent milli-units for.
	// Compare with the return value of Quantity.Value() to
	// see if it's safe to use Quantity.MilliValue().
	MaxMilliValue = int64(((1 << 63) - 1) / 1000)
)
Пример #28
0
func dec(i int64, exponent int) *inf.Dec {
	return inf.NewDec(i, inf.Scale(-exponent))
}
Пример #29
0
// NewMilliQuantity returns a new Quantity representing the given
// value * 1/1000 in the given format. Note that BinarySI formatting
// will round fractional values, and will be changed to DecimalSI for
// values x where (-1 < x < 1) && (x != 0).
func NewMilliQuantity(value int64, format Format) *Quantity {
	return &Quantity{
		Amount: inf.NewDec(value, 3),
		Format: format,
	}
}
Пример #30
0
	Views       int64
	Protected   bool
	Modified    time.Time
	Rating      *inf.Dec
	Tags        []string
	Attachments map[string]WikiAttachment
}

type WikiAttachment []byte

var wikiTestData = []*WikiPage{
	&WikiPage{
		Title:    "Frontpage",
		RevId:    TimeUUID(),
		Body:     "Welcome to this wiki page!",
		Rating:   inf.NewDec(131, 3),
		Modified: time.Date(2013, time.August, 13, 9, 52, 3, 0, time.UTC),
		Tags:     []string{"start", "important", "test"},
		Attachments: map[string]WikiAttachment{
			"logo":    WikiAttachment("\x00company logo\x00"),
			"favicon": WikiAttachment("favicon.ico"),
		},
	},
	&WikiPage{
		Title:    "Foobar",
		RevId:    TimeUUID(),
		Body:     "foo::Foo f = new foo::Foo(foo::Foo::INIT);",
		Modified: time.Date(2013, time.August, 13, 9, 52, 3, 0, time.UTC),
	},
}