Exemple #1
0
// InitializeTest is to run common initial code for test
func InitializeTest(prefix string) {
	flag.Parse()

	//log
	lg.InitializeLog(uint8(*LogFlg), lg.LogOff, 0, prefix, "/var/log/go/test.log")

	//-v : to show Logs.(-test.v=true)
	if o.FindParam("-test.v") {
		lg.Debug("This test can show log in detail.")
	}

	//crypt
	enc.NewCryptDefault()

	//conf
	if *ConfFile == "" {
		*ConfFile = os.Getenv("GOPATH") + "/src/github.com/hiromaily/golibs/config/settings.toml"
	}
	conf.New(*ConfFile, true)

	//json
	if *JSONFile == "" {
		//default
		*JSONFile = os.Getenv("GOPATH") + "/src/github.com/hiromaily/golibs/testdata/json/teachers.json"
	}

	//bench
	if o.FindParam("-test.bench") {
		lg.Debug("This is bench test.")
		BenchFlg = true
	}
}
Exemple #2
0
func TestCheckInterfaceByIf(t *testing.T) {
	val1 := 10
	lg.Debug(CheckInterface(val1))

	val2 := "aaaaa"
	lg.Debug(CheckInterface(val2))
}
Exemple #3
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()
}
Exemple #4
0
//-----------------------------------------------------------------------------
// Test
//-----------------------------------------------------------------------------
func TestCheckInterface(t *testing.T) {
	val1 := 10
	lg.Debug(CheckInterface(val1))

	val2 := "aaaaa"
	lg.Debug(CheckInterface(val2))

	//if err != nil {
	//}
}
Exemple #5
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("- - - - - - - - - - - - - - - - - -")
}
Exemple #6
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)
}
// 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
}
Exemple #8
0
// Save is to save data to text
func (t Text) Save(newData string) bool {
	lg.Debug("Using TxtFile")

	//open saved log
	fp, err := os.OpenFile(t.filePath, os.O_CREATE, 0664)
	defer fp.Close()

	if err == nil {

		scanner := bufio.NewScanner(fp)
		scanner.Scan()
		filedata := scanner.Text()

		if newData == filedata {
			return false
		}
	} else {
		panic(err.Error())
	}

	//save latest info
	content := []byte(newData)
	ioutil.WriteFile(t.filePath, content, 0664)
	return true
}
Exemple #9
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()
}
Exemple #10
0
func TestGetValueAsString(t *testing.T) {
	tu.SkipLog(t)

	lg.Debug(GetValueAsString(dInt))
	lg.Debug(GetValueAsString(dInt64))
	lg.Debug(GetValueAsString(dStr))
	lg.Debug(GetValueAsString(dBool))
	lg.Debug(GetValueAsString(dSlice))
	lg.Debug(GetValueAsString(dTime))
	lg.Debug(GetValueAsString(dMap))
	lg.Debug(GetValueAsString([]time.Duration{dTime}))
	lg.Debug(GetValueAsString(siteInfo))
}
Exemple #11
0
func TestGetTranslationsWithStringArgument(t *testing.T) {
	t.Skip("TestGetTranslationsWithStringArgument")
	for _, lang := range Languages {
		text := T("message2", "Mark").String(lang)
		lg.Debug(lang, text)
		if strings.Index(text, "<no value>") != -1 {
			t.Errorf("arguments was not replaced: %s", text)
		}
	}
}
Exemple #12
0
//-----------------------------------------------------------------------------
// Test
//-----------------------------------------------------------------------------
func TestFilePathParser(t *testing.T) {
	siteInfo := getTeathers()

	path := os.Getenv("GOPATH") + "/src/github.com/hiromaily/golibs/tmpl/file/sample1.tmpl"
	result, err := FilePathParser(path, siteInfo)
	if err != nil {
		t.Fatalf("[01]FilePathParser() error: %s", err)
	}
	lg.Debug(result)
}
Exemple #13
0
func TestNats3(t *testing.T) {
	t.SkipNow()

	var msg *nats.Msg
	//msg := &nats.Msg{}

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

	// Channel Subscriber
	ch := make(chan *nats.Msg, 64)
	sub, err := nc.ChanSubscribe(subjectName3, ch)
	if err != nil {
		t.Errorf("ChanSubscribe() error: %s", err)
	}

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

	// Publisher
	go func() {
		count := 0
		for {
			nc.Publish(subjectName3, []byte("Hello World"))
			count++
			if count == 100 {
				lg.Debug("finished publish")
				break
			}
		}
	}()

	// Subscriber
	go func() {
		count := 0
		for {
			//invalid operation: msg <- ch (send to non-chan type *"github.com/nats-io/nats".Msg)
			msg = <-ch
			lg.Debugf("message is %s", msg.Data)

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

	//wait
	wg.Wait()

	// Unsubscribe
	sub.Unsubscribe()
}
Exemple #14
0
func TestGetTranslationsWithStringArgumentWithMap(t *testing.T) {
	//t.Skip("TestGetTranslationsWithStringArgumentWithMap")
	mapData := map[string]interface{}{"Name": "Mark"}
	for _, lang := range Languages {
		text := T("message2", mapData).String(lang)
		lg.Debug(lang, text)
		if strings.Index(text, "<no value>") != -1 {
			t.Errorf("arguments was not replaced: %s", text)
		}
	}
}
Exemple #15
0
// handling command line
func handleCmdline() {
	flag.Usage = func() {
		fmt.Fprint(os.Stderr, fmt.Sprintf(usage, runtime.NumCPU()))
	}

	flag.Parse()

	//log.Debug("flag.NArg(): " + strconv.Itoa(flag.NArg()))
	lg.Debug("flag.NArg(): ", flag.NArg())
	lg.Debug("mode: ", *mode)
	lg.Debug("toml: ", *toml)
	lg.Debug("n: ", *n)
	lg.Debug("msg: ", *msg)
	lg.Debug("loc: ", *loc)
	lg.Debug("ot: ", *ot)
	lg.Debug("ct: ", *ct)
	lg.Debug("debug: ", *debug)
}
Exemple #16
0
// get tag name
func checkStruct(data *LoginRequest) {

	val := reflect.ValueOf(data).Elem()

	for i := 0; i < val.NumField(); i++ {
		valueField := val.Field(i)
		typeField := val.Type().Field(i)
		tag := typeField.Tag

		lg.Debugf("Field Name: %s,\t Field Value: %v,\t Tag Value: %s",
			typeField.Name, valueField.Interface(), tag.Get("valid"))
	}
	lg.Debug("-------------------------------------")
}
Exemple #17
0
func TestFileTemplate(t *testing.T) {
	siteInfo := getTeathers()

	goPath := os.Getenv("GOPATH")
	tpl, err := tt.ParseFiles(goPath + "/src/github.com/hiromaily/golibs/tmpl/file/sample1.tmpl")
	if err != nil {
		t.Fatalf("[01] template.ParseFiles() error: %s", err)
	}

	result, err := FileTempParser(tpl, siteInfo)
	if err != nil {
		t.Fatalf("[02] FileTempParser() error: %s", err)
	}
	lg.Debug(result)
}
Exemple #18
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)
}
Exemple #19
0
// Save is to save data on Redis
func (rd *StoreRedis) Save(newData string) bool {
	lg.Debug("Using Redis")

	//close
	//defer rd.RD.Close()

	c := rd.RD.Conn
	val, err := redis.String(c.Do("GET", redisKey))

	if err != nil {
		lg.Errorf("redis error is %s\n", err)
	}
	lg.Debugf("new value is %s, old value is %s\n", newData, val)

	if err != nil || newData != val {
		//save
		c.Do("SET", redisKey, newData)
		return true
	}
	return false
}
Exemple #20
0
//-----------------------------------------------------------------------------
// Test
//-----------------------------------------------------------------------------
func TestYAMLTable(t *testing.T) {
	var data []byte
	var err error

	for i, tt := range yamlTests {
		fmt.Printf("[%d] file:%s\n", i+1, tt.yamlFile)
		//data = nil

		//1. load YAML
		data, err = LoadYAMLFile(tt.yamlFile)
		if err != nil {
			t.Errorf("LoadYAMLFile error: file: %s\n error: %s, ", tt.yamlFile, err)
			continue
		}

		//2. using struct data
		//2-1. unmarshal yaml
		//TODO: assert interface to specific type
		if val, ok := tt.typeValue.(T1); ok {
			//TODO: this code is ugly.
			err := yml.Unmarshal(data, &val)
			//checkErrorForUnmarshalStruct(err, tt.yamlFile)
			if err != nil {
				t.Errorf("yml.Unmarshal error on struct: file: %s\n error: %s, ", tt.yamlFile, err)
				continue
			}
			lg.Debugf("After unmarshal YAML on struct: %v", val)

			//2-2. marchal from data
			d, err := yml.Marshal(&val)
			if err != nil {
				t.Errorf("yml.Marshal error on struct: file: %s\n error: %s, ", tt.yamlFile, err)
				continue
			}
			lg.Debugf("After marshal YAML on struct: %v", string(d))
		} else if val, ok := tt.typeValue.(T2); ok {
			err := yml.Unmarshal(data, &val)
			//checkErrorForUnmarshalStruct(err, tt.yamlFile)
			if err != nil {
				t.Errorf("yml.Unmarshal error on struct: file: %s\n error: %s, ", tt.yamlFile, err)
				continue
			}
			lg.Debugf("After unmarshal YAML on struct: %v", val)

			//2-2. marchal from data
			d, err := yml.Marshal(&val)
			if err != nil {
				t.Errorf("yml.Marshal error on struct: file: %s\n error: %s, ", tt.yamlFile, err)
				continue
			}
			lg.Debugf("After marshal YAML on struct: %v", string(d))
		} else if val, ok := tt.typeValue.(T3); ok {
			err := yml.Unmarshal(data, &val)
			//checkErrorForUnmarshalStruct(err, tt.yamlFile)
			if err != nil {
				t.Errorf("yml.Unmarshal error on struct: file: %s\n error: %s, ", tt.yamlFile, err)
				continue
			}
			lg.Debugf("After unmarshal YAML on struct: %v", val)

			//2-2. marchal from data
			d, err := yml.Marshal(&val)
			if err != nil {
				t.Errorf("yml.Marshal error on struct: file: %s\n error: %s, ", tt.yamlFile, err)
				continue
			}
			lg.Debugf("After marshal YAML on struct: %v", string(d))
		} else if val, ok := tt.typeValue.(T4); ok {
			err := yml.Unmarshal(data, &val)
			//checkErrorForUnmarshalStruct(err, tt.yamlFile)
			if err != nil {
				t.Errorf("yml.Unmarshal error on struct: file: %s\n error: %s, ", tt.yamlFile, err)
				continue
			}
			lg.Debugf("After unmarshal YAML on struct: %v", val)

			//2-2. marchal from data
			d, err := yml.Marshal(&val)
			if err != nil {
				t.Errorf("yml.Marshal error on struct: file: %s\n error: %s, ", tt.yamlFile, err)
				continue
			}
			lg.Debugf("After marshal YAML on struct: %v", string(d))
		} else if val, ok := tt.typeValue.(EventB); ok {
			err := yml.Unmarshal(data, &val)
			//checkErrorForUnmarshalStruct(err, tt.yamlFile)
			if err != nil {
				t.Errorf("yml.Unmarshal error on struct: file: %s\n error: %s, ", tt.yamlFile, err)
				continue
			}
			lg.Debugf("After unmarshal YAML on struct: %v", val)

			//2-2. marchal from data
			d, err := yml.Marshal(&val)
			if err != nil {
				t.Errorf("yml.Marshal error on struct: file: %s\n error: %s, ", tt.yamlFile, err)
				continue
			}
			lg.Debugf("After marshal YAML on struct: %v", string(d))
		} else {
			lg.Debug("Assert can not be.")
		}

		//3. as map interface
		checkMapData(t, data, tt.yamlFile)
	}
}