func (initialState *GameState) newGameStateWithAppliedMove(applyMe *Move) (*GameState, error) { occupiedHoles := make([]Coordinate, len(initialState.occupiedHoles)) copy(occupiedHoles, initialState.occupiedHoles) occupiedHoles, err := remove(occupiedHoles, applyMe.From()) if err != nil { debug.PrintStack() return nil, errors.New("Move is not consistent with game state: 'from' hole was unoccupied.") } occupiedHoles, err = remove(occupiedHoles, applyMe.Jumped()) if err != nil { debug.PrintStack() return nil, errors.New("Move is not consistent with game state: jumped hole was unoccupied.") } if contains(occupiedHoles, *applyMe.To()) { debug.PrintStack() fmt.Println("error when applying", applyMe, "to", initialState) return nil, errors.New("Move is not consistent with game state: 'to' hole was occupied.") } if applyMe.To().Row() > initialState.rowCount || applyMe.To().Row() < 1 { errors.New(fmt.Sprintf("Move is not legal because the 'to' hole does not exist: %s", applyMe.To())) } occupiedHoles = append(occupiedHoles, *applyMe.To()) return &GameState{initialState.rowCount, occupiedHoles}, nil }
func (b *fanOutTestBuffer) Select(user string, from, to, expectedFromIndex, expectedToIndex uint64, expected ...string) { signals, fromIndex, toIndex, err := b.buffer.SelectForwards(types.Id(types.NewUserId(user, "test")), from, to) if err != nil { debug.PrintStack() b.t.Fatal("failed to get signal range: ", err) } if len(signals) != len(expected) { debug.PrintStack() b.t.Fatalf("invalid signal count, expected %d but got %d", len(expected), len(signals)) } if expectedFromIndex != fromIndex { debug.PrintStack() b.t.Fatalf("invalid from index, expected %d but got %d", expectedFromIndex, fromIndex) } if expectedToIndex != toIndex { debug.PrintStack() b.t.Fatalf("invalid to index, expected %d but got %d", expectedToIndex, toIndex) } for i, signal := range signals { if signal.EventId.Id != expected[i] { debug.PrintStack() b.t.Fatalf("invalid event id: expected %s, got %s", expected[i], signal.EventId.Id) } } }
func Write(conn net.Conn, filename string, contents string, exptime int) int64 { reader := bufio.NewReader(conn) fmt.Fprintf(conn, "write %v %v %v\r\n%v\r\n", filename, len(contents), exptime, contents) resp, ok := reader.ReadBytes('\n') debugFsnTest(fmt.Sprintf("Write got response:%v\n", string(resp))) if ok != nil { fmt.Fprintf(os.Stderr, "Error in reading from socket in Write\n") fmt.Printf("Error in reading from socket in Write\n") debug.PrintStack() os.Exit(2) } arr := strings.Fields(string(resp)) if arr[0] != "OK" { fmt.Fprintf(os.Stderr, "Expected: %v found: %v in Write 1\n", "OK", arr[0]) fmt.Printf("Expected: %v found: %v in Write 1\n", "OK", arr[0]) debug.PrintStack() os.Exit(2) } version, err := strconv.ParseInt(arr[1], 10, 64) if err != nil { fmt.Fprintf(os.Stderr, "Non-numeric version found in Write") fmt.Printf("Non-numeric version found in Write") debug.PrintStack() os.Exit(2) } return version }
func CasFailure(conn net.Conn, filename string, contents string, incorrect_version int64, correct_version int64, exptime int, errstr string) { reader := bufio.NewReader(conn) fmt.Fprintf(conn, "cas %v %v %v %v\r\n%v\r\n", filename, incorrect_version, len(contents), exptime, contents) resp, ok := reader.ReadBytes('\n') if ok != nil { fmt.Fprintf(os.Stderr, "Error in reading from socket in CasFailure\n") fmt.Printf("Error in reading from socket in CasFailure\n") debug.PrintStack() os.Exit(2) } arr := strings.Fields(string(resp)) //expect(t, arr[0], errstr) if arr[0] != errstr { fmt.Printf("Expected: %v found: %v in CasFailure\n", errstr, arr[0]) debug.PrintStack() os.Exit(2) } //expect(t, arr[1], fmt.Sprintf("%v",version)) if arr[1] != fmt.Sprintf("%v", correct_version) { fmt.Fprintf(os.Stderr, "Expected: %v found: %v in CasFailure\n", fmt.Sprintf("%v", correct_version), arr[1]) fmt.Printf("Expected: %v found: %v in CasFailure\n", fmt.Sprintf("%v", correct_version), arr[1]) debug.PrintStack() os.Exit(2) } }
func CasSuccess(conn net.Conn, filename string, contents string, version int64, exptime int) int64 { reader := bufio.NewReader(conn) fmt.Fprintf(conn, "cas %v %v %v %v\r\n%v\r\n", filename, version, len(contents), exptime, contents) resp, ok := reader.ReadBytes('\n') if ok != nil { fmt.Fprintf(os.Stderr, "Error in reading from socket in CasSuccess\n") fmt.Printf("Error in reading from socket in CasSuccess\n") debug.PrintStack() os.Exit(2) } arr := strings.Fields(string(resp)) //expect(t, arr[0], "OK") if arr[0] != "OK" { fmt.Fprintf(os.Stderr, "Expected: %v found: %v in CasSuccess\n", "OK", arr[0]) fmt.Printf("Expected: %v found: %v in CasSuccess\n", "OK", arr[0]) debug.PrintStack() os.Exit(2) } version, err := strconv.ParseInt(arr[1], 10, 64) if err != nil { fmt.Fprintf(os.Stderr, "Non-numeric version found") fmt.Printf("Non-numeric version found") debug.PrintStack() os.Exit(2) } return version }
func testFindTestSummaryInOutput(t *testing.T, isExpectToFind bool, fullOutput string, isRunSucess bool) { resStr := findTestSummaryInOutput(fullOutput, isRunSucess) if isExpectToFind && resStr == "" { t.Logf("Expected to find Test Summary in provided log.") debug.PrintStack() t.Fatalf("Provided output was: %s", fullOutput) } if !isExpectToFind && resStr != "" { t.Logf("Expected to NOT find Test Summary in provided log.") debug.PrintStack() t.Fatalf("Provided output was: %s", fullOutput) } }
func checkSortRes(t *testing.T, res [][]byte, values ...string) { if len(res) != len(values) { debug.PrintStack() t.Fatalf("invalid xsort res len, %d = %d", len(res), len(values)) } for i := 0; i < len(res); i++ { if string(res[i]) != values[i] { debug.PrintStack() t.Fatalf("invalid xsort res at %d, %s != %s", i, res[i], values[i]) } } }
func (self *Serv) RequestFlush(client *Client, channel string, version int64) (err error) { defer func(client *Client) { r := recover() if r != nil { if self.logger != nil { self.logger.Error("server", "requestFlush failed", util.Fields{"error": r.(error).Error(), "uaid": client.UAID}) debug.PrintStack() } if client != nil { self.ClientPing(client.Prop) } } return }(client) if client != nil { if self.logger != nil { self.logger.Info("server", "Requesting flush", util.Fields{"uaid": client.UAID, "channel": channel, "version": strconv.FormatInt(version, 10)}) } // Attempt to send the command client.Worker.Flush(&client.PushWS, 0, channel, version) } return nil }
// Errcheck simplifies error handling by putting all the generic // code in one place. func Errcheck(err error) { if nil != err { debug.PrintStack() fmt.Printf("Error = %v\n", err) os.Exit(1) } }
/* Forward message to MQTT server */ func ConnectToMQTTServer(MQTTServerAddress string) (*client.Client, error) { defer func() { if err := recover(); err != nil { utils.Log.Println(err) debug.PrintStack() } }() cli := client.New(&client.Options{ ErrorHandler: func(err error) { utils.Log.Println("MQTT Client error:", err) }, }) var err error RandomID := utils.MakeRandomID() err = cli.Connect(&client.ConnectOptions{ Network: "tcp", Address: MQTTServerAddress, ClientID: []byte(RandomID), CleanSession: true, PINGRESPTimeout: 5 * time.Second, KeepAlive: 5, }) if err != nil { return nil, err } return cli, nil }
/* Middleware that catches panics, and: - logs them - optionally reports them to sentry - pass in "" if you don't want this - sends a 500 response You can also use ThrowError() to raise an error that this middleware will catch, for example if you want an error to be reported to sentry */ func BuildErrorCatcher(sentryClient *raven.Client) func(h http.Handler) http.Handler { return func(h http.Handler) http.Handler { handler := func(w http.ResponseWriter, r *http.Request) { defer func() { err := recover() if err == nil { return } if sentryClient != nil { // Send the error to sentry const size = 1 << 12 buf := make([]byte, size) n := runtime.Stack(buf, false) sentryClient.CaptureMessage(fmt.Sprintf("%v\nStacktrace:\n%s", err, buf[:n]), sentryClient.Tags) } switch err := err.(type) { case HttpError: log.Printf("Return response for error %s", err.Message) err.WriteResponse(w) return default: log.Printf("Panic: %v\n", err) debug.PrintStack() http.Error(w, http.StatusText(500), 500) return } }() h.ServeHTTP(w, r) } return http.HandlerFunc(handler) } }
func checkErr(err error) { if err != nil { fmt.Fprintf(os.Stderr, "error: %s\n", err.Error()) debug.PrintStack() os.Exit(1) } }
func TestReadlocation1(t *testing.T) { defer func() { if err := recover(); err != nil { debug.PrintStack() t.Errorf("Fatal Error:%s\n", err) } }() testfile := "testfile.txt" //create testfile content := `1 O1|O1(not set)|O1(not set)|0.0000|0.0000 2 Asia/Pacific Region|Asia/Pacific Region(not set)|Asia/Pacific Region(not set)|35.0000|105.0000 3 Europe|Europe(not set)|Europe(not set)|47.0000|8.0000 4 Andorra|Andorra(not set)|Andorra(not set)|42.5000|1.5000 5 United Arab Emirates|United Arab Emirates(not set)|United Arab Emirates(not set)|24.0000|54.0000 6 Afghanistan|Afghanistan(not set)|Afghanistan(not set)|33.0000|65.0000 7 Antigua and Barbuda|Antigua and Barbuda(not set)|Antigua and Barbuda(not set)|17.0500|-61.8000 ` ostream, _ := os.Create(testfile) ostream.WriteString(content) ostream.Close() t.Log("Starting TestReadblock...") house, err := NewLocationpthouse(testfile) if err != nil { t.Errorf("Fatal Error:%s\n", err) } fmt.Printf("%+v", house) //delete testfile os.Remove(testfile) }
func TestDifference(t *testing.T) { defer func() { if err := recover(); err != nil { debug.PrintStack() t.Errorf("Fatal Error: %s\n", err) } }() t.Log("Starting TestDifference...") commonElem := genRandElement() set, _ := genRandSet(func() Set { return NewSimpleSet() }) set.Add(commonElem) t.Logf("The set value: %v", set) set2, _ := genRandSet(func() Set { return NewSimpleSet() }) set2.Add(commonElem) t.Logf("The set value (2): %v", set2) dSet := Difference(set, set2) for _, v := range dSet.Elements() { if !set.Contains(v) { t.Errorf("ERROR: The set value %v do not contains %v!", set, v) t.FailNow() } if set2.Contains(v) { t.Errorf("ERROR: The set value %v contains %v!", set2, v) t.FailNow() } } t.Logf("The set value %v is a differenced set of %v to %v", dSet, set, set2) }
func TestUnion(t *testing.T) { defer func() { if err := recover(); err != nil { debug.PrintStack() t.Errorf("Fatal Error: %s\n", err) } }() t.Log("Starting TestUnion...") set, _ := genRandSet(func() Set { return NewSimpleSet() }) t.Logf("The set value: %v", set) set2, _ := genRandSet(func() Set { return NewSimpleSet() }) uSet := Union(set, set2) t.Logf("The set value (2): %v", set2) for _, v := range set.Elements() { if !uSet.Contains(v) { t.Errorf("ERROR: The union set value %v do not contains %v!", uSet, v) t.FailNow() } } for _, v := range set2.Elements() { if !uSet.Contains(v) { t.Errorf("ERROR: The union set value %v do not contains %v!", uSet, v) t.FailNow() } } t.Logf("The set value %v is a unioned set of %v and %v", uSet, set, set2) }
func (w *Worker) doTxn(q *Query) (*Result, error) { if q.TXN >= LAST_TXN { debug.PrintStack() clog.Error("Unknown transaction number %v\n", q.TXN) } w.NStats[NTXN]++ if len(q.accessParts) > 1 { w.NStats[NCROSSTXN]++ } w.E.Reset(q) x, err := w.txns[q.TXN](q, w.E) if err == EABORT { w.NStats[NABORTS]++ return nil, err } else if err == ENOKEY { w.NStats[NENOKEY]++ return nil, err } w.NStats[NREADKEYS] += int64(len(q.rKeys)) w.NStats[NWRITEKEYS] += int64(len(q.wKeys)) return x, err //return nil, nil }
// support int and string to compare func AssertEqual(expected interface{}, actual interface{}, testName string, t *testing.T) { switch expected.(type) { case string: if actual != expected { t.Logf("%s: expect value %s, but it is %s", testName, expected, actual) debug.PrintStack() t.Fail() } case int: if actual != expected { t.Logf("%s: expect value %d, but it is %d", testName, expected, actual) debug.PrintStack() t.Fail() } } }
func TestSymmetricDifference(t *testing.T) { defer func() { if err := recover(); err != nil { debug.PrintStack() t.Errorf("Fatal Error: %s\n", err) } }() t.Log("Starting TestSymmetricDifference...") commonElem := genRandElement() set, _ := genRandSet(func() Set { return NewSimpleSet() }) set.Add(commonElem) t.Logf("The set value: %v", set) set2, _ := genRandSet(func() Set { return NewSimpleSet() }) set2.Add(commonElem) t.Logf("The set value (2): %v", set2) sdSet := SymmetricDifference(set, set2) for _, v := range sdSet.Elements() { if set.Contains(v) && set2.Contains(v) { t.Errorf("ERROR: The element %v can not be a common element of %v to %v!", v, set, set2) t.FailNow() } } t.Logf("The set value %v is a symmetric differenced set of %v to %v", sdSet, set, set2) }
// Clear the data that the client stated it received, then re-flush any // records (including new data) func (self *Worker) Ack(sock *PushWS, buffer interface{}) (err error) { defer func() { if r := recover(); r != nil { debug.PrintStack() if self.logger != nil { self.logger.Error("worker", "Unhandled error", util.Fields{"cmd": "ack", "error": r.(error).Error()}) } else { log.Printf("Unhandled error in worker %s", r) } err = sperrors.InvalidDataError } }() if sock.Uaid == "" { return sperrors.InvalidCommandError } data := buffer.(util.JsMap) if data["updates"] == nil { return sperrors.MissingDataError } err = sock.Store.Ack(sock.Uaid, data) // Get the lastAccessed time from wherever. if err == nil { return self.Flush(sock, 0, "", 0) } if self.logger != nil { self.logger.Debug("worker", "sending response", util.Fields{"cmd": "ack", "error": ErrStr(err)}) } return err }
func TestSocketServer(t *testing.T) { defer func() { if err := recover(); err != nil { debug.PrintStack() t.Errorf("Fatal Error:%s\n", err) } }() t.Log("Starting TestSocketServer...") server := NewSocketServer("0.0.0.0:12346") err := server.Listen() if err != nil { t.Log(err) } fmt.Printf("%+v\n", server) go server.Run() t.Log("Start connect SocketServer...") conn, err := net.Dial("tcp", "127.0.0.1:12346") if err != nil { t.Error(err) } conn.Write([]byte("test\n")) fmt.Println("Write Finish") result, err := ioutil.ReadAll(conn) if err != nil { t.Error(err) } fmt.Println(string(result)) time.Sleep(50) }
func check() { error := gl.GetError() if error != 0 { debug.PrintStack() panic(fmt.Sprintf("An error occurred! Code: 0x%x", error)) } }
func must_not(err error) { if err == nil { return } debug.PrintStack() log.Fatal(err.Error()) }
func expect(t *testing.T, expr Expression, expectedClause string, expectedParameters []interface{}) { clause, parameters, err := Compile(expr) if len(err) > 0 { debug.PrintStack() t.Fatal(err[0].Error()) } if clause != expectedClause { debug.PrintStack() t.Fatalf("clause should be %s but is %s", expectedClause, clause) } if !reflect.DeepEqual(expectedParameters, parameters) { debug.PrintStack() t.Fatalf("parameters should be %v but is %v", expectedParameters, parameters) } }
func PostDeviceLKS(sr SessionReader, deviceID keybase1.DeviceID, deviceType string, serverHalf []byte, ppGen PassphraseGeneration, clientHalfRecovery string, clientHalfRecoveryKID keybase1.KID) error { if len(serverHalf) == 0 { return fmt.Errorf("PostDeviceLKS: called with empty serverHalf") } if ppGen < 1 { G.Log.Warning("PostDeviceLKS: ppGen < 1 (%d)", ppGen) debug.PrintStack() } arg := APIArg{ Endpoint: "device/update", NeedSession: true, Args: HTTPArgs{ "device_id": S{Val: deviceID.String()}, "type": S{Val: deviceType}, "lks_server_half": S{Val: hex.EncodeToString(serverHalf)}, "ppgen": I{Val: int(ppGen)}, "lks_client_half": S{Val: clientHalfRecovery}, "kid": S{Val: clientHalfRecoveryKID.String()}, }, SessionR: sr, } _, err := G.API.Post(arg) return err }
func assert(b bool) { if !b { fmt.Println("Assertion error!") debug.PrintStack() os.Exit(-1) } }
func recoverer(c *web.C, h http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { id := middleware.GetReqID(*c) // Raven recoverer defer func() { var packet *raven.Packet switch rval := recover().(type) { case nil: return case error: packet = raven.NewPacket(rval.Error(), raven.NewHttp(r), raven.NewException(rval, raven.NewStacktrace(2, 3, nil))) default: str := fmt.Sprintf("%+v", rval) packet = raven.NewPacket(str, raven.NewHttp(r), raven.NewException(errors.New(str), raven.NewStacktrace(2, 3, nil))) } debug.PrintStack() http.Error(w, http.StatusText(500), 500) env.Raven.Capture(packet, map[string]string{ "request_id": id, }) }() h.ServeHTTP(w, r) }) }
func mustExecute(s Session, sql string) { _, err := s.Execute(sql) if err != nil { debug.PrintStack() log.Fatal(err) } }
// Equals compares two values for equality (DeepEquals). // If they are not equal, an error message is printed // and the function panics. Use only in test scenarios. func Equals(t *testing.T, exp, act interface{}) { if !reflect.DeepEqual(exp, act) { _, file, line, _ := runtime.Caller(1) debug.PrintStack() t.Fatalf("%s:%d\n\n\texp: %+v\n\n\tgot: %+v\n\n", filepath.Base(file), line, exp, act) } }
func Recovery(client *raven.Client, onlyCrashes bool) gin.HandlerFunc { return func(c *gin.Context) { defer func() { flags := map[string]string{ "endpoint": c.Request.RequestURI, } if rval := recover(); rval != nil { debug.PrintStack() rvalStr := fmt.Sprint(rval) packet := raven.NewPacket(rvalStr, raven.NewException(errors.New(rvalStr), raven.NewStacktrace(2, 3, nil))) client.Capture(packet, map[string]string{ "endpoint": c.Request.RequestURI, }) c.AbortWithStatus(http.StatusInternalServerError) } if !onlyCrashes { for _, item := range c.Errors { packet := raven.NewPacket(item.Error(), &raven.Message{ Message: item.Error(), Params: []interface{}{item.Meta}, }) client.Capture(packet, flags) } } }() c.Next() } }
func (ex *defaultExecuter) completeTask(id string, task func(string) error, onFailure func(string, string)) { defer func() { if r := recover(); r != nil { log.WithField("task", id). Errorln("Task failed", r) debug.PrintStack() go onFailure(id, "The error message is below. Please check logs for more details."+"\n\n"+"panic occurred") ex.cMap.setStatus(id, FAILURE) } }() // Run the task. if err := task(id); err != nil { log.WithFields(log.Fields{ "task": id, "error": errors.ErrorStack(err), }).Error("Task failed") go onFailure(id, "The error message is below. Please check logs for more details."+"\n\n"+errors.ErrorStack(err)) ex.cMap.setStatus(id, FAILURE) return } log.WithField("task", id). Info("Task succeeded") ex.cMap.setStatus(id, SUCCESS) }