Example #1
0
func TestTimestampRoundtrip(t *testing.T) {
	defer leaktest.AfterTest(t)()
	ts := time.Date(2006, 7, 8, 0, 0, 0, 123000, time.FixedZone("UTC", 0))

	parse := func(encoded []byte) time.Time {
		decoded, err := parseTs(string(encoded))
		if err != nil {
			t.Fatal(err)
		}
		return decoded.UTC()
	}

	if actual := parse(formatTs(ts, nil, nil)); !ts.Equal(actual) {
		t.Fatalf("timestamp did not roundtrip got [%s] expected [%s]", actual, ts)
	}

	// Also check with a 0, positive, and negative offset.
	CET := time.FixedZone("Europe/Paris", 0)
	EST := time.FixedZone("America/New_York", 0)

	for _, tz := range []*time.Location{time.UTC, CET, EST} {
		if actual := parse(formatTs(ts, tz, nil)); !ts.Equal(actual) {
			t.Fatalf("[%s]: timestamp did not roundtrip got [%s] expected [%s]", tz, actual, ts)
		}
	}
}
Example #2
0
func TestDateParsing(t *testing.T) {
	tests := []struct {
		dateStr string
		exp     time.Time
	}{
		// RFC 5322, Appendix A.1.1
		{
			"Fri, 21 Nov 1997 09:55:06 -0600",
			time.Date(1997, 11, 21, 9, 55, 6, 0, time.FixedZone("", -6*60*60)),
		},
		// RFC5322, Appendix A.6.2
		// Obsolete date.
		{
			"21 Nov 97 09:55:06 GMT",
			time.Date(1997, 11, 21, 9, 55, 6, 0, time.FixedZone("GMT", 0)),
		},
	}
	for _, test := range tests {
		hdr := Header{
			"Date": []string{test.dateStr},
		}
		date, err := hdr.Date()
		if err != nil {
			t.Errorf("Failed parsing %q: %v", test.dateStr, err)
			continue
		}
		if !date.Equal(test.exp) {
			t.Errorf("Parse of %q: got %+v, want %+v", test.dateStr, date, test.exp)
		}
	}
}
Example #3
0
func TestGetTransactions(t *testing.T) {
	t.Parallel()

	k := Kasse{db: createDB(t), log: testLogger(t)}
	defer k.db.Close()

	mero := User{ID: 1, Name: "Merovius", Password: []byte("password")}
	koebi := User{ID: 2, Name: "Koebi", Password: []byte("password1")}

	insertData(t, k.db, []User{
		mero,
		koebi,
	}, []Card{
		{ID: []byte("aaaa"), User: 1},
		{ID: []byte("aaab"), User: 1},
		{ID: []byte("baaa"), User: 2},
		{ID: []byte("baab"), User: 2},
	}, []Transaction{
		{ID: 1, User: 1, Card: nil, Time: time.Date(2015, 4, 6, 22, 59, 3, 0, time.FixedZone("TST", 3600)), Amount: 1000, Kind: "Aufladung"},
		{ID: 2, User: 1, Card: []byte("aaaa"), Time: time.Date(2015, 4, 6, 23, 5, 27, 0, time.FixedZone("TST", 3600)), Amount: -100, Kind: "Kartenswipe"},
		{ID: 3, User: 1, Card: []byte("aaab"), Time: time.Date(2015, 4, 6, 23, 7, 23, 0, time.FixedZone("TST", 3600)), Amount: -100, Kind: "Kartenswipe"},
	})

	tcs := []struct {
		user    User
		n       int
		wantErr error
		amounts []int
	}{
		{koebi, 0, nil, nil},
		{koebi, 23, nil, nil},
		{mero, 2, nil, []int{-100, -100}},
		{mero, 0, nil, []int{-100, -100, 1000}},
	}

	for _, tc := range tcs {
		got, gotErr := k.GetTransactions(tc.user, tc.n)
		if tc.wantErr != nil {
			if gotErr != tc.wantErr {
				t.Errorf("GetTransactions(%v, %v) == (%v, %v), want (_, %v)", tc.user.Name, tc.n, got, gotErr, tc.wantErr)
			}
			continue
		} else if gotErr != nil {
			t.Errorf("GetTransactions(%v, %v) == (%v, %v), want (_, %v)", tc.user.Name, tc.n, got, gotErr, nil)
			continue
		}

		if len(got) != len(tc.amounts) {
			t.Errorf("GetTransactions(%v, %v) == (%v, %v), want %v", tc.user.Name, tc.n, got, gotErr, tc.amounts)
			continue
		}

		for i := range got {
			if got[i].Amount != tc.amounts[i] {
				t.Errorf("GetTransactions(%v, %v) == (%v, %v), want %v", tc.user.Name, tc.n, got, gotErr, tc.amounts)
				continue
			}
		}
	}
}
Example #4
0
// convertIPPDateToTime converts an RFC 2579 date to a time.Time object.
func convertIPPDateToTime(date *C.ipp_uchar_t) time.Time {
	r := bytes.NewReader(C.GoBytes(unsafe.Pointer(date), 11))
	var year uint16
	var month, day, hour, min, sec, dsec uint8
	binary.Read(r, binary.BigEndian, &year)
	binary.Read(r, binary.BigEndian, &month)
	binary.Read(r, binary.BigEndian, &day)
	binary.Read(r, binary.BigEndian, &hour)
	binary.Read(r, binary.BigEndian, &min)
	binary.Read(r, binary.BigEndian, &sec)
	binary.Read(r, binary.BigEndian, &dsec)

	var utcDirection, utcHour, utcMin uint8
	binary.Read(r, binary.BigEndian, &utcDirection)
	binary.Read(r, binary.BigEndian, &utcHour)
	binary.Read(r, binary.BigEndian, &utcMin)

	var utcOffset time.Duration
	utcOffset += time.Duration(utcHour) * time.Hour
	utcOffset += time.Duration(utcMin) * time.Minute
	var loc *time.Location
	if utcDirection == '-' {
		loc = time.FixedZone("", -int(utcOffset.Seconds()))
	} else {
		loc = time.FixedZone("", int(utcOffset.Seconds()))
	}

	nsec := int(dsec) * 100 * int(time.Millisecond)

	return time.Date(int(year), time.Month(month), int(day), int(hour), int(min), int(sec), nsec, loc)
}
Example #5
0
func (d *decoder) parseTimeStamp(dm *defmsg, fieldv reflect.Value, pfield *field) {
	u32 := dm.arch.Uint32(d.tmp[:fitUint32.size()])
	if u32 == 0xFFFFFFFF {
		return
	}
	if u32 < systemTimeMarker {
		if debug {
			log.Println("parsing time: seconds from device power on")
		}
	}

	if pfield.t == timeutc {
		if pfield.num == fieldNumTimeStamp {
			d.timestamp = u32
			d.lastTimeOffset = int32(d.timestamp & compressedTimeMask)
		}
		t := decodeDateTime(u32)
		fieldv.Set(reflect.ValueOf(t))
		return
	}

	// Local timestamp.
	//
	// TODO(tormoder): Improve. We may have offset from
	// UTC, but getting actual timezone is complex. Could
	// take GPS coordinates into account, but
	// complicated...
	//
	// Update - this actually exists for Go
	// https://github.com/bradfitz/latlong
	//
	// For now use a custom timezone with the calculated
	// offset to indicated that it is not UTC.
	var local time.Time
	switch {
	case d.timestamp == 0, d.timestamp < systemTimeMarker:
		// No time reference.
		// Set local with zero offset.
		d.timestamp = u32
		tzone := time.FixedZone(localZoneName, 0)
		local = decodeDateTime(u32)
		local = local.In(tzone)
	default:
		local = decodeDateTime(u32)
		utc := decodeDateTime(d.timestamp)
		offsetDur := local.Sub(utc)
		tzone := time.FixedZone(localZoneName, int(offsetDur.Seconds()))
		local = utc.In(tzone)
	}
	fieldv.Set(reflect.ValueOf(local))
}
Example #6
0
func TestUnserialize(t *testing.T) {
	cases := []unserializeTest{
		{[]byte(example_packet), HookMessage{
			Before: "5aef35982fb2d34e9d9d4502f6ede1072793222d",
			Repository: Repository{
				URL:         "http://github.com/defunkt/github",
				Name:        "github",
				Description: "You're lookin' at it.",
				Watchers:    5,
				Forks:       2,
				Private:     true,
				Owner: Author{
					Email: "*****@*****.**",
					Name:  "defunkt",
				},
			},
			Commits: []Commit{
				{
					ID:  "41a212ee83ca127e3c8cf465891ab7216a705f59",
					URL: "http://github.com/defunkt/github/commit/41a212ee83ca127e3c8cf465891ab7216a705f59",
					Author: Author{
						Email: "*****@*****.**",
						Name:  "Chris Wanstrath",
					},
					Message:   "okay i give in",
					Timestamp: time.Date(2008, 02, 15, 14, 57, 17, 0, time.FixedZone("", -8*3600)),
					Added:     []string{"filepath.rb"},
				},
				{
					ID:  "de8251ff97ee194a289832576287d6f8ad74e3d0",
					URL: "http://github.com/defunkt/github/commit/de8251ff97ee194a289832576287d6f8ad74e3d0",
					Author: Author{
						Email: "*****@*****.**",
						Name:  "Chris Wanstrath",
					},
					Message:   "update pricing a tad",
					Timestamp: time.Date(2008, 02, 15, 14, 36, 34, 0, time.FixedZone("", -8*3600)),
				},
			},
			After: "de8251ff97ee194a289832576287d6f8ad74e3d0",
			Ref:   "refs/heads/master",
		}},
	}

	for _, c := range cases {
		c.perform(t)
	}
}
Example #7
0
func (s *oplogSuite) TestNewMongoTimestamp(c *gc.C) {
	t := time.Date(2015, 6, 24, 12, 47, 0, 0, time.FixedZone("somewhere", 5*3600))

	expected := bson.MongoTimestamp(6163845091342417920)
	c.Assert(mongo.NewMongoTimestamp(t), gc.Equals, expected)
	c.Assert(mongo.NewMongoTimestamp(t.In(time.UTC)), gc.Equals, expected)
}
Example #8
0
// Afghanistan returns a pointer to time.Location of Asia/Kabul
func Afghanistan() *time.Location {
	loc, err := time.LoadLocation("Asia/Kabul")
	if err != nil {
		loc = time.FixedZone("Asia/Kabul", 16200) // UTC + 04:30
	}
	return loc
}
func Test_parseLastModified_Normal(t *testing.T) {
	expected := time.Date(2013, time.November, 27, 0, 6, 52, 0, time.FixedZone("-0500", -5*60*60))
	test_string := `2013-11-27T00:06:52-05:00`
	parsed, err := parseLastModified(test_string)
	assert.Nil(t, err, fmt.Sprintf("unexpected error from parseLastModified: %s", err))
	assert.Equal(t, parsed.String(), expected.String(), fmt.Sprintf("parsed item \"%s\" did not match expected \"%s\"", parsed, expected))
}
Example #10
0
func reqlTimeToNativeTime(timestamp float64, timezone string) (time.Time, error) {
	sec := int64(timestamp)

	t := time.Unix(sec, 0)

	// Caclulate the timezone
	if timezone != "" {
		hours, err := strconv.Atoi(timezone[1:3])
		if err != nil {
			return time.Time{}, err
		}
		minutes, err := strconv.Atoi(timezone[4:6])
		if err != nil {
			return time.Time{}, err
		}
		tzOffset := ((hours * 60) + minutes) * 60
		if timezone[:1] == "-" {
			tzOffset = 0 - tzOffset
		}

		t = t.In(time.FixedZone(timezone, tzOffset))
	}

	return t, nil
}
func (s *ServiceSuite) TestUnconfirmedResourcesDontGenerateEvents(c *C) {
	data, err := ioutil.ReadFile("fixtures/brad_bradworth_event_source_bundle.json")
	util.CheckErr(err)

	bundle := new(models.Bundle)
	json.Unmarshal(data, bundle)

	// Switch a few resources to be unconfirmed
	bundle.Entry[2].Resource.(*models.Condition).VerificationStatus = "refuted"
	bundle.Entry[4].Resource.(*models.MedicationStatement).Status = "entered-in-error"

	es, err := BundleToEventStream(bundle)
	util.CheckErr(err)

	c.Assert(es.Patient, NotNil)
	c.Assert(es.Patient.Id, Equals, "507f1f77bcf86cd799439001")
	c.Assert(es.Events, HasLen, 3)
	loc := time.FixedZone("-0500", -5*60*60)
	// Event 0 (Condition: Atrial Fibrillation)
	c.Assert(es.Events[0].Date.Equal(time.Date(2012, time.September, 20, 8, 0, 0, 0, loc)), Equals, true)
	c.Assert(es.Events[0].Type, Equals, "Condition")
	c.Assert(es.Events[0].End, Equals, false)
	c.Assert(es.Events[0].Value, DeepEquals, bundle.Entry[1].Resource)
	// Event 1 (Condition: Cerebral infarction due to cerebral artery occlusion)
	c.Assert(es.Events[1].Date.Equal(time.Date(2014, time.January, 17, 20, 35, 0, 0, loc)), Equals, true)
	c.Assert(es.Events[1].Type, Equals, "Condition")
	c.Assert(es.Events[1].End, Equals, false)
	c.Assert(es.Events[1].Value, DeepEquals, bundle.Entry[3].Resource)
	// Event 2 (Condition END: Cerebral infarction due to cerebral artery occlusion)
	c.Assert(es.Events[2].Date.Equal(time.Date(2014, time.January, 17, 20, 40, 0, 0, loc)), Equals, true)
	c.Assert(es.Events[2].Type, Equals, "Condition")
	c.Assert(es.Events[2].End, Equals, true)
	c.Assert(es.Events[2].Value, DeepEquals, bundle.Entry[3].Resource)
}
Example #12
0
func TestFmtTimeFull(t *testing.T) {

	loc, err := time.LoadLocation("America/Toronto")
	if err != nil {
		t.Errorf("Expected '<nil>' Got '%s'", err)
	}

	fixed := time.FixedZone("OTHER", -4)

	tests := []struct {
		t        time.Time
		expected string
	}{
		{
			t:        time.Date(2016, 02, 03, 9, 5, 1, 0, loc),
			expected: "9:05:01 am Eastern Standard Time",
		},
		{
			t:        time.Date(2016, 02, 03, 20, 5, 1, 0, fixed),
			expected: "8:05:01 pm OTHER",
		},
	}

	trans := New()

	for _, tt := range tests {
		s := trans.FmtTimeFull(tt.t)
		if s != tt.expected {
			t.Errorf("Expected '%s' Got '%s'", tt.expected, s)
		}
	}
}
Example #13
0
func TimeZone() {
	jst := time.FixedZone("Asia/Tokyo", 9*60*60)
	n1 := time.Now()

	n2 := n1.UTC()
	n3 := n2.In(jst)
	now := time.Date(
		n3.Year(),
		n3.Month(),
		n3.Day(),
		0,
		0,
		0,
		0,
		jst,
	)

	nowUnix := now.Unix()

	tracer.Println("jst:", jst)
	tracer.Println("n1:", n1)           // JST(日本標準時)のためジャストな時間で表示
	tracer.Println("n2:", n2)           // UTC(協定世界時)で表示のため、-9時間
	tracer.Println("n3:", n3)           // Asia/Tokyoに指定した時間、JSTと一緒になる
	tracer.Println("now:", now)         // 実行日の0時
	tracer.Println("nowUnix:", nowUnix) // 1970/01/01 UTC からの経過時間ミリ秒

	prevDay := now.AddDate(0, 0, -1)

	tracer.Println("nowPrevDay:", prevDay)
	tracer.Println("nowPrevDayUnix:", prevDay.Unix()) // 前日の経過時間ミリ秒
}
Example #14
0
// The assertions in this test should also be caught by the integration tests on
// various drivers.
func TestParseTs(t *testing.T) {
	defer leaktest.AfterTest(t)()

	var parseTsTests = []struct {
		strTimestamp string
		expected     time.Time
	}{
		// time.RFC3339Nano for github.com/lib/pq.
		{"2006-07-08T00:00:00.000000123Z", time.Date(2006, 7, 8, 0, 0, 0, 123, time.FixedZone("UTC", 0))},

		// The format accepted by pq.ParseTimestamp.
		{"2001-02-03 04:05:06.123-07", time.Date(2001, time.February, 3, 4, 5, 6, 123000000, time.FixedZone("", -7*60*60))},
	}

	for i, test := range parseTsTests {
		parsed, err := parseTs(test.strTimestamp)
		if err != nil {
			t.Errorf("%d could not parse [%s]: %v", i, test.strTimestamp, err)
			continue
		}
		if !parsed.Equal(test.expected) {
			t.Errorf("%d parsing [%s] got [%s] expected [%s]", i, test.strTimestamp, parsed, test.expected)
		}
	}
}
Example #15
0
func (c *UserInfoCommand) Process(args []string, msg *discordgo.Message, info *GuildInfo) (string, bool) {
	if len(args) < 1 {
		return "```You must provide a user to search for.```", false
	}
	arg := strings.Join(args, " ")
	IDs := FindUsername(arg, info)
	if len(IDs) == 0 { // no matches!
		return "```Error: Could not find any usernames or aliases matching " + arg + "!```", false
	}
	if len(IDs) > 1 {
		return "```Could be any of the following users or their aliases:\n" + strings.Join(IDsToUsernames(IDs, info), "\n") + "```", len(IDs) > 5
	}

	aliases := sb.db.GetAliases(IDs[0])
	dbuser, lastseen, tz, _ := sb.db.GetUser(IDs[0])
	localtime := ""
	if tz == nil {
		tz = time.FixedZone("[Not Set]", 0)
	} else {
		localtime = time.Now().In(tz).Format(time.RFC1123)
	}
	m, err := sb.dg.GuildMember(info.Guild.ID, SBitoa(IDs[0]))
	if err != nil {
		m = &discordgo.Member{Roles: []string{}}
		u, err := sb.dg.User(SBitoa(IDs[0]))
		if err != nil {
			if dbuser == nil {
				return "```Error retrieving user information: " + err.Error() + "```", false
			}
			u = dbuser
		}
		m.User = u
	}
	authortz := getTimezone(info, msg.Author)
	joinedat, err := time.Parse(time.RFC3339Nano, m.JoinedAt)
	joined := ""
	if err == nil {
		joined = joinedat.In(authortz).Format(time.RFC1123)
	}
	guildroles, err := sb.dg.GuildRoles(info.Guild.ID)
	if err != nil {
		guildroles = info.Guild.Roles
	}

	roles := make([]string, 0, len(m.Roles))
	for _, v := range m.Roles {
		if err == nil {
			for _, role := range guildroles {
				if role.ID == v {
					roles = append(roles, role.Name)
					break
				}
			}
		} else {
			roles = append(roles, "<@&"+v+">")
		}
	}

	return ExtraSanitize(fmt.Sprintf("**ID:** %v\n**Username:** %v#%v\n**Nickname:** %v\n**Timezone:** %v\n**Local Time:** %v\n**Joined:** %v\n**Roles:** %v\n**Bot:** %v\n**Last Seen:** %v\n**Aliases:** %v\n**Avatar:** ", m.User.ID, m.User.Username, m.User.Discriminator, m.Nick, tz, localtime, joined, strings.Join(roles, ", "), m.User.Bot, lastseen.In(authortz).Format(time.RFC1123), strings.Join(aliases, ", "))) + discordgo.EndpointUserAvatar(m.User.ID, m.User.Avatar), false
}
Example #16
0
func TestRouterRequestLoggingWithNoContentResponse(t *testing.T) {
	want := "127.0.0.1 - - [11/Oct/2000:13:55:36 -0700] \"GET /mango HTTP/1.1\" 204 0"

	location := time.FixedZone("test", -25200)
	start := time.Date(2000, 10, 11, 13, 55, 36, 0, location)
	nowUTC = func() time.Time {
		return start
	}

	req, _ := http.NewRequest("GET", "https://somewhere.com/mango", nil)
	req.RemoteAddr = "127.0.0.1"
	w := httptest.NewRecorder()
	got := ""
	r := Router{}
	r.RequestLogger = func(l *RequestLog) {
		got = l.CommonFormat()
		if got != want {
			t.Errorf("Log got %q, want %q", got, want)
		}
	}
	r.routes = newMockRoutes()
	r.routes.AddHandlerFunc("/mango", "GET", func(c *Context) {
		c.RespondWith(204)
	})
	r.ServeHTTP(w, req)
}
Example #17
0
// UnmarshalDateTimeTz unmarshals time.Time from the SOAP "dateTime.tz" type.
// This returns a value in the local timezone when the timezone is unspecified.
func UnmarshalDateTimeTz(s string) (result time.Time, err error) {
	dateStr, timeStr, zoneStr, err := splitCompleteDateTimeZone(s)
	if err != nil {
		return
	}

	year, month, day, err := parseDateParts(dateStr)
	if err != nil {
		return
	}

	var hour, minute, second int
	var location *time.Location = localLoc
	if len(timeStr) != 0 {
		hour, minute, second, err = parseTimeParts(timeStr)
		if err != nil {
			return
		}
		if len(zoneStr) != 0 {
			var offset int
			offset, err = parseTimezone(zoneStr)
			if offset == 0 {
				location = time.UTC
			} else {
				location = time.FixedZone("", offset)
			}
		}
	}

	result = time.Date(year, time.Month(month), day, hour, minute, second, 0, location)
	return
}
Example #18
0
func getData() (*[7][][2]string, error) {
	// 1, 4, 7, 10
	resp, err := http.Get("http://acgdb.com/" + getQuarter() + "/bangumi")
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	b, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}
	s := string(b)
	var result [7][][2]string
	anime := rAnime.FindAllStringSubmatch(s, -1)

	for _, v := range anime {
		millisecond, _ := strconv.ParseInt(v[1], 10, 64)
		t := time.Unix(millisecond/1000, 0).In(time.FixedZone("Asia/Beijing", 8*60*60))
		w := int(t.Weekday())
		result[w] = append(result[w], [2]string{t.Format("15:04"), v[2]})
	}
	// 排序
	for _, v := range result {
		sort.Sort(sortAnimeList(v))
	}
	return &result, nil
}
Example #19
0
func onError(err error) string {
	return fmt.Sprintf(
		"%s [%s]",
		err.Error(),
		time.Now().In(time.FixedZone("Asia/Tokyo", 9*60*60)).Format(time.RFC3339),
	)
}
Example #20
0
func (m *MongoSearchSuite) SetUpSuite(c *C) {
	m.EST = time.FixedZone("EST", -5*60*60)
	m.Local, _ = time.LoadLocation("Local")

	//turnOnDebugLog()

	// Set up the database
	m.DBServer = &dbtest.DBServer{}
	m.DBServer.SetPath(c.MkDir())

	m.Session = m.DBServer.Session()
	db := m.Session.DB("fhir-test")
	m.MongoSearcher = &MongoSearcher{db}

	// Read in the data in FHIR format
	data, err := ioutil.ReadFile("../fixtures/search_test_data.json")
	util.CheckErr(err)

	maps := make([]interface{}, 19)
	err = json.Unmarshal(data, &maps)
	util.CheckErr(err)

	for _, resourceMap := range maps {
		r := models.MapToResource(resourceMap, true)
		collection := models.PluralizeLowerResourceName(reflect.TypeOf(r).Elem().Name())
		util.CheckErr(db.C(collection).Insert(r))
	}
}
Example #21
0
func reqlTimeToNativeTime(timestamp float64, timezone string) (time.Time, error) {
	sec, ms := math.Modf(timestamp)

	// Convert to native time rounding to milliseconds
	t := time.Unix(int64(sec), int64(math.Floor(ms*1000+0.5))*1000*1000)

	// Caclulate the timezone
	if timezone != "" {
		hours, err := strconv.Atoi(timezone[1:3])
		if err != nil {
			return time.Time{}, err
		}
		minutes, err := strconv.Atoi(timezone[4:6])
		if err != nil {
			return time.Time{}, err
		}
		tzOffset := ((hours * 60) + minutes) * 60
		if timezone[:1] == "-" {
			tzOffset = 0 - tzOffset
		}

		t = t.In(time.FixedZone(timezone, tzOffset))
	}

	return t, nil
}
Example #22
0
// Iran returns a pointer to time.Location of Asia/Tehran
func Iran() *time.Location {
	loc, err := time.LoadLocation("Asia/Tehran")
	if err != nil {
		loc = time.FixedZone("Asia/Tehran", 12600) // UTC + 03:30
	}
	return loc
}
Example #23
0
func TestStrToTime(t *testing.T) {
	// zoneName, err := time.LoadLocation("CST")
	// if err != nil {
	//     t.Error(err)
	// }

	var testCases = []test{
		{
			time.Date(2012, 11, 22, 21, 28, 10, 0, time.Local),
			"",
			"2012-11-22 21:28:10 +0800 +0800",
		},
		{
			time.Date(2012, 11, 22, 0, 0, 0, 0, time.Local),
			"",
			"2012-11-22 +0800 +0800",
		},
		{
			time.Date(2012, 11, 22, 21, 28, 10, 0, time.FixedZone("CST", 28800)),
			"",
			"2012-11-22 21:28:10 +0800 CST",
		},
	}
	for _, testCase := range testCases {
		time := StrToTime(testCase.strTime)
		// if time != testCase.time {
		if !time.Equal(testCase.time) {
			t.Errorf("(expected) %v != %v (actual)", time, testCase.time)
		}
	}
}
Example #24
0
func TestRouterRequestLoggingWhenUnRecoveredPanic(t *testing.T) {
	msg := "Internal Server Error\n"
	bCount := strconv.Itoa(len(msg))
	want := "127.0.0.1 - - [11/Oct/2000:13:55:36 -0700] \"GET /mango HTTP/1.1\" 500 " + bCount

	location := time.FixedZone("test", -25200)
	start := time.Date(2000, 10, 11, 13, 55, 36, 0, location)
	nowUTC = func() time.Time {
		return start
	}

	req, _ := http.NewRequest("GET", "https://somewhere.com/mango", nil)
	req.RemoteAddr = "127.0.0.1"
	w := httptest.NewRecorder()
	r := Router{}
	ch := make(chan string)
	r.RequestLogger = func(l *RequestLog) {
		ch <- l.CommonFormat()
	}
	r.routes = newMockRoutes()
	r.routes.AddHandlerFunc("/mango", "GET", func(c *Context) {
		panic("what no mangoes!")
	})

	r.ServeHTTP(w, req)

	select {
	case got := <-ch:
		if got != want {
			t.Errorf("Log got %q, want %q", got, want)
		}
	case <-time.After(time.Second * 3):
		t.Errorf("Timed out")
	}
}
Example #25
0
func oParseYoutubeTime(sYoutubeTime string) time.Time {

	aMonths := []time.Month{
		time.January, time.February, time.March, time.April, time.May, time.June,
		time.July, time.August, time.September, time.October, time.November, time.December,
	}

	oRegEx := regexp.MustCompile("(....)-(..)-(..)T(..)\\:(..)\\:(..)\\.(\\d*)Z")
	aTimeData := oRegEx.FindStringSubmatch(sYoutubeTime)
	iYear, _ := strconv.Atoi(aTimeData[1])
	iMonth, _ := strconv.Atoi(aTimeData[2])
	iDay, _ := strconv.Atoi(aTimeData[3])
	iHour, _ := strconv.Atoi(aTimeData[4])
	iMinute, _ := strconv.Atoi(aTimeData[5])
	iSecond, _ := strconv.Atoi(aTimeData[6])
	iOffset, _ := strconv.Atoi(aTimeData[7])
	oLocation := time.FixedZone("UTC", iOffset)
	oTime := time.Date(iYear, aMonths[iMonth-1], iDay, iHour, iMinute, iSecond, 0, oLocation)

	//fmt.Println(sYoutubeTime);
	//fmt.Printf("%#v %#v %#v %#v %#v %#v \n", oTime.Year(), oTime.Month(), oTime.Day(), oTime.Hour(), oTime.Minute(), oTime.Second());

	return oTime

}
Example #26
0
func init() {

	dbname := "default"
	runmode := beego.AppConfig.String("runmode")
	datasource := beego.AppConfig.String("datasource")

	switch runmode {
	case "prod":
		//orm.RegisterDriver("postgres", orm.DR_Postgres)
		//orm.RegisterDataBase(dbname, "postgres", datasource, 30)
		//orm.SetMaxIdleConns(dbname, 100)
		//orm.SetMaxOpenConns(dbname, 100)
		orm.RegisterDriver("mysql", orm.DRMySQL)
		orm.RegisterDataBase(dbname, "mysql", datasource)

	case "dev":
		orm.RegisterDriver("mysql", orm.DRMySQL)
		orm.RegisterDataBase(dbname, "mysql", datasource)

	default:
		//orm.RegisterDataBase(dbname, "sqlite3", datasource)
		orm.RegisterDriver("mysql", orm.DRMySQL)
		orm.RegisterDataBase(dbname, "mysql", datasource)
	}

	orm.DefaultTimeLoc = time.FixedZone("Asia/Tokyo", 9*60*60)

	force, verbose := false, true
	err := orm.RunSyncdb(dbname, force, verbose)
	if err != nil {
		panic(err)
	}

	// orm.RunCommand()
}
Example #27
0
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
}
Example #28
0
func TestResponseLogCombinedFormat(t *testing.T) {
	want := "127.0.0.1 - frank [11/Oct/2000:13:55:36 -0700] " +
		"\"GET /apache_pb.gif HTTP/1.0\" 200 2326 " +
		"\"https://github.com/spaceweasel/mango\" " +
		"\"Mozilla/5.0 (Android; rv:12.0) Gecko/12.0 Firefox/12.0\""

	location := time.FixedZone("test", -25200)
	start := time.Date(2000, 10, 11, 13, 55, 36, 0, location)
	log := RequestLog{
		Start:         start,
		RemoteAddr:    "127.0.0.1",
		AccessRequest: "GET /apache_pb.gif HTTP/1.0",
		Status:        200,
		BytesOut:      2326,
		Referer:       "https://github.com/spaceweasel/mango",
		UserAgent:     "Mozilla/5.0 (Android; rv:12.0) Gecko/12.0 Firefox/12.0",
		UserID:        "frank",
	}

	got := log.CombinedFormat()

	if got != want {
		t.Errorf("Log = %q, want %q", got, want)
	}
}
Example #29
0
func (s *auditSuite) TestValidate_NonUTCTimestampInvalid(c *gc.C) {
	invalidEntry := validEntry()
	invalidEntry.Timestamp = invalidEntry.Timestamp.In(time.FixedZone("x", 3600))

	validationErr := invalidEntry.Validate()
	c.Check(validationErr, jc.Satisfies, errors.IsNotValid)
	c.Check(validationErr, gc.ErrorMatches, "must be set to UTC: Timestamp not valid")
}
Example #30
0
func Test_ParseLayout0(t *testing.T) {
	date, err := parseTime("2014-03-07T05:38:00-05:00")
	expected := time.Date(2014, time.March, 7, 5, 38, 0, 0, time.FixedZone("-0500", -18000))
	assertEqualTime(t, expected, date)
	if err != nil {
		t.Errorf("err should be nil")
	}
}