Пример #1
0
//-----------------------------------------------------------------------------
// Test
//-----------------------------------------------------------------------------
func TestSetDataToStruct(t *testing.T) {
	//tu.SkipLog(t)

	//var columns = []string{"field1", "field2", "field3"}
	//values := []interface{}{10, "Harry", "Japan"}
	values := make([][]interface{}, 2)
	values[0] = []interface{}{10, "Harry", "UK"}
	values[1] = []interface{}{15, "Hiroki", "Japan"}

	//1.struct
	//*
	var techerInfo TeacherInfo
	err := SetDataToStruct(values, &techerInfo)
	if err != nil {
		t.Errorf("[01]SetDataToStruct: error: %s", err)
	}
	lg.Debugf("techerInfo:%#v", techerInfo)
	//*/

	//2.slice struct
	//*
	var techerInfos []TeacherInfo
	err = SetDataToStruct(values, &techerInfos)
	if err != nil {
		t.Errorf("[02]SetDataToStruct: error: %s", err)
	}
	lg.Debugf("techerInfo:%#v", techerInfos)
	//*/
}
Пример #2
0
// LoadJSONFile is to load json file
func LoadJSONFile(filePath string) *SiteInfo {
	lg.Debug("load json file")
	//initialize
	siteInfo = SiteInfo{}

	//test(get current dir)
	//dir := path.Dir(os.Args[0])
	//lg.Debugf("path.Dir(os.Args[0]): %s", dir)

	// Loading jsonfile
	if filePath == "" {
		//dir := path.Dir(os.Args[0])
		//lg.Debugf("path.Dir(os.Args[0]): %s", dir)
		//filePath = fmt.Sprintf("%s/json/teachers.json", dir)
		lg.Fatal("json filepath have to be set.")
		return nil
	}

	file, _ := ioutil.ReadFile(filePath)
	err := json.Unmarshal(file, &siteInfo)

	if err != nil {
		lg.Fatalf("json format is invalid: %v, filepath is %s", err, filePath)
		return nil
	}
	lg.Debugf("SiteInfo.Url: %v", siteInfo.URL)
	lg.Debugf("SiteInfo.Teachers[0].Id: %d, Name: %s, Country: %s", siteInfo.Teachers[0].ID, siteInfo.Teachers[0].Name, siteInfo.Teachers[0].Country)

	return &siteInfo
}
Пример #3
0
func TestGetAllData(t *testing.T) {
	//tu.SkipLog(t)

	mg := GetMongo()
	mg.GetCol(testColUser)

	//#1
	var users []User
	err := mg.C.Find(nil).Sort("age").All(&users)
	if err != nil {
		t.Errorf("mg.C.Find(nil).Sort(\"age\").All(&users) / error:%s", err)
	}
	//t.Logf("result users by find.all: %+v", users)

	//#2 unclear format of json
	mg.GetCol(testColTeacher)

	var v []map[string]interface{}
	err = mg.C.Find(nil).All(&v)
	if err != nil {
		t.Errorf("mg.C.Find(nil).All(&v) / error:%s", err)
		//result argument must be a slice address
	}
	lg.Debugf("result unclear map data by find.all: %+v", v)
	lg.Debugf("result url: %s", v[0]["url"])
}
Пример #4
0
//-----------------------------------------------------------------------------
// READ
//-----------------------------------------------------------------------------
func TestGetOneDataByColumn(t *testing.T) {
	//tu.SkipLog(t)

	mg := GetMongo()
	mg.GetCol(testColUser)

	searchName := "Ken"

	user := new(User)

	//find
	err := mg.FindOne(bson.M{"name": searchName}, user)
	//mg.C.Find(bson.M{"name": searchName}).One(user)
	if err != nil {
		t.Errorf("mg.FindOne(bson.M{\"name\": searchName}, user) / error:%s", err)
		//error:not found
	}

	lg.Debugf("user_id is %v", user.ID)
	lg.Debugf("result user by find: %v", *user)

	//save
	savedUserID = GetObjectID(user.ID)
	lg.Debugf("savedUserID is %s", savedUserID)
}
Пример #5
0
//plus placeholder
func TestSelectInsScanOne2(t *testing.T) {
	db := getMySQL().Db

	//1.int
	var userID int
	sql := "SELECT user_id FROM t_users WHERE delete_flg=?"
	b := db.SelectIns(sql, 0).ScanOne(&userID)
	if db.Err != nil {
		t.Fatalf("[1]db.SelectIns(): %s", db.Err)
	}
	lg.Debugf("user_id is %d, result is %v", userID, b)

	//2.string
	var firstName string
	sql = "SELECT first_name FROM t_users WHERE delete_flg=?"
	b = db.SelectIns(sql, 0).ScanOne(&firstName)
	if db.Err != nil {
		t.Fatalf("[2]db.SelectIns(): %s", db.Err)
	}
	lg.Debugf("firstName is %s, result is %v", firstName, b)

	//3.string
	var updated string
	sql = "SELECT update_datetime FROM t_users WHERE delete_flg=?"
	b = db.SelectIns(sql, 0).ScanOne(&updated)
	if db.Err != nil {
		t.Fatalf("[3]db.SelectIns(): %s", db.Err)
	}
	lg.Debugf("update_datetime is %s, result is %v", updated, b)
}
Пример #6
0
//JSON Type without placeholder
func TestSelectInsScanOneJSON(t *testing.T) {
	tu.SkipLog(t)

	db := getMySQL().Db

	//1.Json Data as string
	var memo string
	sql := "SELECT memo2 FROM t_invoices"
	b := db.SelectIns(sql).ScanOne(&memo)
	if db.Err != nil {
		t.Fatalf("[1]db.SelectIns(): %s", db.Err)
	}
	lg.Debugf("memo2 is %s, result is %v", memo, b)

	//convert string to slice
	var converted []int
	json.Unmarshal([]byte(memo), &converted)
	lg.Debugf("converted memo2 is %v", converted)

	//2.Json Data as Array (This is not correct)
	var memo2 []int
	sql = "SELECT memo2 FROM t_invoices"
	b = db.SelectIns(sql).ScanOne(&memo2)
	if db.Err != nil {
		t.Fatalf("[2]db.SelectIns(): %s", db.Err)
	}
	lg.Debugf("memo2 is %s, result is %v", memo2, b)

}
Пример #7
0
//-----------------------------------------------------------------------------
// CREATE
//-----------------------------------------------------------------------------
// insert one record
func TestInsertOne(t *testing.T) {
	//tu.SkipLog(t)

	mg := GetMongo()
	mg.GetCol(testColUser)

	// test data
	works := []Work{{Occupation: "programmer", CompanyId: 1}, {Occupation: "programmer", CompanyId: 2}}
	address := Address{ZipCode: "1060047", Country: "Japan", City: "Tokyo", Address1: "港区南麻布2-9-7", Address2: "マンション101"}
	user := User{Name: "Harry", Age: 25, Address: address, Works: works, CreatedAt: time.Now()}

	// insert
	err := mg.C.Insert(&user)
	if err != nil {
		t.Errorf("mg.C.Insert(&user) / error:%s", err)
	}

	// check length
	cnt, err := mg.C.Count()
	lg.Debugf("count:%d, err = %s", cnt, err)

	//TODO: Local Time
	//time:2016-07-14 16:57:39.550187911 +0900 JST
	lg.Debugf("time:%v", user.CreatedAt.Local())
}
Пример #8
0
//-----------------------------------------------------------------------------
// functions
//-----------------------------------------------------------------------------
// CallerDebug is just sample of runtime.Caller
func callerDebug(skip int) {
	programCounter, sourceFileName, sourceFileLineNum, ok := runtime.Caller(skip)
	lg.Debugf("ok: %t", ok)
	lg.Debugf("programCounter: %v", programCounter)
	lg.Debugf("sourceFileName: %s", sourceFileName)
	lg.Debugf("sourceFileLineNum: %d", sourceFileLineNum)
	lg.Debug("- - - - - - - - - - - - - - - - - - - - - - - - - - - - -")

	//0.1.2...と増える毎に呼び出し元を辿っていく
	//_, file, line, ok = runtime.Caller(calldepth)
	//pc, src, line, ok := runtime.Caller(0)
	//fmt.Println(pc, src, line, ok)
	//runtime.Caller(0)->582751 {GOPATH}/src/github.com/hiromaily/golibs/log/log.go 138 true

	//pc, src, line, ok = runtime.Caller(1)
	//fmt.Println(pc, src, line, ok)
	//8525 {GOPATH}/src/github.com/hiromaily/goweb/ginserver.go 20 true

	//pc, src, line, ok = runtime.Caller(2)
	//fmt.Println(pc, src, line, ok)
	//11667 {GOPATH}/src/github.com/hiromaily/goweb/ginserver.go 100 true

	//PrintStack prints to standard error the stack trace returned by runtime.Stack.
	debug.PrintStack()
}
Пример #9
0
// CheckByte is to check nil argument at []byte type
func CheckByte(val []byte) {
	//cannot use nil as type bool in argument
	lg.Debugf("CheckByte: %v", val)

	var defaultData []byte
	lg.Debugf("CheckByte2: %v", defaultData)
}
Пример #10
0
//-----------------------------------------------------------------------------
// Test
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//EXPIRE(key, seconds), TTL(key), INFO
//-----------------------------------------------------------------------------
func TestCommonUsingDo(t *testing.T) {
	//tu.SkipLog(t)

	sleepS := 2

	c := GetRedis().Conn

	c.Do("MSET", "key1", 20, "key2", 30)
	c.Do("HMSET", "key3:subkey1", "field1", 1, "field2", 2)
	c.Do("HMSET", "key3:subkey2", "field1", 99, "field2", 100)

	val, err := redis.Int(c.Do("GET", "key1"))
	if err != nil {
		t.Errorf("key1 is 10: value is %v, error is %s", val, err)
	}

	fields, err := redis.Ints(c.Do("HMGET", "key3:subkey1", "field1", "field2"))
	if err != nil {
		t.Errorf("field1 should be 1, field2 should be 1 but result is %#v, error is %s", fields, err)
	}

	//EXPIRE
	c.Do("EXPIRE", "key1", sleepS)
	c.Do("EXPIRE", "key3:subkey1", sleepS)

	//TTL
	s, err := redis.Int(c.Do("TTL", "key1"))
	if err != nil {
		t.Errorf("redis.Int(c.Do(\"TTL\", \"key1\")) error : %s", err)
	}
	lg.Debugf("TTL is %v", s)

	//sleep
	time.Sleep(time.Duration(sleepS+1) * time.Second)

	s, _ = redis.Int(c.Do("TTL", "key1"))
	lg.Debugf("TTL is %v", s)

	//It can't access
	val, err = redis.Int(c.Do("GET", "key1"))
	if err == nil {
		t.Errorf("key1 has already expired: value is %v", val)
	}

	//It can't access
	//TODO:somehow it can access. but value is 0
	fields, err = redis.Ints(c.Do("HMGET", "key3:subkey1", "field1", "field2"))
	//if err == nil {
	if err != nil || fields[0] != 0 || fields[1] != 0 {
		t.Errorf("key3:subkey1 has already expired: value is %+v", fields)
	}

	//It's OK.
	fields, err = redis.Ints(c.Do("HMGET", "key3:subkey2", "field1", "field2"))
	if err != nil {
		//if err != nil || fields[0] != 99 || fields[1] != 100 {
		t.Errorf("field1 should be 99, field2 should be 100 but result is %#v", fields)
	}
}
Пример #11
0
// CheckInterfaceWhenPointer is to check pointer argument in interface{} type
func CheckInterfaceWhenPointer(val interface{}) {
	//0xc82000e640
	lg.Debugf("CheckInterfaceWhenPointer: %v", val)
	v := reflect.ValueOf(val)
	lg.Debugf("CheckInterfaceWhenPointer v.Type(): %v", v.Type()) //*int
	lg.Debugf("CheckInterfaceWhenPointer v.Kind(): %v", v.Kind()) //ptr

}
Пример #12
0
func TestGetRedisInfo(t *testing.T) {
	host, pass, port, err := GetRedisInfo("redis://*****:*****@ec2-50-19-83-130.compute-1.amazonaws.com:20819")

	if err != nil {
		t.Errorf("GetRedisInfo error: %s", err)
	}
	lg.Debugf("host: %s", host)
	lg.Debugf("pass: %s", pass)
	lg.Debugf("port: %d", port)
}
Пример #13
0
func TestUpdateOneDataById(t *testing.T) {
	//tu.SkipLog(t)

	mg := GetMongo()
	mg.GetCol(testColUser)

	//TODO:this is must be gotten automatically
	//get top record

	//userId := "57871a3e340e7601939628e1"
	userId := savedUserID

	idQueryier := bson.ObjectIdHex(userId)

	//oids := make([]bson.ObjectId, len(ids))
	//for i := range ids {
	//	oids[i] = bson.ObjectIdHex(ids[i])
	//}
	//query := bson.M{"_id": bson.M{"$in": oids}}

	// #1. Update (only one record)
	updateData := bson.M{"$set": bson.M{"age": 14, "createdAt": time.Now()}}
	err := mg.C.UpdateId(idQueryier, updateData)
	if err != nil {
		t.Errorf("mg.C.UpdateId(idQueryier, updateData) / error:%s", err)
	}
	// check
	user := new(User)
	mg.C.Find(bson.M{"_id": bson.ObjectIdHex(userId)}).One(user)
	lg.Debugf("result user by find id: %v", *user)
	lg.Debug("- - - - - - - - - - - - - - - - - -")

	// #2. Update (nested element)
	updateData = bson.M{"$set": bson.M{"address.country": "UK", "createdAt": time.Now()}}
	err = mg.C.UpdateId(idQueryier, updateData)
	if err != nil {
		t.Errorf("mg.C.UpdateId(idQueryier, updateData) / error:%s", err)
	}
	// check
	user2 := new(User)
	mg.C.Find(bson.M{"_id": bson.ObjectIdHex(userId)}).One(user2)
	lg.Debugf("result user by find id: %v", *user2)
	lg.Debug("- - - - - - - - - - - - - - - - - -")

	// #3. Update (update by adding element on array)
	updateData = bson.M{"$push": bson.M{"works": bson.M{"occupation": "banker", "company_id": 9}}}
	err = mg.C.UpdateId(idQueryier, updateData)
	if err != nil {
		t.Errorf("mg.C.UpdateId(idQueryier, updateData) / error:%s", err)
	}
	// check
	mg.C.Find(bson.M{"_id": bson.ObjectIdHex(userId)}).One(user2)
	lg.Debugf("result user by find id: %v", *user2)
	lg.Debug("- - - - - - - - - - - - - - - - - -")
}
Пример #14
0
//-----------------------------------------------------------------------------
// Test
//-----------------------------------------------------------------------------
func TestCurrentFunc(t *testing.T) {
	//tu.SkipLog(t)
	s := CurrentFunc(1)
	if s != "TestCurrentFunc" {
		t.Errorf("result of CurrentFunc(1) is wrong: %s", s)
	}
	lg.Debugf("CurrentFunc(1) :%s", s)

	b := CurrentFuncV2()
	lg.Debugf("CurrentFunc2() :%s", b)
}
Пример #15
0
//-----------------------------------------------------------------------------
// Test
//-----------------------------------------------------------------------------
func TestGetMySQLInfo(t *testing.T) {
	host, dbname, user, pass, err := GetMySQLInfo("mysql://*****:*****@us-cdbr-iron-east-04.cleardb.net/heroku_aa95a7f43af0311?reconnect=true")

	if err != nil {
		//unexpected EOF
		t.Errorf("GetMySQLInfo error: %s", err)
	}
	lg.Debugf("host: %s", host)
	lg.Debugf("dbname: %s", dbname)
	lg.Debugf("user: %s", user)
	lg.Debugf("pass: %s", pass)
}
Пример #16
0
func TestGetMongoInfo(t *testing.T) {
	host, dbname, user, pass, port, err := GetMongoInfo("mongodb://*****:*****@ds161495.mlab.com:61495/heroku_7lbnd77m")

	if err != nil {
		//unexpected EOF
		t.Errorf("GetMongoInfo error: %s", err)
	}
	lg.Debugf("host: %s", host)
	lg.Debugf("dbname: %s", dbname)
	lg.Debugf("user: %s", user)
	lg.Debugf("pass: %s", pass)
	lg.Debugf("port: %d", port)
}
Пример #17
0
//-----------------------------------------------------------------------------
// Test
//-----------------------------------------------------------------------------
func TestSelectUser(t *testing.T) {

	type User struct {
		Id        int
		FirstName string
		LastName  string
	}

	var users []User
	GetMySQLInstance().DB.Raw("SELECT user_id, first_name, last_name FROM t_users WHERE delete_flg=?", "0").Scan(&users)

	lg.Debugf("len(users): %v", len(users))
	lg.Debugf("users[0].FirstName: %v", users[0].FirstName)
}
Пример #18
0
func TestGetAllDataByColumn(t *testing.T) {
	//tu.SkipLog(t)

	mg := GetMongo()
	mg.GetCol(testColUser)

	var users []User

	//#1 target is sinple element
	colQuerier := bson.M{"age": 25}
	err := mg.C.Find(colQuerier).All(&users)
	if err != nil {
		t.Errorf("mg.C.Find(colQuerier).All(&users) / error:%s", err)
	}
	if len(users) == 0 {
		t.Error("mg.C.Find(colQuerier).All(&users) / no data")
	}
	lg.Debugf("result users by find.all: length is %d,\n %+v", len(users), users)
	lg.Debug("- - - - - - - - - - - - - - - - - -")

	//#2 target is nested element
	users = nil
	colQuerier = bson.M{"address.zipcode": "1060047"}
	err = mg.C.Find(colQuerier).All(&users)
	if err != nil {
		t.Errorf("mg.C.Find(colQuerier).All(&users) / error:%s", err)
	}
	if len(users) == 0 {
		t.Error("mg.C.Find(colQuerier).All(&users) / no data")
	}
	lg.Debugf("result users by find.all: length is %d,\n %+v", len(users), users)
	lg.Debug("- - - - - - - - - - - - - - - - - -")

	//#3 target is nested and array element
	users = nil
	//bson.M{"categories": bson.M{"$elemMatch": bson.M{"slug": "general"}}}
	colQuerier = bson.M{"works": bson.M{"$elemMatch": bson.M{"occupation": "programmer"}}}
	err = mg.C.Find(colQuerier).All(&users)
	//err = mg.C.Find(nil).Select(colQuerier).All(&users)

	if err != nil {
		t.Errorf("mg.C.Find(colQuerier).All(&users) / error:%s", err)
		//Cannot use $elemMatch projection on a nested field
	}
	if len(users) == 0 {
		t.Error("mg.C.Find(colQuerier).All(&users) / no data")
	}
	lg.Debugf("result users by find.all: length is %d,\n %+v", len(users), users)
}
Пример #19
0
func TestGetExec(t *testing.T) {
	//tu.SkipLog(t)

	result, err := GetExec("ls", "-al")
	if err != nil {
		t.Errorf("TestExec[01] error: %s", err)
	}
	lg.Debugf("GetExec ls -al: %v", result)

	result, err = GetExec("ls", "-a -l")
	if err != nil {
		t.Errorf("TestExec[02] error: %s", err)
	}
	lg.Debugf("GetExec ls -a -l: %v", result)
}
Пример #20
0
// CheckInterfaceWhenSlice is to check slice argument in interface{} type
func CheckInterfaceWhenSlice(val interface{}) {
	//[1 2 3 4 5]
	lg.Debugf("CheckInterfaceWhenSlice: %v", val)
	v := reflect.ValueOf(val)
	lg.Debugf("CheckInterfaceWhenSlice v.Type(): %v", v.Type()) //[]int
	lg.Debugf("CheckInterfaceWhenSlice v.Kind(): %v", v.Kind()) //slice

	//invalid operation: val[0] (type interface {} does not support indexing)
	//lg.Debugf("CheckInterfaceWhenSlice: %d,%d,%d", val[0], val[1], val[2])

	//How to convert interface{} to slice...
	vv, ok := val.([]int)
	lg.Debugf("CheckInterfaceWhenSliceval.([]int): %v, %t, %d", vv, ok, vv[0])

}
Пример #21
0
func TestNats4(t *testing.T) {
	//t.SkipNow()

	// Connection
	nc, _ := nats.Connect(nats.DefaultURL)
	defer nc.Close()

	// Replies
	nc.Subscribe("help", func(m *nats.Msg) {
		nc.Publish(m.Reply, []byte("I can help!"))
	})

	wg := &sync.WaitGroup{}
	wg.Add(1)

	// Requests
	go func() {
		count := 0
		for {
			msg, err := nc.Request("help", []byte("help me"), 10*time.Millisecond)
			if err == nil {
				lg.Debugf("message is %s", msg.Data)
			}

			count++
			if count == 100 {
				wg.Done()
				break
			}
		}
	}()

	//wait
	wg.Wait()
}
Пример #22
0
//-----------------------------------------------------------------------------
// Update
//-----------------------------------------------------------------------------
func TestUpdate(t *testing.T) {
	db := GetCass()
	//UPDATE
	sql := `UPDATE t_users SET email = ? WHERE id = ? IF EXISTS`

	err := db.Session.Query(sql, "*****@*****.**", "ac9321f5-5089-11e6-ac5d-acbc32b5de29").Exec()
	if err != nil {
		//Some partition key parts are missing: id
		t.Errorf("UPDATE error: %s", err)
	}

	//check
	sql = `SELECT first_name, last_name, email FROM t_users LIMIT 1`

	var firstName string
	var lastName string
	var email string

	err = db.Session.Query(sql).Consistency(gocql.One).Scan(&firstName, &lastName, &email)
	if err != nil {
		t.Errorf("check is invalid after updated data,  error: %s", err)
	} else {
		lg.Debugf("%s, %s, %s", email, firstName, lastName)
	}

}
Пример #23
0
func createUserToken(t *testing.T, mode uint8) {
	InitEncrypted(mode)

	ti := time.Now().Add(time.Second * 2).Unix()
	token, err := CreateToken(ti, "client123", "harry", "option555")
	if err != nil {
		t.Errorf("[%d] CreateToken() error: %s", mode, err)
	}
	lg.Debugf("[%d]token: %s", mode, token)

	err = JudgeJWTWithCustomClaim(token, "client123", "harry", "option555")
	if err != nil {
		t.Errorf("[%d] 1.JudgeJWTWithClaim() error: %s", mode, err)
	}

	// set different name
	err = JudgeJWTWithCustomClaim(token, "client123", "harry", "option777")
	if err == nil {
		t.Errorf("[%d] 2.JudgeJWTWithClaim() error has to be set: %s", mode, "Option is invalid")
	}

	time.Sleep(time.Second * 3)

	err = JudgeJWTWithCustomClaim(token, "client123", "harry", "option555")
	if err == nil {
		t.Errorf("[%d] 3.JudgeJWTWithClaim() error has to be set: %s", mode, "Token is expired")
	}
}
Пример #24
0
//-----------------------------------------------------------------------------
// Test
//-----------------------------------------------------------------------------
func TestMail(t *testing.T) {

	type BodyInfo struct {
		ToName   string
		FromName string
	}

	conf := conf.GetConf().Mail

	//subject
	subject := conf.Content[0].Subject
	lg.Debugf("mail conf: %s", subject)

	//body
	path := os.Getenv("GOPATH") + conf.Content[0].Tplfile
	bodyParam := BodyInfo{ToName: "Hiroki", FromName: "Harry"}
	body, err := tpl.FilePathParser(path, bodyParam)
	if err != nil {
		t.Fatalf("FilePathParser error: %s", err)
	}

	//mails
	smtp := SMTP{Address: conf.Address, Pass: conf.Password, Server: conf.SMTP.Server, Port: conf.SMTP.Port}
	ml := &Info{ToAddress: []string{mailTo}, FromAddress: conf.Address,
		Subject: subject, Body: body, SMTP: smtp}
	ml.SendMail(conf.Timeout)
}
Пример #25
0
//-----------------------------------------------------------------------------
// function
//-----------------------------------------------------------------------------
func checkMapData(t *testing.T, b []byte, yamlFile string) {
	m := make(map[interface{}]interface{})

	//3-1. unmarshal yaml
	err := yml.Unmarshal(b, &m)
	if err != nil {
		t.Errorf("yml.Unmarshal error on map: file: %s\n error: %s, ", yamlFile, err)
	}
	lg.Debugf("After unmarshal YAML on map: %v", m)

	//3-2. marshal from map data
	d, err := yml.Marshal(&m)
	if err != nil {
		t.Errorf("yml.Marshal error on map: file: %s\n error: %s, ", yamlFile, err)
	}
	lg.Debugf("After marshal YAML on map: %v", string(d))
}
Пример #26
0
func TestInitFlag2(t *testing.T) {
	//tu.SkipLog(t)

	//./argtest FILE1 -opt1 aaa -opt2 bbb
	//fs := flag.NewFlagSet(os.Args[0], flag.ExitOnError)
	//fs.Parse(os.Args[2:])

	//go test -v flag/flag_test.go -iv 1 -sv abcde
	for i, v := range os.Args {
		lg.Debugf("os.Args[%d]: %v", i, v)
	}

	//lg.Debugf("os.Args[]: %v", os.Args)     //flag.test
	//lg.Debugf("os.Args[1]: %v", os.Args[1]) //os.Args[1]: -test.v=true
	lg.Debugf("flag.NArg(): %v", flag.NArg())
	lg.Debugf("flag.Args(): %v", flag.Args())
}
Пример #27
0
func TestEnv(t *testing.T) {
	//#1 all Environment Variables can be got
	for _, e := range os.Environ() {
		pair := strings.Split(e, "=")
		lg.Debug(pair[0], " : ", pair[1])
	}

	//#2
	os.Setenv("TEST_FLG", "1")
	flg := os.Getenv("TEST_FLG")
	lg.Debugf("TEST_FLG is %s\n", flg)

	// all Environment Variables can be removed.
	os.Clearenv()
	flg = os.Getenv("TEST_FLG")
	lg.Debugf("After Clearenv(), TEST_FLG is %s\n", flg)
}
Пример #28
0
//-----------------------------------------------------------------------------
// Test
//-----------------------------------------------------------------------------
func TestGZipString(t *testing.T) {
	//t.Skip("skipping TestEncodeStruct")
	//*
	str := `SELECT user_id, first_name, last_name FROM t_users WHERE delete_flg=1
	`
	byteData, _ := GZipString(str)

	lg.Debugf("buf x: %x", byteData) //基数16、10以上の数には小文字(a-f)を使用
	//lg.Debugf("buf %o: %o", b.Bytes()) //%oは基数8だが、ここではsliceのuint8なのでエラー / uint8の配列
	lg.Debugf("buf v: %v", byteData) //基数8 = uint8の配列
	//lg.Debugf("buf s: %s", buf.String()) //string
	lg.Debugf("buf hex.Encode string: %s", hex.EncodeToString(byteData)) //string

	//if hex.EncodeToString(byteData) != "82a249640aa44e616d65aa6861727279206461796f" {
	//	t.Errorf("TestGZipString result: %x", byteData)
	//}
}
Пример #29
0
//-----------------------------------------------------------------------------
// Check
//-----------------------------------------------------------------------------
func TestInitFlag(t *testing.T) {
	tu.SkipLog(t)

	//SetUsage(usage)
	//flag.Usage = func() {
	//	fmt.Fprint(os.Stderr, fmt.Sprintf(usage, os.Args[0]))
	//}

	//command-line
	//flag.Parse()

	lg.Debugf("flag.NArg():%v", flag.NArg())
	lg.Debugf("flag.Args():%v", flag.Args())

	//show error
	ShowUsageAndExit("something error")
}
Пример #30
0
//-----------------------------------------------------------------------------
// Test
//-----------------------------------------------------------------------------
func TestKafka(t *testing.T) {
	ch := ChReceive{
		ChWait: make(chan bool),
		ChCMsg: make(chan *sarama.ConsumerMessage),
	}

	//
	//1.Consumer(Receiver)
	c, err := CreateConsumer(host, *tu.KafkaIP)
	if err != nil {
		t.Errorf("CreateConsumer() error: %s", err)
	}

	//2.Producer(Sender)
	p, err := CreateProducer(host, *tu.KafkaIP)
	if err != nil {
		t.Errorf("CreateProducer() error: %s", err)
	}
	defer p.Close()

	//1.Consumer(Receiver)
	go Consumer(c, topicName, ch)

	lg.Debug("wait Reveiver()")
	<-ch.ChWait //After being ready.
	lg.Debug("go after Reveiver()")

	//2.Producer(Sender)
	go func() {
		for i, tt := range msgTests {
			msg := CreateMsg(topicName, tt.key, tt.value)
			err = Producer(p, msg)
			if err != nil {
				t.Errorf("[%d]Sender() error: %s", i, err)
			}
		}
	}()

	count := 0
	for {
		m := <-ch.ChCMsg
		lg.Debugf("Key: %v, Value: %v", string(m.Key), string(m.Value))

		count++
		if count == len(msgTests) {
			break
		}
	}

	//finish notification to Consumer
	ch.ChWait <- true

	<-ch.ChWait //After finish
	//time.Sleep(1 * time.Second)

	//consumer
	//c.Close()
}