Browse Source

Improve tests (#1572)

fix test

Improve tests

Reviewed-on: #1572
pull/1574/head
Lunny Xiao 4 months ago
parent
commit
7278e2ab71
28 changed files with 738 additions and 2095 deletions
  1. +6
    -6
      caches/leveldb.go
  2. +3
    -1
      caches/leveldb_test.go
  3. +125
    -0
      convert.go
  4. +40
    -0
      engine.go
  5. +0
    -28
      engine_context.go
  6. +0
    -28
      engine_context_test.go
  7. +14
    -0
      engine_test.go
  8. +0
    -10
      error.go
  9. +0
    -163
      helpers.go
  10. +3
    -3
      internal/statements/update.go
  11. +13
    -45
      processors_test.go
  12. +26
    -0
      session.go
  13. +0
    -4
      session_cond_test.go
  14. +0
    -23
      session_context.go
  15. +0
    -36
      session_context_test.go
  16. +2
    -1
      session_delete_test.go
  17. +25
    -0
      session_exist_test.go
  18. +39
    -101
      session_find_test.go
  19. +66
    -215
      session_insert_test.go
  20. +179
    -706
      session_pk_test.go
  21. +2
    -8
      session_schema_test.go
  22. +2
    -6
      session_tx_test.go
  23. +103
    -252
      session_update_test.go
  24. +0
    -71
      statement_test.go
  25. +54
    -237
      tags_test.go
  26. +6
    -1
      time_test.go
  27. +0
    -26
      transaction.go
  28. +30
    -124
      types_null_test.go

+ 6
- 6
caches/leveldb.go View File

@ -19,14 +19,14 @@ type LevelDBStore struct {
var _ CacheStore = &LevelDBStore{}
func NewLevelDBStore(dbfile string) *LevelDBStore {
func NewLevelDBStore(dbfile string) (*LevelDBStore, error) {
db := &LevelDBStore{}
if h, err := leveldb.OpenFile(dbfile, nil); err != nil {
panic(err)
} else {
db.store = h
h, err := leveldb.OpenFile(dbfile, nil)
if err != nil {
return nil, err
}
return db
db.store = h
return db, nil
}
func (s *LevelDBStore) Put(key string, value interface{}) error {

+ 3
- 1
caches/leveldb_test.go View File

@ -11,7 +11,9 @@ import (
)
func TestLevelDBStore(t *testing.T) {
store := NewLevelDBStore("./level.db")
store, err := NewLevelDBStore("./level.db")
assert.NoError(t, err)
var kvs = map[string]interface{}{
"a": "b",
}

+ 125
- 0
convert.go View File

@ -346,3 +346,128 @@ func asBool(bs []byte) (bool, error) {
}
return strconv.ParseBool(string(bs))
}
// str2PK convert string value to primary key value according to tp
func str2PKValue(s string, tp reflect.Type) (reflect.Value, error) {
var err error
var result interface{}
var defReturn = reflect.Zero(tp)
switch tp.Kind() {
case reflect.Int:
result, err = strconv.Atoi(s)
if err != nil {
return defReturn, fmt.Errorf("convert %s as int: %s", s, err.Error())
}
case reflect.Int8:
x, err := strconv.Atoi(s)
if err != nil {
return defReturn, fmt.Errorf("convert %s as int8: %s", s, err.Error())
}
result = int8(x)
case reflect.Int16:
x, err := strconv.Atoi(s)
if err != nil {
return defReturn, fmt.Errorf("convert %s as int16: %s", s, err.Error())
}
result = int16(x)
case reflect.Int32:
x, err := strconv.Atoi(s)
if err != nil {
return defReturn, fmt.Errorf("convert %s as int32: %s", s, err.Error())
}
result = int32(x)
case reflect.Int64:
result, err = strconv.ParseInt(s, 10, 64)
if err != nil {
return defReturn, fmt.Errorf("convert %s as int64: %s", s, err.Error())
}
case reflect.Uint:
x, err := strconv.ParseUint(s, 10, 64)
if err != nil {
return defReturn, fmt.Errorf("convert %s as uint: %s", s, err.Error())
}
result = uint(x)
case reflect.Uint8:
x, err := strconv.ParseUint(s, 10, 64)
if err != nil {
return defReturn, fmt.Errorf("convert %s as uint8: %s", s, err.Error())
}
result = uint8(x)
case reflect.Uint16:
x, err := strconv.ParseUint(s, 10, 64)
if err != nil {
return defReturn, fmt.Errorf("convert %s as uint16: %s", s, err.Error())
}
result = uint16(x)
case reflect.Uint32:
x, err := strconv.ParseUint(s, 10, 64)
if err != nil {
return defReturn, fmt.Errorf("convert %s as uint32: %s", s, err.Error())
}
result = uint32(x)
case reflect.Uint64:
result, err = strconv.ParseUint(s, 10, 64)
if err != nil {
return defReturn, fmt.Errorf("convert %s as uint64: %s", s, err.Error())
}
case reflect.String:
result = s
default:
return defReturn, errors.New("unsupported convert type")
}
return reflect.ValueOf(result).Convert(tp), nil
}
func str2PK(s string, tp reflect.Type) (interface{}, error) {
v, err := str2PKValue(s, tp)
if err != nil {
return nil, err
}
return v.Interface(), nil
}
func int64ToIntValue(id int64, tp reflect.Type) reflect.Value {
var v interface{}
kind := tp.Kind()
if kind == reflect.Ptr {
kind = tp.Elem().Kind()
}
switch kind {
case reflect.Int16:
temp := int16(id)
v = &temp
case reflect.Int32:
temp := int32(id)
v = &temp
case reflect.Int:
temp := int(id)
v = &temp
case reflect.Int64:
temp := id
v = &temp
case reflect.Uint16:
temp := uint16(id)
v = &temp
case reflect.Uint32:
temp := uint32(id)
v = &temp
case reflect.Uint64:
temp := uint64(id)
v = &temp
case reflect.Uint:
temp := uint(id)
v = &temp
}
if tp.Kind() == reflect.Ptr {
return reflect.ValueOf(v).Convert(tp)
}
return reflect.ValueOf(v).Elem().Convert(tp)
}
func int64ToInt(id int64, tp reflect.Type) interface{} {
return int64ToIntValue(id, tp).Interface()
}

+ 40
- 0
engine.go View File

@ -1260,3 +1260,43 @@ func (engine *Engine) Unscoped() *Session {
func (engine *Engine) tbNameWithSchema(v string) string {
return dialects.TableNameWithSchema(engine.dialect, v)
}
// Context creates a session with the context
func (engine *Engine) Context(ctx context.Context) *Session {
session := engine.NewSession()
session.isAutoClose = true
return session.Context(ctx)
}
// SetDefaultContext set the default context
func (engine *Engine) SetDefaultContext(ctx context.Context) {
engine.defaultContext = ctx
}
// PingContext tests if database is alive
func (engine *Engine) PingContext(ctx context.Context) error {
session := engine.NewSession()
defer session.Close()
return session.PingContext(ctx)
}
// Transaction Execute sql wrapped in a transaction(abbr as tx), tx will automatic commit if no errors occurred
func (engine *Engine) Transaction(f func(*Session) (interface{}, error)) (interface{}, error) {
session := engine.NewSession()
defer session.Close()
if err := session.Begin(); err != nil {
return nil, err
}
result, err := f(session)
if err != nil {
return nil, err
}
if err := session.Commit(); err != nil {
return nil, err
}
return result, nil
}

+ 0
- 28
engine_context.go View File

@ -1,28 +0,0 @@
// Copyright 2019 The Xorm Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build go1.8
package xorm
import "context"
// Context creates a session with the context
func (engine *Engine) Context(ctx context.Context) *Session {
session := engine.NewSession()
session.isAutoClose = true
return session.Context(ctx)
}
// SetDefaultContext set the default context
func (engine *Engine) SetDefaultContext(ctx context.Context) {
engine.defaultContext = ctx
}
// PingContext tests if database is alive
func (engine *Engine) PingContext(ctx context.Context) error {
session := engine.NewSession()
defer session.Close()
return session.PingContext(ctx)
}

+ 0
- 28
engine_context_test.go View File

@ -1,28 +0,0 @@
// Copyright 2017 The Xorm Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build go1.8
package xorm
import (
"context"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
func TestPingContext(t *testing.T) {
assert.NoError(t, prepareEngine())
ctx, canceled := context.WithTimeout(context.Background(), time.Nanosecond)
defer canceled()
time.Sleep(time.Nanosecond)
err := testEngine.(*Engine).PingContext(ctx)
assert.Error(t, err)
assert.Contains(t, err.Error(), "context deadline exceeded")
}

transancation_test.go → engine_test.go View File

@ -5,6 +5,7 @@
package xorm
import (
"context"
"fmt"
"testing"
"time"
@ -12,6 +13,19 @@ import (
"github.com/stretchr/testify/assert"
)
func TestPingContext(t *testing.T) {
assert.NoError(t, prepareEngine())
ctx, canceled := context.WithTimeout(context.Background(), time.Nanosecond)
defer canceled()
time.Sleep(time.Nanosecond)
err := testEngine.(*Engine).PingContext(ctx)
assert.Error(t, err)
assert.Contains(t, err.Error(), "context deadline exceeded")
}
func TestAutoTransaction(t *testing.T) {
assert.NoError(t, prepareEngine())

+ 0
- 10
error.go View File

@ -37,13 +37,3 @@ type ErrFieldIsNotExist struct {
func (e ErrFieldIsNotExist) Error() string {
return fmt.Sprintf("field %s is not valid on table %s", e.FieldName, e.TableName)
}
// ErrFieldIsNotValid is not valid
type ErrFieldIsNotValid struct {
FieldName string
TableName string
}
func (e ErrFieldIsNotValid) Error() string {
return fmt.Sprintf("field %s is not valid on table %s", e.FieldName, e.TableName)
}

+ 0
- 163
helpers.go View File

@ -1,163 +0,0 @@
// Copyright 2015 The Xorm Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package xorm
import (
"errors"
"fmt"
"reflect"
"strconv"
"time"
)
// str2PK convert string value to primary key value according to tp
func str2PKValue(s string, tp reflect.Type) (reflect.Value, error) {
var err error
var result interface{}
var defReturn = reflect.Zero(tp)
switch tp.Kind() {
case reflect.Int:
result, err = strconv.Atoi(s)
if err != nil {
return defReturn, fmt.Errorf("convert %s as int: %s", s, err.Error())
}
case reflect.Int8:
x, err := strconv.Atoi(s)
if err != nil {
return defReturn, fmt.Errorf("convert %s as int8: %s", s, err.Error())
}
result = int8(x)
case reflect.Int16:
x, err := strconv.Atoi(s)
if err != nil {
return defReturn, fmt.Errorf("convert %s as int16: %s", s, err.Error())
}
result = int16(x)
case reflect.Int32:
x, err := strconv.Atoi(s)
if err != nil {
return defReturn, fmt.Errorf("convert %s as int32: %s", s, err.Error())
}
result = int32(x)
case reflect.Int64:
result, err = strconv.ParseInt(s, 10, 64)
if err != nil {
return defReturn, fmt.Errorf("convert %s as int64: %s", s, err.Error())
}
case reflect.Uint:
x, err := strconv.ParseUint(s, 10, 64)
if err != nil {
return defReturn, fmt.Errorf("convert %s as uint: %s", s, err.Error())
}
result = uint(x)
case reflect.Uint8:
x, err := strconv.ParseUint(s, 10, 64)
if err != nil {
return defReturn, fmt.Errorf("convert %s as uint8: %s", s, err.Error())
}
result = uint8(x)
case reflect.Uint16:
x, err := strconv.ParseUint(s, 10, 64)
if err != nil {
return defReturn, fmt.Errorf("convert %s as uint16: %s", s, err.Error())
}
result = uint16(x)
case reflect.Uint32:
x, err := strconv.ParseUint(s, 10, 64)
if err != nil {
return defReturn, fmt.Errorf("convert %s as uint32: %s", s, err.Error())
}
result = uint32(x)
case reflect.Uint64:
result, err = strconv.ParseUint(s, 10, 64)
if err != nil {
return defReturn, fmt.Errorf("convert %s as uint64: %s", s, err.Error())
}
case reflect.String:
result = s
default:
return defReturn, errors.New("unsupported convert type")
}
return reflect.ValueOf(result).Convert(tp), nil
}
func str2PK(s string, tp reflect.Type) (interface{}, error) {
v, err := str2PKValue(s, tp)
if err != nil {
return nil, err
}
return v.Interface(), nil
}
func int64ToIntValue(id int64, tp reflect.Type) reflect.Value {
var v interface{}
kind := tp.Kind()
if kind == reflect.Ptr {
kind = tp.Elem().Kind()
}
switch kind {
case reflect.Int16:
temp := int16(id)
v = &temp
case reflect.Int32:
temp := int32(id)
v = &temp
case reflect.Int:
temp := int(id)
v = &temp
case reflect.Int64:
temp := id
v = &temp
case reflect.Uint16:
temp := uint16(id)
v = &temp
case reflect.Uint32:
temp := uint32(id)
v = &temp
case reflect.Uint64:
temp := uint64(id)
v = &temp
case reflect.Uint:
temp := uint(id)
v = &temp
}
if tp.Kind() == reflect.Ptr {
return reflect.ValueOf(v).Convert(tp)
}
return reflect.ValueOf(v).Elem().Convert(tp)
}
func int64ToInt(id int64, tp reflect.Type) interface{} {
return int64ToIntValue(id, tp).Interface()
}
func makeArray(elem string, count int) []string {
res := make([]string, count)
for i := 0; i < count; i++ {
res[i] = elem
}
return res
}
func rType(bean interface{}) reflect.Type {
sliceValue := reflect.Indirect(reflect.ValueOf(bean))
// return reflect.TypeOf(sliceValue.Interface())
return sliceValue.Type()
}
func structName(v reflect.Type) string {
for v.Kind() == reflect.Ptr {
v = v.Elem()
}
return v.Name()
}
func formatTime(t time.Time) string {
return t.Format("2006-01-02 15:04:05")
}

+ 3
- 3
internal/statements/update.go View File

@ -6,6 +6,7 @@ package statements
import (
"database/sql/driver"
"errors"
"fmt"
"reflect"
"time"
@ -200,8 +201,7 @@ func (statement *Statement) BuildUpdates(bean interface{},
continue
}
} else {
// TODO: how to handler?
panic("not supported")
return nil, nil, errors.New("Not supported multiple primary keys")
}
}
} else {
@ -209,7 +209,7 @@ func (statement *Statement) BuildUpdates(bean interface{},
if requiredField || !utils.IsStructZero(fieldValue) {
bytes, err := json.DefaultJSONHandler.Marshal(fieldValue.Interface())
if err != nil {
panic(fmt.Sprintf("mashal %v failed", fieldValue.Interface()))
return nil, nil, fmt.Errorf("mashal %v failed", fieldValue.Interface())
}
if col.SQLType.IsText() {
val = string(bytes)

+ 13
- 45
processors_test.go View File

@ -125,17 +125,11 @@ func TestProcessors(t *testing.T) {
assert.NoError(t, prepareEngine())
err := testEngine.DropTables(&ProcessorsStruct{})
if err != nil {
t.Error(err)
panic(err)
}
assert.NoError(t, err)
p := &ProcessorsStruct{}
err = testEngine.CreateTables(&ProcessorsStruct{})
if err != nil {
t.Error(err)
panic(err)
}
assert.NoError(t, err)
b4InsertFunc := func(bean interface{}) {
if v, ok := (bean).(*ProcessorsStruct); ok {
@ -259,42 +253,22 @@ func TestProcessors(t *testing.T) {
_, err = testEngine.Before(b4UpdateFunc).After(afterUpdateFunc).Update(p)
assert.NoError(t, err)
if p.B4UpdateFlag == 0 {
t.Error(errors.New("B4UpdateFlag not set"))
}
if p.AfterUpdatedFlag == 0 {
t.Error(errors.New("AfterUpdatedFlag not set"))
}
if p.B4UpdateViaExt == 0 {
t.Error(errors.New("B4UpdateViaExt not set"))
}
if p.AfterUpdatedViaExt == 0 {
t.Error(errors.New("AfterUpdatedViaExt not set"))
}
assert.False(t, p.B4UpdateFlag == 0, "B4UpdateFlag not set")
assert.False(t, p.AfterUpdatedFlag == 0, "AfterUpdatedFlag not set")
assert.False(t, p.B4UpdateViaExt == 0, "B4UpdateViaExt not set")
assert.False(t, p.AfterUpdatedViaExt == 0, "AfterUpdatedViaExt not set")
p2 = &ProcessorsStruct{}
has, err = testEngine.ID(p.Id).Get(p2)
assert.NoError(t, err)
assert.True(t, has)
if p2.B4UpdateFlag == 0 {
t.Error(errors.New("B4UpdateFlag not set"))
}
if p2.AfterUpdatedFlag != 0 {
t.Error(errors.New("AfterUpdatedFlag is set: " + string(p.AfterUpdatedFlag)))
}
if p2.B4UpdateViaExt == 0 {
t.Error(errors.New("B4UpdateViaExt not set"))
}
if p2.AfterUpdatedViaExt != 0 {
t.Error(errors.New("AfterUpdatedViaExt is set: " + string(p.AfterUpdatedViaExt)))
}
if p2.BeforeSetFlag != 9 {
t.Error(fmt.Errorf("BeforeSetFlag is %d not 9", p2.BeforeSetFlag))
}
if p2.AfterSetFlag != 9 {
t.Error(fmt.Errorf("AfterSetFlag is %d not 9", p2.BeforeSetFlag))
}
assert.False(t, p2.B4UpdateFlag == 0, "B4UpdateFlag not set")
assert.False(t, p2.AfterUpdatedFlag != 0, fmt.Sprintf("AfterUpdatedFlag is set: %d", p.AfterUpdatedFlag))
assert.False(t, p2.B4UpdateViaExt == 0, "B4UpdateViaExt not set")
assert.False(t, p2.AfterUpdatedViaExt != 0, fmt.Sprintf("AfterUpdatedViaExt is set: %d", p.AfterUpdatedViaExt))
assert.False(t, p2.BeforeSetFlag != 9, fmt.Sprintf("BeforeSetFlag is %d not 9", p2.BeforeSetFlag))
assert.False(t, p2.AfterSetFlag != 9, fmt.Sprintf("AfterSetFlag is %d not 9", p2.BeforeSetFlag))
// --
// test delete processors
@ -450,12 +424,7 @@ func TestProcessorsTx(t *testing.T) {
p2 := &ProcessorsStruct{}
_, err = testEngine.ID(p.Id).Get(p2)
assert.NoError(t, err)
if p2.Id > 0 {
err = errors.New("tx got committed upon insert!?")
t.Error(err)
panic(err)
}
assert.False(t, p2.Id > 0, "tx got committed upon insert!?")
// --
// test insert processors with tx commit
@ -846,7 +815,6 @@ func TestProcessorsTx(t *testing.T) {
t.Error(errors.New("AfterUpdatedFlag set"))
}
session.Close()
// --
}
type AfterLoadStructA struct {

+ 26
- 0
session.go View File

@ -22,6 +22,16 @@ import (
"xorm.io/xorm/schemas"
)
// ErrFieldIsNotValid is not valid
type ErrFieldIsNotValid struct {
FieldName string
TableName string
}
func (e ErrFieldIsNotValid) Error() string {
return fmt.Sprintf("field %s is not valid on table %s", e.FieldName, e.TableName)
}
type sessionType int
const (
@ -883,3 +893,19 @@ func (session *Session) incrVersionFieldValue(fieldValue *reflect.Value) {
fieldValue.SetUint(fieldValue.Uint() + 1)
}
}
// Context sets the context on this session
func (session *Session) Context(ctx context.Context) *Session {
session.ctx = ctx
return session
}
// PingContext test if database is ok
func (session *Session) PingContext(ctx context.Context) error {
if session.isAutoClose {
defer session.Close()
}
session.engine.logger.Infof("PING DATABASE %v", session.engine.DriverName())
return session.DB().PingContext(ctx)
}

+ 0
- 4
session_cond_test.go View File

@ -139,13 +139,11 @@ func TestIn(t *testing.T) {
users := make([]Userinfo, 0)
err = testEngine.In("id", ids[0], ids[1], ids[2]).Find(&users)
assert.NoError(t, err)
fmt.Println(users)
assert.EqualValues(t, 3, len(users))
users = make([]Userinfo, 0)
err = testEngine.In("id", ids).Find(&users)
assert.NoError(t, err)
fmt.Println(users)
assert.EqualValues(t, 3, len(users))
for _, user := range users {
@ -163,7 +161,6 @@ func TestIn(t *testing.T) {
err = testEngine.Where(department+" = ?", "dev").In("id", idsInterface...).Find(&users)
assert.NoError(t, err)
fmt.Println(users)
assert.EqualValues(t, 3, len(users))
for _, user := range users {
@ -177,7 +174,6 @@ func TestIn(t *testing.T) {
err = testEngine.In("id", 1).In("id", 2).In(department, dev).Find(&users)
assert.NoError(t, err)
fmt.Println(users)
cnt, err = testEngine.In("id", ids[0]).Update(&Userinfo{Departname: "dev-"})
assert.NoError(t, err)

+ 0
- 23
session_context.go View File

@ -1,23 +0,0 @@
// Copyright 2019 The Xorm Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package xorm
import "context"
// Context sets the context on this session
func (session *Session) Context(ctx context.Context) *Session {
session.ctx = ctx
return session
}
// PingContext test if database is ok
func (session *Session) PingContext(ctx context.Context) error {
if session.isAutoClose {
defer session.Close()
}
session.engine.logger.Infof("PING DATABASE %v", session.engine.DriverName())
return session.DB().PingContext(ctx)
}

+ 0
- 36
session_context_test.go View File

@ -1,36 +0,0 @@
// Copyright 2019 The Xorm Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package xorm
import (
"context"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
func TestQueryContext(t *testing.T) {
type ContextQueryStruct struct {
Id int64
Name string
}
assert.NoError(t, prepareEngine())
assertSync(t, new(ContextQueryStruct))
_, err := testEngine.Insert(&ContextQueryStruct{Name: "1"})
assert.NoError(t, err)
ctx, cancel := context.WithTimeout(context.Background(), time.Nanosecond)
defer cancel()
time.Sleep(time.Nanosecond)
has, err := testEngine.Context(ctx).Exist(&ContextQueryStruct{Name: "1"})
assert.Error(t, err)
assert.Contains(t, err.Error(), "context deadline exceeded")
assert.False(t, has)
}

+ 2
- 1
session_delete_test.go View File

@ -8,9 +8,10 @@ import (
"testing"
"time"
"github.com/stretchr/testify/assert"
"xorm.io/xorm/caches"
"xorm.io/xorm/schemas"
"github.com/stretchr/testify/assert"
)
func TestDelete(t *testing.T) {

+ 25
- 0
session_exist_test.go View File

@ -5,7 +5,9 @@
package xorm
import (
"context"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
@ -181,3 +183,26 @@ func TestExistStructForJoin(t *testing.T) {
assert.NoError(t, err)
assert.True(t, has)
}
func TestExistContext(t *testing.T) {
type ContextQueryStruct struct {
Id int64
Name string
}
assert.NoError(t, prepareEngine())
assertSync(t, new(ContextQueryStruct))
_, err := testEngine.Insert(&ContextQueryStruct{Name: "1"})
assert.NoError(t, err)
ctx, cancel := context.WithTimeout(context.Background(), time.Nanosecond)
defer cancel()
time.Sleep(time.Nanosecond)
has, err := testEngine.Context(ctx).Exist(&ContextQueryStruct{Name: "1"})
assert.Error(t, err)
assert.Contains(t, err.Error(), "context deadline exceeded")
assert.False(t, has)
}

+ 39
- 101
session_find_test.go View File

@ -5,7 +5,6 @@
package xorm
import (
"errors"
"fmt"
"testing"
"time"
@ -79,17 +78,11 @@ func TestWhere(t *testing.T) {
users := make([]Userinfo, 0)
err := testEngine.Where("id > ?", 2).Find(&users)
if err != nil {
t.Error(err)
panic(err)
}
assert.NoError(t, err)
fmt.Println(users)
err = testEngine.Where("id > ?", 2).And("id < ?", 10).Find(&users)
if err != nil {
t.Error(err)
panic(err)
}
assert.NoError(t, err)
fmt.Println(users)
}
@ -200,13 +193,7 @@ func TestFindMap(t *testing.T) {
users := make(map[int64]Userinfo)
err := testEngine.Find(&users)
if err != nil {
t.Error(err)
panic(err)
}
for _, user := range users {
fmt.Println(user)
}
assert.NoError(t, err)
}
func TestFindMap2(t *testing.T) {
@ -215,13 +202,7 @@ func TestFindMap2(t *testing.T) {
users := make(map[int64]*Userinfo)
err := testEngine.Find(&users)
if err != nil {
t.Error(err)
panic(err)
}
for id, user := range users {
fmt.Println(id, user)
}
assert.NoError(t, err)
}
func TestDistinct(t *testing.T) {
@ -239,8 +220,6 @@ func TestDistinct(t *testing.T) {
assert.NoError(t, err)
assert.EqualValues(t, 1, len(users))
fmt.Println(users)
type Depart struct {
Departname string
}
@ -248,12 +227,7 @@ func TestDistinct(t *testing.T) {
users2 := make([]Depart, 0)
err = testEngine.Distinct(departname).Table(new(Userinfo)).Find(&users2)
assert.NoError(t, err)
if len(users2) != 1 {
fmt.Println(len(users2))
t.Error(err)
panic(errors.New("should be one record"))
}
fmt.Println(users2)
assert.EqualValues(t, 1, len(users2))
}
func TestOrder(t *testing.T) {
@ -263,12 +237,10 @@ func TestOrder(t *testing.T) {
users := make([]Userinfo, 0)
err := testEngine.OrderBy("id desc").Find(&users)
assert.NoError(t, err)
fmt.Println(users)
users2 := make([]Userinfo, 0)
err = testEngine.Asc("id", "username").Desc("height").Find(&users2)
assert.NoError(t, err)
fmt.Println(users2)
}
func TestGroupBy(t *testing.T) {
@ -287,15 +259,6 @@ func TestHaving(t *testing.T) {
users := make([]Userinfo, 0)
err := testEngine.GroupBy("username").Having("username='xlw'").Find(&users)
assert.NoError(t, err)
fmt.Println(users)
/*users = make([]Userinfo, 0)
err = testEngine.Cols("id, username").GroupBy("username").Having("username='xlw'").Find(&users)
if err != nil {
t.Error(err)
panic(err)
}
fmt.Println(users)*/
}
func TestOrderSameMapper(t *testing.T) {
@ -315,12 +278,10 @@ func TestOrderSameMapper(t *testing.T) {
users := make([]Userinfo, 0)
err := testEngine.OrderBy("id desc").Find(&users)
assert.NoError(t, err)
fmt.Println(users)
users2 := make([]Userinfo, 0)
err = testEngine.Asc("id", "Username").Desc("Height").Find(&users2)
assert.NoError(t, err)
fmt.Println(users2)
}
func TestHavingSameMapper(t *testing.T) {
@ -337,10 +298,7 @@ func TestHavingSameMapper(t *testing.T) {
users := make([]Userinfo, 0)
err := testEngine.GroupBy("`Username`").Having("`Username`='xlw'").Find(&users)
if err != nil {
t.Fatal(err)
}
fmt.Println(users)
assert.NoError(t, err)
}
func TestFindInts(t *testing.T) {
@ -350,39 +308,24 @@ func TestFindInts(t *testing.T) {
userinfo := testEngine.GetTableMapper().Obj2Table("Userinfo")
var idsInt64 []int64
err := testEngine.Table(userinfo).Cols("id").Desc("id").Find(&idsInt64)
if err != nil {
t.Fatal(err)
}
fmt.Println(idsInt64)
assert.NoError(t, err)
var idsInt32 []int32
err = testEngine.Table(userinfo).Cols("id").Desc("id").Find(&idsInt32)
if err != nil {
t.Fatal(err)
}
fmt.Println(idsInt32)
assert.NoError(t, err)
var idsInt []int
err = testEngine.Table(userinfo).Cols("id").Desc("id").Find(&idsInt)
if err != nil {
t.Fatal(err)
}
fmt.Println(idsInt)
assert.NoError(t, err)
var idsUint []uint
err = testEngine.Table(userinfo).Cols("id").Desc("id").Find(&idsUint)
if err != nil {
t.Fatal(err)
}
fmt.Println(idsUint)
assert.NoError(t, err)
type MyInt int
var idsMyInt []MyInt
err = testEngine.Table(userinfo).Cols("id").Desc("id").Find(&idsMyInt)
if err != nil {
t.Fatal(err)
}
fmt.Println(idsMyInt)
assert.NoError(t, err)
}
func TestFindStrings(t *testing.T) {
@ -392,10 +335,7 @@ func TestFindStrings(t *testing.T) {
username := testEngine.GetColumnMapper().Obj2Table("Username")
var idsString []string
err := testEngine.Table(userinfo).Cols(username).Desc("id").Find(&idsString)
if err != nil {
t.Fatal(err)
}
fmt.Println(idsString)
assert.NoError(t, err)
}
func TestFindMyString(t *testing.T) {
@ -406,10 +346,7 @@ func TestFindMyString(t *testing.T) {
var idsMyString []MyString
err := testEngine.Table(userinfo).Cols(username).Desc("id").Find(&idsMyString)
if err != nil {
t.Fatal(err)
}
fmt.Println(idsMyString)
assert.NoError(t, err)
}
func TestFindInterface(t *testing.T) {
@ -420,10 +357,7 @@ func TestFindInterface(t *testing.T) {
username := testEngine.GetColumnMapper().Obj2Table("Username")
var idsInterface []interface{}
err := testEngine.Table(userinfo).Cols(username).Desc("id").Find(&idsInterface)
if err != nil {
t.Fatal(err)
}
fmt.Println(idsInterface)
assert.NoError(t, err)
}
func TestFindSliceBytes(t *testing.T) {
@ -433,12 +367,7 @@ func TestFindSliceBytes(t *testing.T) {
userinfo := testEngine.GetTableMapper().Obj2Table("Userinfo")
var ids [][][]byte
err := testEngine.Table(userinfo).Desc("id").Find(&ids)
if err != nil {
t.Fatal(err)
}
for _, record := range ids {
fmt.Println(record)
}
assert.NoError(t, err)
}
func TestFindSlicePtrString(t *testing.T) {
@ -448,12 +377,7 @@ func TestFindSlicePtrString(t *testing.T) {
userinfo := testEngine.GetTableMapper().Obj2Table("Userinfo")
var ids [][]*string
err := testEngine.Table(userinfo).Desc("id").Find(&ids)
if err != nil {
t.Fatal(err)
}
for _, record := range ids {
fmt.Println(record)
}
assert.NoError(t, err)
}
func TestFindMapBytes(t *testing.T) {
@ -463,12 +387,7 @@ func TestFindMapBytes(t *testing.T) {
userinfo := testEngine.GetTableMapper().Obj2Table("Userinfo")
var ids []map[string][]byte
err := testEngine.Table(userinfo).Desc("id").Find(&ids)
if err != nil {
t.Fatal(err)
}
for _, record := range ids {
fmt.Println(record)
}
assert.NoError(t, err)
}
func TestFindMapPtrString(t *testing.T) {
@ -479,9 +398,6 @@ func TestFindMapPtrString(t *testing.T) {
var ids []map[string]*string
err := testEngine.Table(userinfo).Desc("id").Find(&ids)
assert.NoError(t, err)
for _, record := range ids {
fmt.Println(record)
}
}
func TestFindBit(t *testing.T) {
@ -868,3 +784,25 @@ func TestMoreExtends(t *testing.T) {
Find(&books)
assert.NoError(t, err)
}
func TestDistinctAndCols(t *testing.T) {
type DistinctAndCols struct {
Id int64
Name string
}
assert.NoError(t, prepareEngine())
assertSync(t, new(DistinctAndCols))
cnt, err := testEngine.Insert(&DistinctAndCols{
Name: "test",
})
assert.NoError(t, err)
assert.EqualValues(t, 1, cnt)
var names []string
err = testEngine.Table("distinct_and_cols").Cols("name").Distinct("name").Find(&names)
assert.NoError(t, err)
assert.EqualValues(t, 1, len(names))
assert.EqualValues(t, "test", names[0])
}

+ 66
- 215
session_insert_test.go View File

@ -5,7 +5,6 @@
package xorm
import (
"errors"
"fmt"
"reflect"
"testing"
@ -154,9 +153,6 @@ func TestInsert(t *testing.T) {
// Username is unique, so this should return error
assert.Error(t, err, "insert should fail but no error returned")
assert.EqualValues(t, 0, cnt, "insert not returned 1")
if err == nil {
panic("should return err")
}
}
func TestInsertAutoIncr(t *testing.T) {
@ -167,19 +163,9 @@ func TestInsertAutoIncr(t *testing.T) {
user := Userinfo{Username: "xiaolunwen2", Departname: "dev", Alias: "lunny", Created: time.Now(),
Detail: Userdetail{Id: 1}, Height: 1.78, Avatar: []byte{1, 2, 3}, IsMan: true}
cnt, err := testEngine.Insert(&user)
fmt.Println(user.Uid)
if err != nil {
t.Error(err)
panic(err)
}
if cnt != 1 {
err = errors.New("insert not returned 1")
t.Error(err)
panic(err)
}
if user.Uid <= 0 {
t.Error(errors.New("not return id error"))
}
assert.NoError(t, err)
assert.EqualValues(t, 1, cnt)
assert.Greater(t, user.Uid, int64(0))
}
type DefaultInsert struct {
@ -203,26 +189,10 @@ func TestInsertDefault(t *testing.T) {
has, err := testEngine.Desc("id").Get(di)
assert.NoError(t, err)
if !has {
err = errors.New("error with no data")
t.Error(err)
panic(err)
}
if di.Status != -1 {
err = errors.New("inserted error data")
t.Error(err)
panic(err)
}
if di2.Updated.Unix() != di.Updated.Unix() {
err = errors.New("updated should equal")
t.Error(err, di.Updated, di2.Updated)
panic(err)
}
if di2.Created.Unix() != di.Created.Unix() {
err = errors.New("created should equal")
t.Error(err, di.Created, di2.Created)
panic(err)
}
assert.True(t, has)
assert.EqualValues(t, -1, di.Status)
assert.EqualValues(t, di2.Updated.Unix(), di.Updated.Unix())
assert.EqualValues(t, di2.Created.Unix(), di.Created.Unix())
}
type DefaultInsert2 struct {
@ -237,53 +207,20 @@ func TestInsertDefault2(t *testing.T) {
di := new(DefaultInsert2)
err := testEngine.Sync2(di)
if err != nil {
t.Error(err)
}
assert.NoError(t, err)
var di2 = DefaultInsert2{Name: "test"}
_, err = testEngine.Omit(testEngine.GetColumnMapper().Obj2Table("CheckTime")).Insert(&di2)
if err != nil {
t.Error(err)
}
assert.NoError(t, err)
has, err := testEngine.Desc("id").Get(di)
if err != nil {
t.Error(err)
}
if !has {
err = errors.New("error with no data")
t.Error(err)
panic(err)
}
assert.NoError(t, err)
assert.True(t, has)
has, err = testEngine.NoAutoCondition().Desc("id").Get(&di2)
if err != nil {
t.Error(err)
}
if !has {
err = errors.New("error with no data")
t.Error(err)
panic(err)
}
if *di != di2 {
err = fmt.Errorf("%v is not equal to %v", di, di2)
t.Error(err)
panic(err)
}
/*if di2.Updated.Unix() != di.Updated.Unix() {
err = errors.New("updated should equal")
t.Error(err, di.Updated, di2.Updated)
panic(err)
}
if di2.Created.Unix() != di.Created.Unix() {
err = errors.New("created should equal")
t.Error(err, di.Created, di2.Created)
panic(err)
}*/
assert.NoError(t, err)
assert.True(t, has)
assert.EqualValues(t, *di, di2)
}
type CreatedInsert struct {
@ -321,138 +258,82 @@ func TestInsertCreated(t *testing.T) {
di := new(CreatedInsert)
err := testEngine.Sync2(di)
if err != nil {
t.Fatal(err)
}
assert.NoError(t, err)
ci := &CreatedInsert{}
_, err = testEngine.Insert(ci)
if err != nil {
t.Fatal(err)
}
assert.NoError(t, err)
has, err := testEngine.Desc("id").Get(di)
if err != nil {
t.Fatal(err)
}
if !has {
t.Fatal(ErrNotExist)
}
if ci.Created.Unix() != di.Created.Unix() {
t.Fatal("should equal:", ci, di)
}
fmt.Println("ci:", ci, "di:", di)
assert.NoError(t, err)
assert.True(t, has)
assert.EqualValues(t, ci.Created.Unix(), di.Created.Unix())
di2 := new(CreatedInsert2)
err = testEngine.Sync2(di2)
if err != nil {
t.Fatal(err)
}
assert.NoError(t, err)
ci2 := &CreatedInsert2{}
_, err = testEngine.Insert(ci2)
if err != nil {
t.Fatal(err)
}
assert.NoError(t, err)
has, err = testEngine.Desc("id").Get(di2)
if err != nil {
t.Fatal(err)
}
if !has {
t.Fatal(ErrNotExist)
}
if ci2.Created != di2.Created {
t.Fatal("should equal:", ci2, di2)
}
fmt.Println("ci2:", ci2, "di2:", di2)
assert.NoError(t, err)
assert.True(t, has)
assert.EqualValues(t, ci2.Created, di2.Created)
di3 := new(CreatedInsert3)
err = testEngine.Sync2(di3)
if err != nil {
t.Fatal(err)
}
assert.NoError(t, err)
ci3 := &CreatedInsert3{}
_, err = testEngine.Insert(ci3)
if err != nil {
t.Fatal(err)
}
assert.NoError(t, err)
has, err = testEngine.Desc("id").Get(di3)
if err != nil {
t.Fatal(err)
}
if !has {
t.Fatal(ErrNotExist)
}
if ci3.Created != di3.Created {
t.Fatal("should equal:", ci3, di3)
}
fmt.Println("ci3:", ci3, "di3:", di3)
assert.NoError(t, err)
assert.True(t, has)
assert.EqualValues(t, ci3.Created, di3.Created)
di4 := new(CreatedInsert4)
err = testEngine.Sync2(di4)
if err != nil {
t.Fatal(err)
}
assert.NoError(t, err)
ci4 := &CreatedInsert4{}
_, err = testEngine.Insert(ci4)
if err != nil {
t.Fatal(err)
}
assert.NoError(t, err)
has, err = testEngine.Desc("id").Get(di4)
if err != nil {
t.Fatal(err)
}
if !has {
t.Fatal(ErrNotExist)
}
if ci4.Created != di4.Created {
t.Fatal("should equal:", ci4, di4)
}
fmt.Println("ci4:", ci4, "di4:", di4)
assert.NoError(t, err)
assert.True(t, has)
assert.EqualValues(t, ci4.Created, di4.Created)
di5 := new(CreatedInsert5)
err = testEngine.Sync2(di5)
if err != nil {
t.Fatal(err)
}
assert.NoError(t, err)
ci5 := &CreatedInsert5{}
_, err = testEngine.Insert(ci5)
if err != nil {
t.Fatal(err)
}
assert.NoError(t, err)
has, err = testEngine.Desc("id").Get(di5)
if err != nil {
t.Fatal(err)
}
if !has {
t.Fatal(ErrNotExist)
}
if ci5.Created.Unix() != di5.Created.Unix() {
t.Fatal("should equal:", ci5, di5)
}
fmt.Println("ci5:", ci5, "di5:", di5)
assert.NoError(t, err)
assert.True(t, has)
assert.EqualValues(t, ci5.Created.Unix(), di5.Created.Unix())
di6 := new(CreatedInsert6)
err = testEngine.Sync2(di6)
if err != nil {
t.Fatal(err)
}
assert.NoError(t, err)
oldTime := time.Now().Add(-time.Hour)
ci6 := &CreatedInsert6{Created: oldTime}
_, err = testEngine.Insert(ci6)
if err != nil {
t.Fatal(err)
}
assert.NoError(t, err)
has, err = testEngine.Desc("id").Get(di6)
if err != nil {
t.Fatal(err)
}
if !has {
t.Fatal(ErrNotExist)
}
if ci6.Created.Unix() != di6.Created.Unix() {
t.Fatal("should equal:", ci6, di6)
}
fmt.Println("ci6:", ci6, "di6:", di6)
assert.NoError(t, err)
assert.True(t, has)
assert.EqualValues(t, ci6.Created.Unix(), di6.Created.Unix())
}
type JsonTime time.Time
@ -509,25 +390,16 @@ func TestCreatedJsonTime(t *testing.T) {
di5 := new(MyJsonTime)
err := testEngine.Sync2(di5)
if err != nil {
t.Fatal(err)
}
assert.NoError(t, err)
ci5 := &MyJsonTime{}
_, err = testEngine.Insert(ci5)
if err != nil {
t.Fatal(err)
}
assert.NoError(t, err)
has, err := testEngine.Desc("id").Get(di5)
if err != nil {
t.Fatal(err)
}
if !has {
t.Fatal(ErrNotExist)
}
if time.Time(ci5.Created).Unix() != time.Time(di5.Created).Unix() {
t.Fatal("should equal:", time.Time(ci5.Created).Unix(), time.Time(di5.Created).Unix())
}
fmt.Println("ci5:", ci5, "di5:", di5)
assert.NoError(t, err)
assert.True(t, has)
assert.EqualValues(t, time.Time(ci5.Created).Unix(), time.Time(di5.Created).Unix())
var dis = make([]MyJsonTime, 0)
err = testEngine.Find(&dis)
@ -546,10 +418,7 @@ func TestInsertMulti2(t *testing.T) {
{Username: "xlw22", Departname: "dev", Alias: "lunny3", Created: time.Now()},
}
cnt, err := testEngine.Insert(&users)
if err != nil {
t.Error(err)
panic(err)
}
assert.NoError(t, err)
assert.EqualValues(t, len(users), cnt)
users2 := []*Userinfo{
@ -573,28 +442,10 @@ func TestInsertTwoTable(t *testing.T) {
userinfo := Userinfo{Username: "xlw3", Departname: "dev", Alias: "lunny4", Created: time.Now(), Detail: userdetail}
cnt, err := testEngine.Insert(&userinfo, &userdetail)
if err != nil {
t.Error(err)
panic(err)
}
if userinfo.Uid <= 0 {
err = errors.New("not return id error")
t.Error(err)
panic(err)
}
if userdetail.Id <= 0 {
err = errors.New("not return id error")
t.Error(err)
panic(err)
}
if cnt != 2 {
err = errors.New("insert not returned 2")
t.Error(err)
panic(err)
}
assert.NoError(t, err)
assert.Greater(t, userinfo.Uid, int64(0))
assert.Greater(t, userdetail.Id, int64(0))
assert.EqualValues(t, 2, cnt)
}
func TestInsertCreatedInt64(t *testing.T) {

+ 179
- 706
session_pk_test.go
File diff suppressed because it is too large
View File


+ 2
- 8
session_schema_test.go View File

@ -260,16 +260,10 @@ func TestCharst(t *testing.T) {
assert.NoError(t, prepareEngine())
err := testEngine.DropTables("user_charset")
if err != nil {
t.Error(err)
panic(err)
}
assert.NoError(t, err)
err = testEngine.Charset("utf8").Table("user_charset").CreateTable(&Userinfo{})
if err != nil {
t.Error(err)
panic(err)
}
assert.NoError(t, err)
}
func TestSync2_1(t *testing.T) {

+ 2
- 6
session_tx_test.go View File

@ -53,9 +53,7 @@ func TestCombineTransaction(t *testing.T) {
counter := func() {
total, err := testEngine.Count(&Userinfo{})
if err != nil {
t.Error(err)
}
assert.NoError(t, err)
fmt.Printf("----now total %v records\n", total)
}
@ -97,9 +95,7 @@ func TestCombineTransactionSameMapper(t *testing.T) {
counter := func() {
total, err := testEngine.Count(&Userinfo{})
if err != nil {
t.Error(err)
}
assert.NoError(t, err)
fmt.Printf("----now total %v records\n", total)
}

+ 103
- 252
session_update_test.go View File

@ -5,7 +5,6 @@
package xorm
import (
"errors"
"fmt"
"sync"
"testing"
@ -277,10 +276,7 @@ func TestUpdateMap2(t *testing.T) {
_, err := testEngine.Table("update_must_cols").Where("id =?", 1).Update(map[string]interface{}{
"bool": true,
})
if err != nil {
t.Error(err)
panic(err)
}
assert.NoError(t, err)
}
func TestUpdate1(t *testing.T) {
@ -293,14 +289,8 @@ func TestUpdate1(t *testing.T) {
var ori Userinfo
has, err := testEngine.Get(&ori)
if err != nil {
t.Error(err)
panic(err)
}
if !has {
t.Error(errors.New("not exist"))
panic(errors.New("not exist"))
}
assert.NoError(t, err)
assert.True(t, has)
// update by id
user := Userinfo{Username: "xxx", Height: 1.2}
@ -324,10 +314,7 @@ func TestUpdate1(t *testing.T) {
{
user := &Userinfo{Username: "not null data", Height: 180.5}
_, err := testEngine.Insert(user)
if err != nil {
t.Error(err)
panic(err)
}
assert.NoError(t, err)
userID := user.Uid
has, err := testEngine.ID(userID).
@ -337,29 +324,15 @@ func TestUpdate1(t *testing.T) {
And("detail_id = ?", 0).
And("is_man = ?", 0).
Get(&Userinfo{})
if err != nil {
t.Error(err)
panic(err)
}
if !has {
err = errors.New("cannot insert properly")
t.Error(err)
panic(err)
}
assert.NoError(t, err)
assert.True(t, has, "cannot insert properly")
updatedUser := &Userinfo{Username: "null data"}
cnt, err = testEngine.ID(userID).