session_sum_test.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. // Copyright 2017 The Xorm Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package xorm
  5. import (
  6. "fmt"
  7. "strconv"
  8. "testing"
  9. "github.com/stretchr/testify/assert"
  10. )
  11. func isFloatEq(i, j float64, precision int) bool {
  12. return fmt.Sprintf("%."+strconv.Itoa(precision)+"f", i) == fmt.Sprintf("%."+strconv.Itoa(precision)+"f", j)
  13. }
  14. func TestSum(t *testing.T) {
  15. assert.NoError(t, prepareEngine())
  16. type SumStruct struct {
  17. Int int
  18. Float float32
  19. }
  20. var (
  21. cases = []SumStruct{
  22. {1, 6.2},
  23. {2, 5.3},
  24. {92, -0.2},
  25. }
  26. )
  27. var i int
  28. var f float32
  29. for _, v := range cases {
  30. i += v.Int
  31. f += v.Float
  32. }
  33. assert.NoError(t, testEngine.Sync2(new(SumStruct)))
  34. cnt, err := testEngine.Insert(cases)
  35. assert.NoError(t, err)
  36. assert.EqualValues(t, 3, cnt)
  37. colInt := testEngine.ColumnMapper.Obj2Table("Int")
  38. colFloat := testEngine.ColumnMapper.Obj2Table("Float")
  39. sumInt, err := testEngine.Sum(new(SumStruct), colInt)
  40. assert.NoError(t, err)
  41. assert.EqualValues(t, int(sumInt), i)
  42. sumFloat, err := testEngine.Sum(new(SumStruct), colFloat)
  43. assert.NoError(t, err)
  44. assert.Condition(t, func() bool {
  45. return isFloatEq(sumFloat, float64(f), 2)
  46. })
  47. sums, err := testEngine.Sums(new(SumStruct), colInt, colFloat)
  48. assert.NoError(t, err)
  49. assert.EqualValues(t, 2, len(sums))
  50. assert.EqualValues(t, i, int(sums[0]))
  51. assert.Condition(t, func() bool {
  52. return isFloatEq(sums[1], float64(f), 2)
  53. })
  54. sumsInt, err := testEngine.SumsInt(new(SumStruct), colInt)
  55. assert.NoError(t, err)
  56. assert.EqualValues(t, 1, len(sumsInt))
  57. assert.EqualValues(t, i, int(sumsInt[0]))
  58. }