示例#1
0
func TestSaveToDb(t *testing.T) {
	//for hacking testing added :-)
	db := csdb.MustConnectTest()
	defer db.Close()
	dbrSess := dbr.NewConnection(db, nil).NewSession(nil)

	//		var peds = TableProductEntityDecimalSlice{
	//			&TableProductEntityDecimal{ValueID: 1, AttributeID: 73, StoreID: 0, EntityID: 1, Value: money.New(money.Precision(4)).Set(9990000)},
	//			&TableProductEntityDecimal{ValueID: 2, AttributeID: 78, StoreID: 0, EntityID: 1, Value: money.New(money.Precision(4))}, // null values
	//			&TableProductEntityDecimal{ValueID: 3, AttributeID: 74, StoreID: 0, EntityID: 1, Value: money.New(money.Precision(4))}, // null values
	//			&TableProductEntityDecimal{ValueID: 4, AttributeID: 77, StoreID: 0, EntityID: 1, Value: money.New(money.Precision(4))}, // null values
	//			&TableProductEntityDecimal{ValueID: 5, AttributeID: 73, StoreID: 1, EntityID: 1, Value: money.New(money.Precision(4)).Set(7059933)},
	//			&TableProductEntityDecimal{ValueID: 6, AttributeID: 73, StoreID: 4, EntityID: 1, Value: money.New(money.Precision(4)).Set(7059933)},
	//			&TableProductEntityDecimal{ValueID: 7, AttributeID: 73, StoreID: 2, EntityID: 1, Value: money.New(money.Precision(4)).Set(7059933)},
	//			&TableProductEntityDecimal{ValueID: 8, AttributeID: 73, StoreID: 3, EntityID: 1, Value: money.New(money.Precision(4)).Set(7059933)},
	//		}

	tuple := &TableProductEntityDecimal{ValueID: 0, AttributeID: 73, StoreID: 3, EntityID: 231, Value: money.New(money.Precision(4)).Set(7779933)}
	tuple2 := &TableProductEntityDecimal{ValueID: 0, AttributeID: 74, StoreID: 2, EntityID: 231, Value: money.New(money.Precision(4)).Set(8889933)}
	ib := dbrSess.InsertInto("catalog_product_entity_decimal")
	ib.Columns("attribute_id", "store_id", "entity_id", "value")

	ib.Values(tuple.AttributeID, tuple.StoreID, tuple.EntityID, &tuple.Value)
	ib.Values(tuple2.AttributeID, tuple2.StoreID, tuple2.EntityID, &tuple2.Value)
	//	t.Error(ib.ToSql())
	res, err := ib.Exec()
	t.Log(err)
	t.Logf("%#v", res)
	t.Log(res.LastInsertId())
	t.Log(res.RowsAffected())

}
示例#2
0
func TestGetAttributeSelectSql(t *testing.T) {
	dbc := csdb.MustConnectTest()
	defer dbc.Close()

	dbrSess := dbc.NewSession()
	dbrSelect, err := eav.GetAttributeSelectSql(dbrSess, codegen.NewAddAttrTables(dbc.DB, "customer"), 1, 4)
	if err != nil {
		t.Fatal(err)
	}
	sql, _, err := dbrSelect.ToSql()
	assert.NoError(t, err)

	_, err = sqlbeautifier.FromString(sql) // check for syntax errors
	if err != nil {
		t.Fatalf("%s\n\n%s\n", err, sql)
	}

	if testWantGetAttributeSelectSql != sql {

		buf, err := sqlbeautifier.FromString(testWantGetAttributeSelectSql)
		if err != nil {
			t.Fatalf("%s\n%s\n", err, testWantGetAttributeSelectSql)
		}
		sql = sqlbeautifier.MustFromString(sql)
		println(diff.MustUnified(buf.String(), sql), "\n")
		t.Fatal(sql)
	}

	// @todo error is that we have column attribute_model in the select list but it should not occur
	// because in codegen it is defined that this column has no usage so we can skip it.
}
示例#3
0
func TestEntityTypeSliceGetByCode(t *testing.T) {
	db := csdb.MustConnectTest()
	defer db.Close()
	dbrSess := dbr.NewConnection(db, nil).NewSession(nil)

	s, err := eav.TableCollection.Structure(eav.TableIndexEntityType)
	if err != nil {
		t.Error(err)
	}

	var entityTypeCollection eav.TableEntityTypeSlice
	_, err = dbrSess.
		Select(s.Columns...).
		From(s.Name).
		LoadStructs(&entityTypeCollection)
	if err != nil {
		t.Error(err)
	}

	etc, err := entityTypeCollection.GetByCode("catalog_categories")
	assert.Nil(t, etc)
	assert.Error(t, err)

	etc, err = entityTypeCollection.GetByCode("catalog_category")
	assert.NotNil(t, etc)
	assert.NoError(t, err)
}
示例#4
0
func TestStorageReInit(t *testing.T) {

	// quick implement, use mock of dbr.SessionRunner and remove connection
	dbc := csdb.MustConnectTest()
	defer func() { assert.NoError(t, dbc.Close()) }()

	nsg := store.MustNewStorage(nil, nil, nil)
	assert.NoError(t, nsg.ReInit(dbc.NewSession()))

	stores, err := nsg.Stores()
	assert.NoError(t, err)
	assert.True(t, stores.Len() > 0, "Expecting at least one store loaded from DB")
	for _, s := range stores {
		assert.NotEmpty(t, s.Data.Code.String, "Store: %#v", s.Data)
	}

	groups, err := nsg.Groups()
	assert.True(t, groups.Len() > 0, "Expecting at least one group loaded from DB")
	assert.NoError(t, err)
	for _, g := range groups {
		assert.NotEmpty(t, g.Data.Name, "Group: %#v", g.Data)
	}

	websites, err := nsg.Websites()
	assert.True(t, websites.Len() > 0, "Expecting at least one website loaded from DB")
	assert.NoError(t, err)
	for _, w := range websites {
		assert.NotEmpty(t, w.Data.Code.String, "Website: %#v", w.Data)
	}
}
示例#5
0
func TestTableStructure(t *testing.T) {
	db := csdb.MustConnectTest()
	defer db.Close()

	sValid, err := tableMap.Structure(table1)
	assert.NotNil(t, sValid)
	assert.NoError(t, err)

	assert.Equal(t, "catalog_category_anc_categs_index_tmp", tableMap.Name(table2))
	assert.Equal(t, "", tableMap.Name(table4))

	sInvalid, err := tableMap.Structure(table4)
	assert.Nil(t, sInvalid)
	assert.Error(t, err)

	dbrSess := dbr.NewConnection(db, nil).NewSession(nil)
	selectBuilder, err := sValid.Select(dbrSess)
	assert.NoError(t, err)
	selectString, _ := selectBuilder.ToSql()
	assert.Equal(t, "SELECT `main_table`.`category_id`, `main_table`.`path` FROM `catalog_category_anc_categs_index_idx` AS `main_table`", selectString)

	selectBuilder, err = sInvalid.Select(dbrSess)
	assert.Error(t, err)
	assert.Nil(t, selectBuilder)
}
示例#6
0
func TestGetFieldNames(t *testing.T) {
	db := csdb.MustConnectTest()
	defer db.Close()

	tests := []struct {
		table  string
		pkOnly bool
		count  int
	}{
		{
			table:  "eav_attribute",
			pkOnly: false,
			count:  15,
		},
		{
			table:  "catalog_product_entity_decimal",
			pkOnly: true,
			count:  1,
		},
	}

	for _, test := range tests {
		cols, err := GetColumns(db, test.table)
		if err != nil {
			t.Error(err)
		}
		fields := cols.GetFieldNames(test.pkOnly)
		assert.Len(t, fields, test.count)
	}
}
示例#7
0
func TestGetTables(t *testing.T) {
	db := csdb.MustConnectTest()
	defer db.Close()

	tests := []struct {
		query    string
		expErr   bool
		expCount int
	}{
		{
			query:    "SHOW TABLES LIKE 'catalog_product_entity%'",
			expErr:   false,
			expCount: 11,
		},
		{
			query:    "SHOW TABLES LIK ' catalog_product_entity",
			expErr:   true,
			expCount: 0,
		},
	}

	for _, test := range tests {
		tables, err := GetTables(db, test.query)
		if test.expErr {
			assert.Error(t, err)
		}
		if !test.expErr && err != nil {
			t.Error(err)
		}

		assert.Len(t, tables, test.expCount)
	}
}
示例#8
0
// TestApplyCoreConfigData reads from the MySQL core_config_data table and applies
// these value to the underlying storage. tries to get back the values from the
// underlying storage
func TestApplyCoreConfigData(t *testing.T) {
	defer debugLogBuf.Reset()
	defer infoLogBuf.Reset()

	dbc := csdb.MustConnectTest()
	defer func() { assert.NoError(t, dbc.Close()) }()
	sess := dbc.NewSession(nil) // nil tricks the NewSession ;-)

	s := config.NewService()
	defer func() { assert.NoError(t, s.Close()) }()

	loadedRows, writtenRows, err := s.ApplyCoreConfigData(sess)
	if err != nil {
		t.Fatal(err)
	}
	assert.True(t, loadedRows > 9, "loadedRows %d", loadedRows)
	assert.True(t, writtenRows > 9, "writtenRows %d", writtenRows)

	//	println("\n", debugLogBuf.String(), "\n")
	//	println("\n", infoLogBuf.String(), "\n")

	assert.NoError(t, s.Write(config.Path("web/secure/offloader_header"), config.ScopeDefault(), config.Value("SSL_OFFLOADED")))

	h, err := s.String(config.Path("web/secure/offloader_header"), config.ScopeDefault())
	assert.NoError(t, err)
	assert.Exactly(t, "SSL_OFFLOADED", h)

	assert.Len(t, s.Storage.AllKeys(), writtenRows)
}
示例#9
0
func init() {
	dbc := csdb.MustConnectTest()
	defer dbc.Close()
	if err := eav.TableCollection.Init(dbc.NewSession()); err != nil {
		panic(err)
	}
}
示例#10
0
func init() {
	dbc := csdb.MustConnectTest()
	config.TableCollection.Init(dbc.NewSession())
	if err := dbc.Close(); err != nil {
		panic(err)
	}
}
示例#11
0
func TestDBStorageMultipleStmt(t *testing.T) {
	debugLogBuf.Reset()
	defer debugLogBuf.Reset() // contains only data from the debug level, info level will be dumped to os.Stdout
	defer infoLogBuf.Reset()

	if testing.Short() {
		t.Skip("Test skipped in short mode")
	}
	dbc := csdb.MustConnectTest()
	defer func() { assert.NoError(t, dbc.Close()) }()

	sdb := config.MustNewDBStorage(dbc.DB)
	sdb.All.Idle = time.Second * 1
	sdb.Read.Idle = time.Second * 1
	sdb.Write.Idle = time.Second * 1

	sdb.Start()

	tests := []struct {
		key       string
		value     interface{}
		wantValue string
	}{
		{"websites/10/testDBStorage/secure/base_url", "http://corestore.io", "http://corestore.io"},
		{"websites/10/testDBStorage/log/active", 1, "1"},
		{"websites/20/testDBStorage/log/clean", 19.999, "19.999"},
		{"websites/20/testDBStorage/product/shipping", 29.999, "29.999"},
		{"default/0/testDBStorage/checkout/multishipping", false, "false"},
	}
	for i, test := range tests {
		sdb.Set(test.key, test.value)
		assert.Exactly(t, test.wantValue, sdb.Get(test.key), "Test: %v", test)
		if i < 2 {
			// last two iterations reopen a new statement, not closing it and reusing it
			time.Sleep(time.Millisecond * 1500) // trigger ticker to close statements
		}
	}

	for i, test := range tests {
		ak := util.StringSlice(sdb.AllKeys())
		assert.True(t, ak.Include(test.key), "Missing Key: %s", test.key)
		if i < 2 {
			time.Sleep(time.Millisecond * 1500) // trigger ticker to close statements
		}
	}
	assert.NoError(t, sdb.Stop())

	logStr := debugLogBuf.String()
	assert.Exactly(t, 3, strings.Count(logStr, `csdb.ResurrectStmt.stmt.Prepare SQL: "INSERT INTO`))
	assert.Exactly(t, 3, strings.Count(logStr, "csdb.ResurrectStmt.stmt.Prepare SQL: \"SELECT `value` FROM"))

	assert.Exactly(t, 4, strings.Count(logStr, `csdb.ResurrectStmt.stmt.Close SQL: "INSERT INTO`), "\n%s\n", logStr)
	assert.Exactly(t, 4, strings.Count(logStr, "csdb.ResurrectStmt.stmt.Close SQL: \"SELECT `value` FROM"))

	//println("\n", logStr, "\n")

	// 6 is: open close for iteration 0+1, open in iteration 2 and close in iteration 4
	assert.Exactly(t, 6, strings.Count(logStr, fmt.Sprintf("CONCAT(scope,'%s',scope_id,'%s',path) AS `fqpath`", scope.PS, scope.PS)))
}
示例#12
0
func TestApplyCoreConfigData(t *testing.T) {
	db := csdb.MustConnectTest()
	defer db.Close()
	sess := dbr.NewConnection(db, nil).NewSession(nil)

	m := config.NewManager()
	if err := m.ApplyCoreConfigData(sess); err != nil {
		t.Error(err)
	}
}
示例#13
0
func TestTableGroupSliceLoad(t *testing.T) {
	db := csdb.MustConnectTest()
	defer db.Close()
	dbrSess := dbr.NewConnection(db, nil).NewSession(nil)
	var groups store.TableGroupSlice
	groups.Load(dbrSess)
	assert.True(t, groups.Len() > 2)
	for _, s := range groups {
		assert.True(t, len(s.Name) > 1)
	}
}
示例#14
0
func TestTableStoreSliceLoad(t *testing.T) {
	db := csdb.MustConnectTest()
	defer db.Close()
	dbrSess := dbr.NewConnection(db, nil).NewSession(nil)
	var stores store.TableStoreSlice
	stores.Load(dbrSess)
	assert.True(t, stores.Len() > 2)
	for _, s := range stores {
		assert.True(t, len(s.Code.String) > 1)
	}
}
示例#15
0
func TestApplyCoreConfigData(t *testing.T) {
	dbc := csdb.MustConnectTest()
	defer func() { assert.NoError(t, dbc.Close()) }()
	sess := dbc.NewSession(nil)

	m := config.NewManager()
	if err := m.ApplyCoreConfigData(sess); err != nil {
		t.Error(err)
	}
	// todo check if data has been really written ;-)
}
示例#16
0
func TestGetAttributeSelectSql(t *testing.T) {
	db := csdb.MustConnectTest()
	defer db.Close()

	dbrSess := dbr.NewConnection(db, nil).NewSession(nil)
	dbrSelect, err := eav.GetAttributeSelectSql(dbrSess, NewAddAttrTables(db, "customer"), 1, 4)
	if err != nil {
		t.Error(err)
	}
	sql, _ := dbrSelect.ToSql()
	assert.Equal(t, "SELECT `main_table`.`attribute_id`, `main_table`.`entity_type_id`, `main_table`.`attribute_code`, `main_table`.`backend_model`, `main_table`.`backend_type`, `main_table`.`backend_table`, `main_table`.`frontend_model`, `main_table`.`frontend_input`, `main_table`.`frontend_label`, `main_table`.`frontend_class`, `main_table`.`source_model`, `main_table`.`is_user_defined`, `main_table`.`is_unique`, `main_table`.`note`, `additional_table`.`input_filter`, `additional_table`.`validate_rules`, `additional_table`.`is_system`, `additional_table`.`sort_order`, `additional_table`.`data_model`, `additional_table`.`is_used_for_customer_segment`, IFNULL(`scope_table`.`is_visible`, `additional_table`.`is_visible`) AS `is_visible`, IFNULL(`scope_table`.`is_required`, `main_table`.`is_required`) AS `is_required`, IFNULL(`scope_table`.`default_value`, `main_table`.`default_value`) AS `default_value`, IFNULL(`scope_table`.`multiline_count`, `additional_table`.`multiline_count`) AS `multiline_count` FROM `eav_attribute` AS `main_table` INNER JOIN `customer_eav_attribute` AS `additional_table` ON (`additional_table`.`attribute_id` = `main_table`.`attribute_id`) AND (`main_table`.`entity_type_id` = ?) LEFT JOIN `customer_eav_attribute_website` AS `scope_table` ON (`scope_table`.`attribute_id` = `main_table`.`attribute_id`) AND (`scope_table`.`website_id` = ?)", sql)
}
示例#17
0
func TestTableStoreSliceLoad(t *testing.T) {
	dbc := csdb.MustConnectTest()
	defer dbc.Close()
	dbrSess := dbc.NewSession()

	var stores store.TableStoreSlice
	stores.SQLSelect(dbrSess)
	assert.True(t, stores.Len() >= 2) // @todo proper test data in database
	for _, s := range stores {
		assert.True(t, len(s.Code.String) > 1)
	}
}
示例#18
0
func TestTableWebsiteSliceLoad(t *testing.T) {
	dbc := csdb.MustConnectTest()
	defer dbc.Close()
	dbrSess := dbc.NewSession()

	var websites store.TableWebsiteSlice
	websites.Load(dbrSess)
	assert.True(t, websites.Len() > 2)
	for _, s := range websites {
		assert.True(t, len(s.Code.String) > 1)
	}
}
示例#19
0
func TestTableStoreSliceLoad(t *testing.T) {
	defer debugLogBuf.Reset()
	dbc := csdb.MustConnectTest()
	defer func() { assert.NoError(t, dbc.Close()) }()
	dbrSess := dbc.NewSession()

	var stores store.TableStoreSlice
	_, err := stores.SQLSelect(dbrSess)
	assert.NoError(t, err)
	assert.True(t, stores.Len() >= 2) // @todo proper test data in database
	for _, s := range stores {
		assert.True(t, len(s.Code.String) > 1)
	}
}
示例#20
0
func TestTableWebsiteSliceLoad(t *testing.T) {
	dbc := csdb.MustConnectTest()
	defer func() { assert.NoError(t, dbc.Close()) }()
	dbrSess := dbc.NewSession()

	var websites store.TableWebsiteSlice
	_, err := websites.SQLSelect(dbrSess)
	assert.NoError(t, err)

	assert.True(t, websites.Len() >= 2)
	for _, s := range websites {
		assert.True(t, len(s.Code.String) > 1)
	}
}
示例#21
0
// depends on generated code
func TestSQLQueryToColumnsToStruct(t *testing.T) {
	db := csdb.MustConnectTest()
	defer db.Close()

	dbrSess := dbr.NewConnection(db, nil).NewSession(nil)
	dbrSelect, err := eav.GetAttributeSelectSql(dbrSess, NewAddAttrTables(db, "catalog_product"), 4, 0)
	if err != nil {
		t.Error(err)
	}

	colSliceDbr, err := SQLQueryToColumns(db, dbrSelect)
	if err != nil {
		t.Error(err)
	}

	assert.Len(t, colSliceDbr, 35)

	for _, col := range colSliceDbr {
		assert.True(t, col.Field.Valid, fmt.Sprintf("%#v", col))
		assert.True(t, col.Type.Valid, fmt.Sprintf("%#v", col))
	}

	columns2, err2 := SQLQueryToColumns(db, nil, "SELECT * FROM `catalog_product_option`", " ORDER BY option_id DESC")
	if err2 != nil {
		t.Error(err2)
	}
	assert.Len(t, columns2, 10)
	for _, col := range columns2 {
		assert.True(t, col.Field.Valid, fmt.Sprintf("%#v", col))
		assert.True(t, col.Type.Valid, fmt.Sprintf("%#v", col))
	}

	colSliceDbr.MapSQLToGoDBRType()
	code, err := ColumnsToStructCode(nil, "testStruct", colSliceDbr)
	if err != nil {
		t.Error(err, "\n", string(code))
	}

	checkContains := [][]byte{
		[]byte(`TeststructSlice`),
		[]byte(`dbr.NullString`),
		[]byte("`db:\"is_visible_in_advanced_search\"`"),
	}
	for _, s := range checkContains {
		if false == bytes.Contains(code, s) {
			t.Errorf("%s\ndoes not contain %s", code, s)
		}
	}
}
示例#22
0
func TestTableGroupSliceLoad(t *testing.T) {
	dbc := csdb.MustConnectTest()
	defer dbc.Close()
	dbrSess := dbc.NewSession()

	var groups store.TableGroupSlice
	rows, err := groups.Load(dbrSess)
	assert.NoError(t, err)
	assert.True(t, rows > 0)

	assert.True(t, groups.Len() > 2)
	for _, s := range groups {
		assert.True(t, len(s.Name) > 1)
	}
}
示例#23
0
func TestValue(t *testing.T) {
	dbrSess := csdb.MustConnectTest().NewSession()

	tuple := &TableProductEntityDecimal{ValueID: 0, AttributeID: 73, StoreID: 3, EntityID: 231, Value: money.New(money.WithPrecision(4)).Set(7779933)}
	tuple2 := &TableProductEntityDecimal{ValueID: 0, AttributeID: 74, StoreID: 2, EntityID: 231, Value: money.New(money.WithPrecision(4)).Set(8889933)}
	ib := dbrSess.InsertInto("catalog_product_entity_decimal")
	ib.Columns("attribute_id", "store_id", "entity_id", "value")

	ib.Values(tuple.AttributeID, tuple.StoreID, tuple.EntityID, tuple.Value)
	ib.Values(tuple2.AttributeID, tuple2.StoreID, tuple2.EntityID, &tuple2.Value)

	sql, args := ib.ToSql()
	fullSql, err := dbr.Preprocess(sql, args)
	assert.NoError(t, err)
	assert.Contains(t, fullSql, `(73,3,231,777.9933),(74,2,231,888.9933)`)
}
示例#24
0
func TestGetAttributeSelectSql(t *testing.T) {
	dbc := csdb.MustConnectTest()
	defer dbc.Close()

	dbrSess := dbc.NewSession()
	dbrSelect, err := eav.GetAttributeSelectSql(dbrSess, codegen.NewAddAttrTables(dbc.DB, "customer"), 1, 4)
	if err != nil {
		t.Error(err)
	} else {
		sql, _ := dbrSelect.ToSql()
		assert.Equal(t, "SELECT `main_table`.`attribute_id`, `main_table`.`entity_type_id`, `main_table`.`attribute_code`, `main_table`.`backend_model`, `main_table`.`backend_type`, `main_table`.`backend_table`, `main_table`.`frontend_model`, `main_table`.`frontend_input`, `main_table`.`frontend_label`, `main_table`.`frontend_class`, `main_table`.`source_model`, `main_table`.`is_user_defined`, `main_table`.`is_unique`, `main_table`.`note`, `additional_table`.`input_filter`, `additional_table`.`validate_rules`, `additional_table`.`is_system`, `additional_table`.`sort_order`, `additional_table`.`data_model`, IFNULL(`scope_table`.`is_visible`, `additional_table`.`is_visible`) AS `is_visible`, IFNULL(`scope_table`.`is_required`, `main_table`.`is_required`) AS `is_required`, IFNULL(`scope_table`.`default_value`, `main_table`.`default_value`) AS `default_value`, IFNULL(`scope_table`.`multiline_count`, `additional_table`.`multiline_count`) AS `multiline_count` FROM `eav_attribute` AS `main_table` INNER JOIN `customer_eav_attribute` AS `additional_table` ON (`additional_table`.`attribute_id` = `main_table`.`attribute_id`) AND (`main_table`.`entity_type_id` = ?) LEFT JOIN `customer_eav_attribute_website` AS `scope_table` ON (`scope_table`.`attribute_id` = `main_table`.`attribute_id`) AND (`scope_table`.`website_id` = ?)", sql)
	}

	// @todo error is that we have column attribute_model in the select list but it should not occur
	// because in codegen it is defined that this column has no usage so we can skip it.
}
示例#25
0
// BenchmarkGetTables-4	    2000	    865974 ns/op	   31042 B/op	     683 allocs/op
func BenchmarkGetTables(b *testing.B) {
	dbc := csdb.MustConnectTest()
	defer dbc.Close()
	b.ReportAllocs()
	var err error
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		benchmarkGetTables, err = GetTables(dbc.NewSession())
		if err != nil {
			b.Error(err)
		}
		if len(benchmarkGetTables) < 200 {
			b.Errorf("There should be at least 200 tables in the database. Got: %d", len(benchmarkGetTables))
		}
	}
}
示例#26
0
func TestNewManagerReInit(t *testing.T) {
	numCPU := runtime.NumCPU()
	prevCPU := runtime.GOMAXPROCS(numCPU)
	t.Logf("GOMAXPROCS was: %d now: %d", prevCPU, numCPU)
	defer runtime.GOMAXPROCS(prevCPU)

	// quick implement, use mock of dbr.SessionRunner and remove connection
	db := csdb.MustConnectTest()
	defer db.Close()
	dbrSess := dbr.NewConnection(db, nil).NewSession(nil)

	storeManager := store.NewManager(store.NewStorageOption(nil /* trick it*/))
	if err := storeManager.ReInit(dbrSess); err != nil {
		t.Fatal(err)
	}

	tests := []struct {
		have    config.ScopeIDer
		wantErr error
	}{
		{config.ScopeCode("de"), nil},
		{config.ScopeCode("cz"), store.ErrStoreNotFound},
		{config.ScopeCode("de"), nil},
		{config.ScopeID(1), nil},
		{config.ScopeID(100), store.ErrStoreNotFound},
		{mockIDCode{1, "de"}, nil},
		{mockIDCode{2, "cz"}, store.ErrStoreNotFound},
		{mockIDCode{2, ""}, nil},
		{nil, store.ErrAppStoreNotSet}, // if set returns default store
	}

	for _, test := range tests {
		s, err := storeManager.Store(test.have)
		if test.wantErr == nil {
			assert.NoError(t, err, "For test: %#v", test)
			assert.NotNil(t, s)
			//			assert.NotEmpty(t, s.Data().Code.String, "%#v", s.Data())
		} else {
			assert.Error(t, err, "For test: %#v", test)
			assert.EqualError(t, test.wantErr, err.Error(), "For test: %#v", test)
			assert.Nil(t, s)
		}
	}
	assert.False(t, storeManager.IsCacheEmpty())
	storeManager.ClearCache()
	assert.True(t, storeManager.IsCacheEmpty())
}
示例#27
0
func TestNewTableManagerInit(t *testing.T) {
	dbc := csdb.MustConnectTest()
	defer dbc.Close()
	i := csdb.Index(4711)
	tm0 := csdb.NewTableManager(csdb.AddTableByName(i, "admin_user"))
	assert.EqualError(t, tm0.Init(dbc.NewSession(), true), csdb.ErrManagerInitReload.Error())
	err := tm0.Init(dbc.NewSession())
	assert.NoError(t, err)

	table, err2 := tm0.Structure(i)
	assert.NoError(t, err2)
	assert.Equal(t, 1, table.CountPK)
	assert.Equal(t, 1, table.CountUnique)
	assert.True(t, len(table.Columns.FieldNames()) >= 15)

	assert.Nil(t, tm0.Init(dbc.NewSession()))
}
示例#28
0
func TestDBStorageOneStmt(t *testing.T) {
	debugLogBuf.Reset()
	defer debugLogBuf.Reset()
	defer infoLogBuf.Reset()

	dbc := csdb.MustConnectTest()
	defer func() { assert.NoError(t, dbc.Close()) }()

	sdb := config.MustNewDBStorage(dbc.DB).Start()

	// Stop() would only be called under rare circumstances on a production system
	defer func() { assert.NoError(t, sdb.Stop()) }()

	tests := []struct {
		key       string
		value     interface{}
		wantNil   bool
		wantValue string
	}{
		{"stores/1/testDBStorage/secure/base_url", "http://corestore.io", false, "http://corestore.io"},
		{"stores/1/testDBStorage/log/active", 1, false, "1"},
		{"stores/99999/testDBStorage/log/clean", 19.999, false, "19.999"},
		{"stores/99999/testDBStorage/log/clean", 29.999, false, "29.999"},
		{"default/1/testDBStorage/catalog/purge", true, false, "true"},
		{"default/1/testDBStorage/catalog/clean", 0, false, "0"},
	}
	for _, test := range tests {
		sdb.Set(test.key, test.value)
		if test.wantNil {
			assert.Nil(t, sdb.Get(test.key), "Test: %v", test)
		} else {
			assert.Exactly(t, test.wantValue, sdb.Get(test.key), "Test: %v", test)
		}
	}

	assert.Exactly(t, 1, strings.Count(debugLogBuf.String(), `csdb.ResurrectStmt.stmt.Prepare SQL: "INSERT INTO`))
	assert.Exactly(t, 1, strings.Count(debugLogBuf.String(), "csdb.ResurrectStmt.stmt.Prepare SQL: \"SELECT `value` FROM"))

	for _, test := range tests {
		ak := util.StringSlice(sdb.AllKeys()) // trigger many queries with one statement
		assert.True(t, ak.Include(test.key), "Missing Key: %s", test.key)
	}
	assert.Exactly(t, 1, strings.Count(debugLogBuf.String(), fmt.Sprintf("CONCAT(scope,'%s',scope_id,'%s',path) AS `fqpath`", scope.PS, scope.PS)))
}
示例#29
0
func TestNewManagerReInit(t *testing.T) {

	t.Skip(TODO_Better_Test_Data)

	// quick implement, use mock of dbr.SessionRunner and remove connection
	dbc := csdb.MustConnectTest()
	defer dbc.Close()
	dbrSess := dbc.NewSession()

	storeManager := store.NewManager(store.NewStorage(nil /* trick it*/))
	if err := storeManager.ReInit(dbrSess); err != nil {
		t.Fatal(err)
	}

	tests := []struct {
		have    scope.StoreIDer
		wantErr error
	}{
		{scope.MockCode("dede"), nil},
		{scope.MockCode("czcz"), store.ErrIDNotFoundTableStoreSlice},
		{scope.MockID(1), nil},
		{scope.MockID(100), store.ErrStoreNotFound},
		{mockIDCode{1, "dede"}, nil},
		{mockIDCode{2, "czfr"}, store.ErrStoreNotFound},
		{mockIDCode{2, ""}, nil},
		{nil, store.ErrAppStoreNotSet}, // if set returns default store
	}

	for _, test := range tests {
		s, err := storeManager.Store(test.have)
		if test.wantErr == nil {
			assert.NoError(t, err, "No Err; for test: %#v", test)
			assert.NotNil(t, s)
			//			assert.NotEmpty(t, s.Data.Code.String, "%#v", s.Data)
		} else {
			assert.Error(t, err, "Err for test: %#v", test)
			assert.EqualError(t, test.wantErr, err.Error(), "EqualErr for test: %#v", test)
			assert.Nil(t, s)
		}
	}
	assert.False(t, storeManager.IsCacheEmpty())
	storeManager.ClearCache()
	assert.True(t, storeManager.IsCacheEmpty())
}
示例#30
0
func off_TestLoadFromDb(t *testing.T) {
	//for hacking testing added :-)
	conn := csdb.MustConnectTest()
	defer conn.Close()
	dbrSess := conn.NewSession()

	sel := dbrSess.SelectBySql("SELECT * FROM `catalog_product_entity_decimal`")
	var peds TableProductEntityDecimalSlice

	if rows, err := sel.LoadStructs(&peds); err != nil {
		t.Error(err)
	} else if rows == 0 {
		t.Error("0 rows loaded")
	}

	for _, ped := range peds {
		fmt.Printf("%#v\n", ped)
	}
}