Exemplo n.º 1
0
func BenchmarkDoCreateAccount(b *testing.B) {
	for n := 0; n < b.N; n++ {
		accountDetail := AccountDetails{
			"",
			"",
			"User,Test",
			decimal.NewFromFloat(0.),
			decimal.NewFromFloat(0.),
			decimal.NewFromFloat(0.),
			"cheque",
			0,
		}

		accountHolderDetail := AccountHolderDetails{
			"Test",
			"User",
			"1900-01-01",
			"19000101-1000-100",
			"555-123-1234",
			"",
			"*****@*****.**",
			"Address 1",
			"Address 2",
			"Address 3",
			"22202",
		}

		ti := time.Now()
		sqlTime := int32(ti.Unix())
		_ = doCreateAccount(sqlTime, &accountDetail, &accountHolderDetail)
		_ = doDeleteAccount(&accountDetail)
	}
}
Exemplo n.º 2
0
func setAccountDetails(data []string) (accountDetails AccountDetails, err error) {
	if len(data) < 15 {
		return AccountDetails{}, errors.New("accounts.setAccountDetails: Not all fields required present")
	}

	if data[4] == "" {
		return AccountDetails{}, errors.New("accounts.setAccountDetails: Family name cannot be empty")
	}
	if data[3] == "" {
		return AccountDetails{}, errors.New("accounts.setAccountDetails: Given name cannot be empty")
	}
	accountDetails.BankNumber = BANK_NUMBER
	accountDetails.AccountHolderName = data[4] + "," + data[3] // Family Name, Given Name
	accountDetails.AccountBalance = decimal.NewFromFloat(OPENING_BALANCE)
	accountDetails.Overdraft = decimal.NewFromFloat(OPENING_OVERDRAFT)
	accountDetails.AvailableBalance = decimal.NewFromFloat(OPENING_BALANCE + OPENING_OVERDRAFT)
	// Get account type
	accountType := data[14]
	switch accountType {
	case "":
		accountType = "cheque" // Default to chequing account
		break
	case "savings", "cheque", "merchant", "money-market", "cd", "ira", "rcp", "credit", "mortgage", "loan":
		// Valid
		break
	default:
		return AccountDetails{}, errors.New("accounts.setAccountDetails: Account type not valid, must be one of savings, cheque, merchant, money-market, cd, ira, rcp, credit, mortgage, loan")
		break
	}
	accountDetails.Type = accountType

	return
}
Exemplo n.º 3
0
//Encode generates a geozip bucket id for a given latitude and longitude.
//Argument validate is true if a validation is to be performed.
//Precision is a number in the range of [0, 18] such that 0 gives lowest precision (000000000000000000) and 18 gives the most precise bucket id.
func Encode(latitude, longitude float64, validate bool, precision int) int64 {
	if validate && !Valid(latitude, longitude) {
		return 0
	}
	latitudeShifted := decimal.NewFromFloat(latitude).Add(decimal.NewFromFloat(90.0))
	longitudeShifted := decimal.NewFromFloat(longitude).Add(decimal.NewFromFloat(180.0))
	latString := latitudeShifted.String() + ".0"
	lonString := longitudeShifted.String() + ".0"
	latParts := strings.Split(latString, ".")
	lonParts := strings.Split(lonString, ".")
	latString = resizeCharacteristic(latParts[0]) + resizeMantissa(latParts[1])
	lonString = resizeCharacteristic(lonParts[0]) + resizeMantissa(lonParts[1])
	bucketString := zip(latString, lonString)
	bucket, err := strconv.ParseInt(bucketString, 10, 64)
	if err != nil {
		fmt.Errorf("Error parsing zipped string to int64")
	}
	for i := 0; i < maxPrecision-precision; i++ {
		bucket /= 10
	}
	for i := 0; i < maxPrecision-precision; i++ {
		bucket *= 10
	}
	return bucket
}
Exemplo n.º 4
0
func Money(value interface{}, code string) (MoneyObject, error) {
	currency, found := CurrencyTypes[code]
	if !found {
		return MoneyObject{}, errors.New("Code not found.")
	}

	var money decimal.Decimal
	var moneyObject MoneyObject

	switch v := value.(type) {
	case string:
		m, err := decimal.NewFromString(v)
		if err != nil {
			return MoneyObject{}, err
		}
		money = m
	case float32:
		money = decimal.NewFromFloat(float64(v))
	case float64:
		money = decimal.NewFromFloat(v)
	case int:
		money = decimal.NewFromFloat(float64(v))
	default:
		return MoneyObject{}, errors.New("Value could not be translated.")
	}

	moneyObject.money = money
	moneyObject.currency = currency

	return moneyObject, nil
}
Exemplo n.º 5
0
func TestDoCreateAccount(t *testing.T) {
	//accountDetails AccountDetails, accountHolderDetails AccountHolderDetails
	accountDetail := AccountDetails{
		"",
		"",
		"User,Test",
		decimal.NewFromFloat(0.),
		decimal.NewFromFloat(0.),
		decimal.NewFromFloat(0.),
		0,
	}

	ti := time.Now()
	sqlTime := int32(ti.Unix())
	err := doCreateAccount(sqlTime, &accountDetail)

	if err != nil {
		t.Errorf("DoCreateAccount does not pass. Looking for %v, got %v", nil, err)
	}

	err = doDeleteAccount(&accountDetail)
	if err != nil {
		t.Errorf("DoDeleteAccount does not pass. Looking for %v, got %v", nil, err)
	}
}
Exemplo n.º 6
0
//Decode is the inverse operation of Encode.
//Decode returns latitude, longitude, and whether or not they are both represented precisely as float64 types.
func Decode(bucket int64) (float64, float64, bool) {
	var latitudeUnshifted, longitudeUnshifted decimal.Decimal
	var latitude, longitude float64
	var err error
	var exact bool
	bucketString := strconv.FormatInt(bucket, 10)
	for len(bucketString) < 18 {
		bucketString = "0" + bucketString
	}

	latString, lonString := unzip(bucketString)
	latString = latString[0:3] + "." + latString[3:]
	lonString = lonString[0:3] + "." + lonString[3:]

	latitudeUnshifted, err = decimal.NewFromString(latString)
	longitudeUnshifted, err = decimal.NewFromString(lonString)
	if err != nil {
		fmt.Errorf("Error creating decimal from string")
	}
	latitudeUnshifted = latitudeUnshifted.Sub(decimal.NewFromFloat(90.0))
	longitudeUnshifted = longitudeUnshifted.Sub(decimal.NewFromFloat(180.0))
	latitude, exact = latitudeUnshifted.Float64()
	longitude, exact = longitudeUnshifted.Float64()
	return latitude, longitude, exact
}
Exemplo n.º 7
0
func TestSquareRootOfFour(t *testing.T) {
	four := decimal.NewFromFloat(4.0)
	sqrt := Sqrt(four)
	if !sqrt.Equals(decimal.NewFromFloat(2.0)) {
		t.Fatalf("Square root of %s is %s", four, sqrt)
	}
	t.Logf("Square root of %s is %s", four, sqrt)
}
Exemplo n.º 8
0
func BenchmarkAddDecimalWithoutNew(b *testing.B) {
	decimalStartFloat := decimal.NewFromFloat(StartFloat)
	decimalFactor := decimal.NewFromFloat(Factor)

	for n := 0; n < b.N; n++ {
		AddDecimalWithoutNew(decimalStartFloat, decimalFactor)
	}
}
Exemplo n.º 9
0
func AddDecimal() (calculated decimal.Decimal) {
	decimalStartFloat := decimal.NewFromFloat(StartFloat)
	decimalFactor := decimal.NewFromFloat(Factor)

	calculated = decimalStartFloat.Add(decimalFactor)

	return
}
Exemplo n.º 10
0
func MultiplyDecimal() (calculated decimal.Decimal) {
	decimalStartFloat := decimal.NewFromFloat(StartFloat)
	decimalFactor := decimal.NewFromFloat(Factor)

	calculated = decimalStartFloat.Mul(decimalFactor)

	return
}
Exemplo n.º 11
0
func TestCanWidthdraw(t *testing.T) {

	account := CreateAccount(10)
	account.Deposit(decimal.NewFromFloat(20))

	account.Withdraw(decimal.NewFromFloat(50))
	assert.Equal(t, decimal.NewFromFloat(20).String(), account.GetBalance().String())

}
Exemplo n.º 12
0
// Square root using Newton's method
// Shamelessly ripped from https://gist.github.com/marcellodesales/2487009
func Sqrt(x decimal.Decimal) decimal.Decimal {
	p := decimal.NewFromFloat(0.0)
	z := decimal.NewFromFloat(1.0)
	for !p.Sub(z).Equals(ConstMin) {
		z = newton(z, x)
		p = newton(z, x)
	}
	return z
}
Exemplo n.º 13
0
func TestCalculate(t *testing.T) {
	irrf := NewIRRF(irrfByYear["2016"])
	for _, testCase := range testCases {
		irrfDue := irrf.Calculate(decimal.NewFromFloat(testCase.irrfBase))
		if irrfDue.Cmp(decimal.NewFromFloat(testCase.irrfDue)) != 0 {
			t.Errorf("Expected %v, got %v", testCase.irrfDue, irrfDue)
		}
	}
}
Exemplo n.º 14
0
func TestCalculate(t *testing.T) {
	inss := NewINSS(inssByYear["2016"])
	for _, testCase := range testCases {
		inssDue := inss.Calculate(decimal.NewFromFloat(testCase.grossSalary))
		if inssDue.Cmp(decimal.NewFromFloat(testCase.inssDue)) != 0 {
			t.Errorf("Expected %v, got %v", testCase.inssDue, inssDue)
		}
	}
}
Exemplo n.º 15
0
func setupGrid() *Grid {
	grid := NewGrid(NewCoord(decimal.NewFromFloat(0.0),
		decimal.NewFromFloat(0.0)), decimal.NewFromFloat(90.0),
		decimal.NewFromFloat(180.0), nil, nil)
	grid.Append(coordA)
	grid.Append(coordB)
	grid.Append(coordC)
	grid.Append(coordD)
	return grid
}
Exemplo n.º 16
0
func TestDeposit(t *testing.T) {

	account := CreateAccount(10)
	assert.Equal(t, account.GetBalance(), decimal.NewFromFloat(0))

	account.Deposit(decimal.NewFromFloat(2510.50))
	assert.Equal(t, account.GetBalance(), decimal.NewFromFloat(2510.50))

	// Attempt to deposit negative value
	_, err := account.Deposit(decimal.NewFromFloat(-1))
	assert.NotNil(t, err)

}
Exemplo n.º 17
0
func BenchmarkSavePainTransaction(b *testing.B) {
	config, _ := configuration.LoadConfig()
	SetConfig(&config)

	for n := 0; n < b.N; n++ {
		sender := AccountHolder{"accountNumSender", "bankNumSender"}
		receiver := AccountHolder{"accountNumReceiver", "bankNumReceiver"}
		trans := PAINTrans{101, sender, receiver, decimal.NewFromFloat(0.), decimal.NewFromFloat(0.), 10., 10., "Test desc", "approved"}

		_ = savePainTransaction(trans)
		_ = removePainTransaction(trans)
	}
}
Exemplo n.º 18
0
func main() {
	rand.Seed(time.Now().UTC().UnixNano())

	termChan := make(chan os.Signal, 1)
	signal.Notify(termChan, syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM)

	cant := 0
	log.Println("Flooding with transactions... =D")
	initialDate, _ := time.Parse("2-JAN-06 15:04:05", "1-JAN-14 10:00:00")

	for i := 0; i < 5; i++ {
		go func() {
			for {
				id := fmt.Sprintf("%v", rand.Intn(10000))
				from := randomdata.Currency()
				to := randomdata.Currency()
				rate := decimal.NewFromFloat(randomdata.Decimal(1, 2, 2))
				sell := decimal.NewFromFloat(randomdata.Decimal(50, 1000, 2))
				buy := rate.Mul(sell)
				tp := initialDate.Add(time.Hour * 24 * time.Duration(cant)).
					Format("2-JAN-06 15:04:05")

				oc := randomdata.Country(randomdata.TwoCharCountry)

				m := map[string]interface{}{
					"userId":             id,
					"currencyFrom":       from,
					"currencyTo":         to,
					"amountSell":         sell,
					"amountBuy":          buy,
					"rate":               rate,
					"timePlaced":         tp,
					"originatingCountry": oc,
				}
				mJson, _ := json.Marshal(m)
				contentReader := bytes.NewReader(mJson)
				req, _ := http.NewRequest("POST", "http://localhost:8080/api/v1/transaction", contentReader)
				req.Header.Set("Content-Type", "application/json")
				client := &http.Client{}
				client.Do(req)
				cant++

				time.Sleep(time.Millisecond * time.Duration(3000))
			}
		}()
	}

	<-termChan
	log.Println("total messages:", cant)
}
Exemplo n.º 19
0
func TestSummary(t *testing.T) {
	ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		summaryAPI := fmt.Sprintf("/accounts/%d/summary", TestAccountID)
		assert.Equal(t, summaryAPI, req.RequestURI)

		err := respondWithFixture(w, "summary.json")
		require.NoError(t, err)
	}))
	defer ts.Close()

	ar := newClient(ts.URL, "Token", nil).Accounts(TestAccountID)
	summary, err := ar.Summary()
	require.NoError(t, err)

	assert.Equal(t, 1788402, summary.InvestorID)
	assert.Equal(t, decimal.NewFromFloat(50.77), summary.AvailableCash)
	assert.Equal(t, decimal.NewFromFloat(100.15), summary.AccountTotal)
	assert.Equal(t, decimal.NewFromFloat(0.26), summary.AccruedInterest)
	assert.Equal(t, decimal.NewFromFloat(0), summary.InFundingBalance)
	assert.Equal(t, decimal.NewFromFloat(0.16), summary.ReceivedInterest)
	assert.Equal(t, decimal.NewFromFloat(0.62), summary.ReceivedPrincipal)
	assert.Equal(t, decimal.NewFromFloat(0), summary.ReceivedLateFees)
	assert.Equal(t, decimal.NewFromFloat(49.38), summary.OutstandingPrincipal)
	assert.Equal(t, 2, summary.TotalNotes)
	assert.Equal(t, 3, summary.TotalPortfolios)
}
Exemplo n.º 20
0
func orderTests(t *testing.T, order Order) {
	// Check that dates are parsed
	d := time.Date(2016, time.May, 17, 4, 14, 36, 0, time.UTC)
	if !d.Equal(*order.CreatedAt) {
		t.Errorf("Order.CreatedAt returned %+v, expected %+v", order.CreatedAt, d)
	}

	// Check null dates
	if order.ProcessedAt != nil {
		t.Errorf("Order.ProcessedAt returned %+v, expected %+v", order.ProcessedAt, nil)
	}

	// Check prices
	p := decimal.NewFromFloat(10)
	if !p.Equals(*order.TotalPrice) {
		t.Errorf("Order.TotalPrice returned %+v, expected %+v", order.TotalPrice, p)
	}

	// Check null prices, notice that prices are usually not empty.
	if order.TotalTax != nil {
		t.Errorf("Order.TotalTax returned %+v, expected %+v", order.TotalTax, nil)
	}

	// Check customer
	if order.Customer == nil {
		t.Error("Expected Customer to not be nil")
	}
	if order.Customer.Email != "*****@*****.**" {
		t.Errorf("Customer.Email, expected %v, actual %v", "*****@*****.**", order.Customer.Email)
	}
}
Exemplo n.º 21
0
func DecimalGen(r ohyeah.Int64F) ohyeah.Generator {
	return func() interface{} {
		a := float64(r())
		b := float64(r())
		return decimal.NewFromFloat(a * b)
	}
}
Exemplo n.º 22
0
//小数点绝对值
func AbsDecimal(x float64) float64 {
	xDecimal := decimal.NewFromFloat(x)

	xAbsDecimal := xDecimal.Abs()

	return toFloat64(xAbsDecimal)
}
Exemplo n.º 23
0
func TestWithdrawFunds(t *testing.T) {
	amount := decimal.NewFromFloat(100.0)
	ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		defer req.Body.Close()
		withdrawFundsAPI := fmt.Sprintf("/accounts/%d/funds/withdraw", TestAccountID)
		assert.Equal(t, withdrawFundsAPI, req.RequestURI)

		var body struct {
			Amount decimal.Decimal `json:"amount"`
		}
		err := json.NewDecoder(req.Body).Decode(&body)
		require.NoError(t, err)

		assert.Equal(t, amount, body.Amount)

		err = respondWithFixture(w, "withdraw_funds.json")
		require.NoError(t, err)
	}))
	defer ts.Close()

	ar := newClient(ts.URL, "Token", nil).Accounts(TestAccountID)
	withdrawal, err := ar.WithdrawFunds(amount)
	require.NoError(t, err)

	ti, err := time.Parse(timeFormat, "2015-01-22T00:00:00.000-0800")
	require.NoError(t, err)

	assert.Equal(t, amount, withdrawal.Amount)
	assert.Equal(t, 12345, withdrawal.InvestorID)
	assert.Equal(t, ti, withdrawal.EstimatedFundsTransferDate.Time)
}
Exemplo n.º 24
0
func BenchmarkDoCreateAccount(b *testing.B) {
	for n := 0; n < b.N; n++ {
		accountDetail := AccountDetails{
			"",
			"",
			"User,Test",
			decimal.NewFromFloat(0.),
			decimal.NewFromFloat(0.),
			decimal.NewFromFloat(0.),
			0,
		}

		ti := time.Now()
		sqlTime := int32(ti.Unix())
		_ = doCreateAccount(sqlTime, &accountDetail)
		_ = doDeleteAccount(&accountDetail)
	}
}
Exemplo n.º 25
0
func TestSavePainTransaction(t *testing.T) {
	config, _ := configuration.LoadConfig()
	SetConfig(&config)

	sender := AccountHolder{"accountNumSender", "bankNumSender"}
	receiver := AccountHolder{"accountNumReceiver", "bankNumReceiver"}
	trans := PAINTrans{101, sender, receiver, decimal.NewFromFloat(0.), decimal.NewFromFloat(0.), 10., 10., "Test desc", "approved"}

	err := savePainTransaction(trans)
	if err != nil {
		t.Errorf("DoSavePainTransaction does not pass. Looking for %v, got %v", nil, err)
	}

	err = removePainTransaction(trans)
	if err != nil {
		t.Errorf("DoDeleteAccount does not pass. Looking for %v, got %v", nil, err)
	}
}
Exemplo n.º 26
0
func TestCalculate(t *testing.T) {
	dep := NewDependent(decimal.NewFromFloat(50))
	for _, testCase := range testCases {
		depDeduction := dep.Calculate(testCase.quantity)
		if depDeduction.Cmp(testCase.expected) != 0 {
			t.Errorf("Expected %v, got %v", testCase.expected, depDeduction)
		}
	}
}
Exemplo n.º 27
0
func BenchmarkUpdateHoldingAccount(b *testing.B) {
	config, _ := configuration.LoadConfig()
	SetConfig(&config)

	for n := 0; n < b.N; n++ {
		ti := time.Now()
		sqlTime := int32(ti.Unix())
		_ = updateBankHoldingAccount(decimal.NewFromFloat(0.), sqlTime)
	}
}
Exemplo n.º 28
0
func TestUpdateHoldingAccount(t *testing.T) {
	config, _ := configuration.LoadConfig()
	SetConfig(&config)

	ti := time.Now()
	sqlTime := int32(ti.Unix())

	err := updateBankHoldingAccount(decimal.NewFromFloat(0.), sqlTime)
	if err != nil {
		t.Errorf("DoUpdateHoldingAccount does not pass. Looking for %v, got %v", nil, err)
	}
}
Exemplo n.º 29
0
//具体计算
func operate(a, b float64, oper string) float64 {
	aDecimal := decimal.NewFromFloat(a)
	bDecimal := decimal.NewFromFloat(b)

	rDecimal := decimal.Decimal{}
	switch oper {
	case "add":
		rDecimal = aDecimal.Add(bDecimal)
	case "sub":
		rDecimal = aDecimal.Sub(bDecimal)
	case "mul":
		rDecimal = aDecimal.Mul(bDecimal)
	case "div":
		rDecimal = aDecimal.Div(bDecimal)
	case "mod":
		rDecimal = aDecimal.Mod(bDecimal)
	default:
		panic(errors.New("非法运算符!"))
	}
	return toFloat64(rDecimal)
}
Exemplo n.º 30
0
func TestDiv(t *testing.T) {
	for i := range samp {
		x := copy(samp[0])
		x.Div(samp[0], samp[i])
		if x.Unit != samp[0].Unit {
			t.Errorf("got: %s wanted: %s", samp[0].Unit, x.Unit)
		}
		if e := decimal.NewFromFloat(1.0); e.Cmp(x.dec) != 0 {
			t.Errorf("got: %f wanted: %f", x.dec, e)
		}
	}
}