func TestSlot_list(t *testing.T) { _, client := mockServerClient(t) layout := "2006-01-02" prev, err := time.Parse(layout, "2015-12-14") if err != nil { t.Fatal(err) } to, _ := time.Parse(layout, "2015-12-15") _ = prev params := SlotParams{ From: prev, To: to, SelectedResources: []int{}, } slots, err := client.ServiceSlot(427, params) if err != nil { t.Error(err) } if e := 4; len(slots) != e { t.Fatalf("wrong number of slots returned got: %d wanted: %d", len(slots), e) } }
func (ctl *controller) getActivity(c web.C, w http.ResponseWriter, r *http.Request) { teamID, _ := c.Env["team_id"].(string) p := api.ActivityQueryParams{ AppID: r.URL.Query().Get("app"), GroupID: r.URL.Query().Get("group"), ChannelID: r.URL.Query().Get("channel"), InstanceID: r.URL.Query().Get("instance"), Version: r.URL.Query().Get("version"), } p.Severity, _ = strconv.Atoi(r.URL.Query().Get("severity")) p.Start, _ = time.Parse(time.RFC3339, r.URL.Query().Get("start")) p.End, _ = time.Parse(time.RFC3339, r.URL.Query().Get("end")) p.Page, _ = strconv.ParseUint(r.URL.Query().Get("page"), 10, 64) p.PerPage, _ = strconv.ParseUint(r.URL.Query().Get("perpage"), 10, 64) activityEntriesJSON, err := ctl.api.GetActivityJSON(teamID, p) switch err { case nil: w.Write(activityEntriesJSON) case sql.ErrNoRows: w.Write([]byte(`[]`)) default: logger.Error("getActivity", "error", err, "teamID", teamID, "p", p) http.Error(w, http.StatusText(400), 400) } }
func parseDateTime(str string, loc *time.Location) (t time.Time, err error) { switch len(str) { case 10: // YYYY-MM-DD if str == "0000-00-00" { return } t, err = time.Parse(timeFormat[:10], str) case 19: // YYYY-MM-DD HH:MM:SS if str == "0000-00-00 00:00:00" { return } t, err = time.Parse(timeFormat, str) default: err = fmt.Errorf("Invalid Time-String: %s", str) return } // Adjust location if err == nil && loc != time.UTC { y, mo, d := t.Date() h, mi, s := t.Clock() t, err = time.Date(y, mo, d, h, mi, s, t.Nanosecond(), loc), nil } return }
func checkstatus(p *os.Process, pname string, timest string) bool { fmt.Println("checkstatus", pname, p) reportlog[timest]["status"] = pname + " running" reportlog[timest][pname+"start"] = time.Now().Format("20060102150405") liner, _ := json.Marshal(reportlog) ioutil.WriteFile("static/data/reportlog.json", liner, 0) pw, _ := p.Wait() fmt.Println("checkstatus over", p) fmt.Println("timest=", timest) reportlog[timest][pname+"stop"] = time.Now().Format("20060102150405") t1, _ := time.Parse("20060102150405", reportlog[timest][pname+"stop"]) t2, _ := time.Parse("20060102150405", reportlog[timest][pname+"start"]) reportlog[timest][pname+"time"] = strconv.Itoa(int(t1.Sub(t2)) / 1e9) fmt.Println("t1=", t1) fmt.Println("t2=", t2) fmt.Println("cost=", t1.Sub(t2)) status := pw.Success() if status == true { reportlog[timest]["status"] = pname + " success" fmt.Println("checkstatus over success ", pname, p) } else { reportlog[timest]["status"] = pname + " failed" fmt.Println("checkstatus over failed ", pname, p) } liner, _ = json.Marshal(reportlog) ioutil.WriteFile("static/data/reportlog.json", liner, 0) return status }
func (s *DockerSuite) TestLogsSinceFutureFollow(c *check.C) { // TODO Windows TP5 - Figure out why this test is so flakey. Disabled for now. testRequires(c, DaemonIsLinux) name := "testlogssincefuturefollow" out, _ := dockerCmd(c, "run", "-d", "--name", name, "busybox", "/bin/sh", "-c", `for i in $(seq 1 5); do echo log$i; sleep 1; done`) // Extract one timestamp from the log file to give us a starting point for // our `--since` argument. Because the log producer runs in the background, // we need to check repeatedly for some output to be produced. var timestamp string for i := 0; i != 100 && timestamp == ""; i++ { if out, _ = dockerCmd(c, "logs", "-t", name); out == "" { time.Sleep(time.Millisecond * 100) // Retry } else { timestamp = strings.Split(strings.Split(out, "\n")[0], " ")[0] } } c.Assert(timestamp, checker.Not(checker.Equals), "") t, err := time.Parse(time.RFC3339Nano, timestamp) c.Assert(err, check.IsNil) since := t.Unix() + 2 out, _ = dockerCmd(c, "logs", "-t", "-f", fmt.Sprintf("--since=%v", since), name) c.Assert(out, checker.Not(checker.HasLen), 0, check.Commentf("cannot read from empty log")) lines := strings.Split(strings.TrimSpace(out), "\n") for _, v := range lines { ts, err := time.Parse(time.RFC3339Nano, strings.Split(v, " ")[0]) c.Assert(err, checker.IsNil, check.Commentf("cannot parse timestamp output from log: '%v'", v)) c.Assert(ts.Unix() >= since, checker.Equals, true, check.Commentf("earlier log found. since=%v logdate=%v", since, ts)) } }
func decodeTime(r io.Reader, f reflect.Value) error { s, err := decodeStr(r) if err != nil { return err } var t time.Time if s != "" { // Samsung has trailing dots. s = strings.TrimRight(s, ".") // Jolla Sailfish has trailing "Z". s = strings.TrimRight(s, "Z") t, err = time.Parse(timeFormat, s) if err != nil { // Nokia lumia has numTZ t, err = time.Parse(timeFormatNumTZ, s) if err != nil { return err } } } f.Set(reflect.ValueOf(t)) return nil }
func NewAppointment(name string, day time.Weekday, start string, end string, participants []int) (*Appointment, error) { start_time, err := time.Parse(time.Kitchen, start) if err != nil { return nil, errors.New(start + " is not a valid start time. Format times like \"XX:YYPM\".") } end_time, err := time.Parse(time.Kitchen, end) if err != nil { return nil, errors.New(end + " is not a valid end time. Format times like \"XX:YYPM\".") } if !isValidTime(&start_time) || !isValidTime(&end_time) { return nil, errors.New("Appointment times must start and end at XY:00 or XY:30.") } if end_time.Sub(start_time) <= 0 { return nil, errors.New("Appointment must end after it starts.") } var parts [n]bool for _, i := range participants { if i < 1 || i > n { return nil, fmt.Errorf("%d is not a valid user ID.", i) } parts[i-1] = true } a := Appointment{name, day, start_time, end_time, parts} return &a, nil }
func (t *TimePeriod) SetBSON(raw bson.Raw) error { var str string err := raw.Unmarshal(&str) if err == nil { str = strings.Replace(str, "\"", "", -1) split := strings.Split(str, "/") if len(split) == 2 { t.FromTime, err = time.Parse(STD_TIME_FORMAT_PERIOD, split[0]) if err != nil { return err } t.ToTime, err = time.Parse(STD_TIME_FORMAT_PERIOD, split[1]) if err != nil { return err } } else { t.FromTime, err = time.Parse(STD_TIME_FORMAT_INSTANT, split[0]) if err != nil { return err } } } return err }
func rangeIntoDays(start, end string) ([]timeBlock, error) { sT, err := time.Parse("20060102", start) if err != nil { return nil, err } eT, err := time.Parse("20060102", end) if err != nil { return nil, err } days := int(eT.Sub(sT).Hours())/24 + 1 dates := make([]timeBlock, days) for i := 0; i < days; i++ { durString := fmt.Sprintf("%dh", 24*i) d, err := time.ParseDuration(durString) if err != nil { return nil, err } dayBegin := sT.Add(d) dayEnd := dayBegin.Add(time.Duration(86399000000000)) dates[i] = timeBlock{dayBegin, dayEnd} } return dates, nil }
func parseTxtInvoice(version, lino int, line string) (invoice *Invoice, err error) { invoice = &Invoice{} var raised, due string if version == fileVersion { if _, err = fmt.Sscanf(line, "INVOICE ID=%d CUSTOMER=%d "+ "DEPARTMENT=%s RAISED=%s DUE=%s PAID=%t", &invoice.Id, &invoice.CustomerId, &invoice.DepartmentId, &raised, &due, &invoice.Paid); err != nil { return nil, fmt.Errorf("invalid invoice %v line %d", err, lino) } } else { if _, err = fmt.Sscanf(line, "INVOICE ID=%d CUSTOMER=%d "+ "RAISED=%s DUE=%s PAID=%t", &invoice.Id, &invoice.CustomerId, &raised, &due, &invoice.Paid); err != nil { return nil, fmt.Errorf("invalid invoice %v line %d", err, lino) } } if invoice.Raised, err = time.Parse(dateFormat, raised); err != nil { return nil, fmt.Errorf("invalid raised %v line %d", err, lino) } if invoice.Due, err = time.Parse(dateFormat, due); err != nil { return nil, fmt.Errorf("invalid due %v line %d", err, lino) } if i := strings.Index(line, noteSep); i > -1 { invoice.Note = strings.TrimSpace(line[i+len(noteSep):]) } if version < fileVersion { updateInvoice(invoice) } return invoice, nil }
func (s *Summary) UnmarshalJSON(b []byte) error { e := new(encodedSummary) if err := json.Unmarshal(b, e); err != nil { return err } s.Port = e.Port s.Success = e.Success s.Failure = e.Failure s.Total = e.Total var err error if s.StartTime, err = time.Parse(time.RFC3339, e.StartTime); err != nil { return err } if s.EndTime, err = time.Parse(time.RFC3339, e.EndTime); err != nil { return err } s.Duration = s.EndTime.Sub(s.StartTime) s.Senders = e.Senders s.Timeout = time.Duration(e.Timeout) * time.Second if e.TLSVersion != nil { s.TLSVersion = *e.TLSVersion } if e.MailType != nil { s.MailType = *e.MailType } if e.CAFile != nil { s.CAFile = *e.CAFile } return nil }
func getFeeds(feedSetting FeedSetting) { resp, err := http.Get(feedSetting.URL) //there's no reason to panic on this if err != nil { fmt.Printf("Couldn't reach URL: %v \n\n", feedSetting.URL) return } var results Result decoder := xml.NewDecoder(resp.Body) decoder.CharsetReader = charset.NewReaderLabel err = decoder.Decode(&results) checkError(err) //xml.Unmarshal([]byte(tempStr), &results) session, _ := mgo.Dial("localhost") feeds := session.DB("wcproc").C("feeds") feed := Feed{} feeds.Find(bson.M{"category": feedSetting.Name}).Sort("-date").One(&feed) //convert the feed.date string to time.Time since unmarshal wont do it for me for iter, element := range results.ItemList { lastThree := element.PubDate[len(element.PubDate)-3:] results.ItemList[iter].Link = strings.Trim(element.Link, " ") if _, err := strconv.Atoi(lastThree); err == nil { results.ItemList[iter].Date, err = time.Parse(time.RFC1123Z, element.PubDate) checkError(err) } else { results.ItemList[iter].Date, err = time.Parse(time.RFC1123, element.PubDate) checkError(err) } } //check to see if any articles exist past the last article date in db for iter, element := range results.ItemList { if element.Date.After(feed.Date.Local()) { //check title name against db for duplicates, some news feeds like to change the pubdate over the length of 6 hours matchup := Feed{} feeds.Find(bson.M{"title": element.Title, "category": feedSetting.Name}).One(&matchup) if matchup.Category == "" { fmt.Printf("adding: %v -- %v \n", element.Date, element.Title) results.ItemList[iter].ArticleId = feedSetting.ArticleId results.ItemList[iter].Category = feedSetting.Name _ = feeds.Insert(results.ItemList[iter]) } } } session.Close() }
func machineFromMongodb(db *mongodb.MongoDB) (*machines, error) { from, err := time.Parse(time.RFC3339, "2015-03-07T13:15:00Z") if err != nil { return nil, err } to, err := time.Parse(time.RFC3339, "2015-04-10T07:30:00Z") if err != nil { return nil, err } machines := newMachines() err = db.Run("jMachines", func(c *mgo.Collection) error { var m koding.Machine iter := c.Find( bson.M{ "createdAt": bson.M{ "$gte": from.UTC(), "$lt": to.UTC(), }, // "status.state": machinestate.Stopped.String(), }, ).Iter() for iter.Next(&m) { machines.docs = append(machines.docs, m) } return iter.Close() }) return machines, err }
func (s *S) TestListHealingHistoryCmdRun(c *check.C) { var buf bytes.Buffer context := cmd.Context{Stdout: &buf} trans := &cmdtest.ConditionalTransport{ Transport: cmdtest.Transport{Message: healingJsonData, Status: http.StatusOK}, CondFunc: func(req *http.Request) bool { return req.URL.Path == "/docker/healing" }, } manager := cmd.Manager{} client := cmd.NewClient(&http.Client{Transport: trans}, nil, &manager) healing := &ListHealingHistoryCmd{} err := healing.Run(&context, client) c.Assert(err, check.IsNil) startT, _ := time.Parse(time.RFC3339, "2014-10-23T08:00:00.000Z") endT, _ := time.Parse(time.RFC3339, "2014-10-23T08:30:00.000Z") startTStr := startT.Local().Format(time.Stamp) endTStr := endT.Local().Format(time.Stamp) expected := fmt.Sprintf(`Node: +-----------------+-----------------+---------+---------+---------+-------+ | Start | Finish | Success | Failing | Created | Error | +-----------------+-----------------+---------+---------+---------+-------+ | %s | %s | true | addr1 | addr2 | | +-----------------+-----------------+---------+---------+---------+-------+ Container: +-----------------+-----------------+---------+------------+------------+-------+ | Start | Finish | Success | Failing | Created | Error | +-----------------+-----------------+---------+------------+------------+-------+ | %s | %s | false | 1234567890 | | err1 | +-----------------+-----------------+---------+------------+------------+-------+ | %s | %s | true | 1234567890 | 9234567890 | | +-----------------+-----------------+---------+------------+------------+-------+ `, startTStr, endTStr, startTStr, endTStr, startTStr, endTStr) c.Assert(buf.String(), check.Equals, expected) }
// Extract will retrieve a Config resource from an operation result. func (r commonResult) Extract() (*Config, error) { if r.Err != nil { return nil, r.Err } var response struct { Config Config `mapstructure:"configuration"` } err := mapstructure.Decode(r.Body, &response) val := r.Body.(map[string]interface{})["configuration"].(map[string]interface{}) if t, ok := val["created"].(string); ok && t != "" { creationTime, err := time.Parse(time.RFC3339, t) if err != nil { return &response.Config, err } response.Config.Created = creationTime } if t, ok := val["updated"].(string); ok && t != "" { updatedTime, err := time.Parse(time.RFC3339, t) if err != nil { return &response.Config, err } response.Config.Updated = updatedTime } return &response.Config, err }
// Status sorts by taking the CreationDate attribute, converting it to UNIX // epoch, and adds it to the weighted value of the status tag. It sorts from // newest to oldest AMIs. func Status(a1, a2 *AMI) bool { var dateFmt = "2006-01-02T15:04:05.000Z" var icdate, istatus uint64 var jcdate, jstatus uint64 // Parse the CreationDate attribute if a1.Image.CreationDate != nil { if date, err := time.Parse(dateFmt, *a1.Image.CreationDate); err == nil { icdate = uint64(date.Unix()) } } if a2.Image.CreationDate != nil { if date, err := time.Parse(dateFmt, *a2.Image.CreationDate); err == nil { jcdate = uint64(date.Unix()) } } // Get the status tag if status := a1.Tag("status"); status != "" { istatus, _ = statusWeight[strings.ToLower(status)] } if status := a2.Tag("status"); status != "" { jstatus, _ = statusWeight[strings.ToLower(status)] } return icdate+istatus > jcdate+jstatus }
func shouldUpdate(resp *http.Response, fi os.FileInfo, newer, newermetamtime bool) bool { var stale bool = false filemtime := fi.ModTime() if newermetamtime { parsed, err := time.Parse(time.RFC1123, resp.Header.Get("x-amz-meta-last-modified")) if err != nil { // can't see metamtime upload anyhow stale = true fmt.Fprint(os.Stderr, "Can't read metamtime, setting stale to upload again\n") } if parsed.Before(filemtime) { stale = true } } if newer { parsed, err := time.Parse(time.RFC1123, resp.Header.Get("Last-Modified")) if err != nil { // can't see metamtime upload anyhow stale = true fmt.Fprint(os.Stderr, "Can't read metamtime, setting stale to upload again\n") } if parsed.Before(filemtime) { stale = true } } return stale }
func cliInit(c *cli.Context) (dates map[string]time.Time) { var err error dates = make(map[string]time.Time) if len(c.String("from")) > 0 { dates["fromDate"], err = time.Parse("2006-01-02", c.String("from")) if err != nil { fmt.Printf("%v", err) os.Exit(1) } } else { dates["fromDate"] = time.Date(time.Now().Year(), 1, 1, 0, 0, 0, 0, time.UTC) } if len(c.String("to")) > 0 { dates["toDate"], err = time.Parse(isoDateFmt, c.String("to")) if err != nil { fmt.Printf("%v", err) os.Exit(1) } } else { dates["toDate"] = time.Date(time.Now().Year(), 12, 31, 0, 0, 0, 0, time.UTC) } return dates }
func getEventRequest(o *eventReqOpts) (*Request, bool, error) { ereq := NewRequest(o) stream := false ereq.EventType[o.etype] = true if o.maxEvents > 0 { ereq.maxEventsReturned = o.maxEvents } if len(o.startTime) > 0 { newTime, err := time.Parse(time.RFC3339, o.startTime) if err == nil { ereq.StartTime = newTime } } if len(o.endTime) > 0 { newTime, err := time.Parse(time.RFC3339, o.endTime) if err == nil { ereq.EndTime = newTime } } return ereq, stream, nil }
// setMetaData sets the fs data from a storage.Object func (o *FsObjectStorage) setMetaData(info *storage.Object) { o.url = info.MediaLink o.bytes = int64(info.Size) // Read md5sum md5sumData, err := base64.StdEncoding.DecodeString(info.Md5Hash) if err != nil { fs.Log(o, "Bad MD5 decode: %v", err) } else { o.md5sum = hex.EncodeToString(md5sumData) } // read mtime out of metadata if available mtimeString, ok := info.Metadata[metaMtime] if ok { modTime, err := time.Parse(timeFormatIn, mtimeString) if err == nil { o.modTime = modTime return } else { fs.Debug(o, "Failed to read mtime from metadata: %s", err) } } // Fallback to the Updated time modTime, err := time.Parse(timeFormatIn, info.Updated) if err != nil { fs.Log(o, "Bad time decode: %v", err) } else { o.modTime = modTime } }
/* requestTime method will parse the time from the request "x-amz-date" or "date" headers. If the "x-amz-date" header is present, that will take priority over the "date" header. If neither header is defined or we are unable to parse either header as a valid date then we will create a new "x-amz-date" header with the current time. */ func (s *V4Signer) requestTime(req *http.Request) time.Time { // Get "x-amz-date" header date := req.Header.Get("x-amz-date") // Attempt to parse as ISO8601BasicFormat t, err := time.Parse(ISO8601BasicFormat, date) if err == nil { return t } // Attempt to parse as http.TimeFormat t, err = time.Parse(http.TimeFormat, date) if err == nil { req.Header.Set("x-amz-date", t.Format(ISO8601BasicFormat)) return t } // Get "date" header date = req.Header.Get("date") // Attempt to parse as http.TimeFormat t, err = time.Parse(http.TimeFormat, date) if err == nil { return t } // Create a current time header to be used t = time.Now().UTC() req.Header.Set("x-amz-date", t.Format(ISO8601BasicFormat)) return t }
func TestRecord_GetRecordTime(t *testing.T) { recorder := &Recpt1Recorder{} r, _ := ParseRecord([]byte(`{ "_id": "12345", "channel_name": "MyChannel", "title": "Title", "start_at": "2012-01-01T01:00:00Z", "end_at": "2012-01-01T02:00:00Z" }`)) now, _ := time.Parse(time.RFC3339, "2012-01-01T00:00:00Z") rec := recorder.GetRecordTime(r, now) if rec.Hours() != 1.0 { t.Errorf("GetRecordTime() => %f, want %f", rec.Hours(), 1.0) } now, _ = time.Parse(time.RFC3339, "2012-01-01T01:30:00Z") rec = recorder.GetRecordTime(r, now) if rec.Hours() != 0.5 { t.Errorf("GetRecordTime() => %f, want %f", rec.Hours(), 0.5) } now, _ = time.Parse(time.RFC3339, "2012-01-01T02:30:00Z") rec = recorder.GetRecordTime(r, now) if rec.Hours() != 0 { t.Errorf("GetRecordTime() => %f, want %f", rec.Hours(), 0) } }
// RunEvents is the handler for 'scw events' func RunEvents(ctx CommandContext, args EventsArgs) error { events, err := ctx.API.GetTasks() if err != nil { return fmt.Errorf("unable to fetch tasks from the Scaleway API: %v", err) } for _, event := range *events { startedAt, err := time.Parse("2006-01-02T15:04:05.000000+00:00", event.StartDate) if err != nil { return fmt.Errorf("unable to parse started date from the Scaleway API: %v", err) } terminatedAt := "" if event.TerminationDate != "" { terminatedAtTime, err := time.Parse("2006-01-02T15:04:05.000000+00:00", event.TerminationDate) if err != nil { return fmt.Errorf("unable to parse terminated date from the Scaleway API: %v", err) } terminatedAt = units.HumanDuration(time.Now().UTC().Sub(terminatedAtTime)) } fmt.Printf("%s %s: %s (%s %d) %s\n", startedAt, event.HrefFrom, event.Description, event.Status, event.Progress, terminatedAt) } return nil }
func main() { p := fmt.Println t := time.Now() p(t.Format(time.RFC3339)) t1, e := time.Parse( time.RFC3339, "2012-11-01T22:08:41+00:00") p(t1) p(t.Format("3:04PM")) p(t.Format("Mon Jan _2 15:04:05 2006")) p(t.Format("2006-01-02T15:04:05.999999-07:00")) form := "3 04 PM" t2, e := time.Parse(form, "8 41 PM") p(t2) fmt.Printf("%d-%02d-%02dT%02d:%02d:%02d-00:00\n", t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), t.Second()) ansic := "Mon Jan _2 15:04:05 2006" _, e = time.Parse(ansic, "8:41PM") p(e) }
func parseOffset(value string) (*time.Location, error) { var err error var t time.Time var loc *time.Location t, err = time.Parse("-07:00", value) if err == nil { return fixedZone(t), nil } t, err = time.Parse("-0700", value) if err == nil { return fixedZone(t), nil } _, err = time.Parse("MST", value) if err == nil { var offset int offset, err = timezone.GetOffset(value) if err != nil { return loc, err } return time.FixedZone(value, offset), nil } return loc, errInvalidOffset }
func (b *Booking) PostGet(exe gorp.SqlExecutor) error { var ( obj interface{} err error ) obj, err = exe.Get(User{}, b.UserId) if err != nil { return fmt.Errorf("Error loading a booking's user (%d): %s", b.UserId, err) } b.User = obj.(*User) obj, err = exe.Get(Hotel{}, b.HotelId) if err != nil { return fmt.Errorf("Error loading a booking's hotel (%d): %s", b.HotelId, err) } b.Hotel = obj.(*Hotel) if b.CheckInDate, err = time.Parse(SQL_DATE_FORMAT, b.CheckInStr); err != nil { return fmt.Errorf("Error parsing check in date '%s':", b.CheckInStr, err) } if b.CheckOutDate, err = time.Parse(SQL_DATE_FORMAT, b.CheckOutStr); err != nil { return fmt.Errorf("Error parsing check out date '%s':", b.CheckOutStr, err) } return nil }
func getCreationStartTime(t *testing.T, ctx *testutils.RktRunCtx, imageID string) (creation time.Time, start time.Time) { // Run rkt list --full rktCmd := fmt.Sprintf("%s list --full", ctx.Cmd()) child := spawnOrFail(t, rktCmd) child.Wait() // Get creation time match := fmt.Sprintf(".*%s\t.*\t(.*)\t(.*)\t", imageID) result, out, err := expectRegexWithOutput(child, match) if err != nil { t.Fatalf("%q regex not found, Error: %v\nOutput: %v", match, err, out) } tmStr := strings.TrimSpace(result[1]) creation, err = time.Parse(defaultTimeLayout, tmStr) if err != nil { t.Fatalf("Error parsing creation time: %q", err) } tmStr = strings.TrimSpace(result[2]) start, err = time.Parse(defaultTimeLayout, tmStr) if err != nil { t.Fatalf("Error parsing start time: %q", err) } return creation, start }
func TestKeyExpiry(t *testing.T) { kring, _ := ReadKeyRing(readerFromHex(expiringKeyHex)) entity := kring[0] const timeFormat = "2006-01-02" time1, _ := time.Parse(timeFormat, "2013-07-01") // The expiringKeyHex key is structured as: // // pub 1024R/5E237D8C created: 2013-07-01 expires: 2013-07-31 usage: SC // sub 1024R/1ABB25A0 created: 2013-07-01 expires: 2013-07-08 usage: E // sub 1024R/96A672F5 created: 2013-07-01 expires: 2013-07-31 usage: E // // So this should select the first, non-expired encryption key. key, _ := entity.encryptionKey(time1) if id := key.PublicKey.KeyIdShortString(); id != "1ABB25A0" { t.Errorf("Expected key 1ABB25A0 at time %s, but got key %s", time1.Format(timeFormat), id) } // Once the first encryption subkey has expired, the second should be // selected. time2, _ := time.Parse(timeFormat, "2013-07-09") key, _ = entity.encryptionKey(time2) if id := key.PublicKey.KeyIdShortString(); id != "96A672F5" { t.Errorf("Expected key 96A672F5 at time %s, but got key %s", time2.Format(timeFormat), id) } // Once all the keys have expired, nothing should be returned. time3, _ := time.Parse(timeFormat, "2013-08-01") if key, ok := entity.encryptionKey(time3); ok { t.Errorf("Expected no key at time %s, but got key %s", time3.Format(timeFormat), key.PublicKey.KeyIdShortString()) } }
func (image *ImageDetails) CreatedAt() (time.Time, error) { t, e := time.Parse("2006-01-02T15:04:05.999999999Z", image.Created) if e != nil { t, e = time.Parse("2006-01-02T15:04:05.999999999-07:00", image.Created) } return t, e }
func Incidents(t miniprofiler.Timer, w http.ResponseWriter, r *http.Request) (interface{}, error) { alert := r.FormValue("alert") toTime := time.Now().UTC() fromTime := toTime.Add(-14 * 24 * time.Hour) // 2 weeks if from := r.FormValue("from"); from != "" { t, err := time.Parse(tsdbFormatSecs, from) if err != nil { return nil, err } fromTime = t } if to := r.FormValue("to"); to != "" { t, err := time.Parse(tsdbFormatSecs, to) if err != nil { return nil, err } toTime = t } incidents := schedule.GetIncidents(alert, fromTime, toTime) maxIncidents := 200 if len(incidents) > maxIncidents { incidents = incidents[:maxIncidents] } return incidents, nil }