Golang Date示例

说明

golang date示例是从最受好评的开源项目中提取的实现代码,你可以参考下面示例的使用方式。

编程语言: Golang

命名空间/包名称: Time

示例#1
文件: plugin_test.go 项目: intervention-engine/riskservice

func (p *PluginSuite) TestSortByAsOf(c *C) {
	results := []RiskServiceCalculationResult{
		{
			AsOf:  time.Date(2000, time.January, 1, 0, 0, 0, 0, time.UTC),
			Score: ptrToInt(1),
		},
		{
			AsOf:  time.Date(2004, time.January, 1, 0, 0, 0, 0, time.UTC),
			Score: ptrToInt(2),
		},
		{
			AsOf:  time.Date(2002, time.January, 1, 0, 0, 0, 0, time.UTC),
			Score: ptrToInt(3),
		},
		{
			AsOf:  time.Date(2005, time.January, 1, 0, 0, 0, 0, time.UTC),
			Score: ptrToInt(4),
		},
		{
			AsOf:  time.Date(1999, time.January, 1, 0, 0, 0, 0, time.UTC),
			Score: ptrToInt(5),
		},
	}

	sort.Sort(byAsOfDate(results))
	for i, score := range []int{5, 1, 3, 2, 4} {
		c.Assert(*results[i].Score, Equals, score)
	}
}

示例#2
文件: log.go 项目: ChinaLongGanHu/wqs

func genNextClock() (time.Time, time.Time) {
	now := time.Now().Local()
	year, month, day := now.Date()
	hour, _, _ := now.Clock()
	return time.Date(year, month, day, hour, 0, 0, 0, time.Local),
		time.Date(year, month, day, hour+1, 0, 0, 0, time.Local)
}

示例#3
文件: ec2_role_provider_test.go 项目: chancez/mantle

func TestEC2RoleProviderExpiryWindowIsExpired(t *testing.T) {
	server := initTestServer("2014-12-16T01:51:37Z", false)
	defer server.Close()

	p := &ec2rolecreds.EC2RoleProvider{
		Client:       ec2metadata.New(&ec2metadata.Config{Endpoint: aws.String(server.URL + "/latest")}),
		ExpiryWindow: time.Hour * 1,
	}
	p.CurrentTime = func() time.Time {
		return time.Date(2014, 12, 15, 0, 51, 37, 0, time.UTC)
	}

	assert.True(t, p.IsExpired(), "Expect creds to be expired before retrieve.")

	_, err := p.Retrieve()
	assert.Nil(t, err, "Expect no error")

	assert.False(t, p.IsExpired(), "Expect creds to not be expired after retrieve.")

	p.CurrentTime = func() time.Time {
		return time.Date(2014, 12, 16, 0, 55, 37, 0, time.UTC)
	}

	assert.True(t, p.IsExpired(), "Expect creds to be expired.")
}

示例#4
文件: repos_commits_test.go 项目: gmlewis/go-github

func TestRepositoriesService_ListCommits(t *testing.T) {
	setup()
	defer teardown()

	// given
	mux.HandleFunc("/repos/o/r/commits", func(w http.ResponseWriter, r *http.Request) {
		testMethod(t, r, "GET")
		testFormValues(t, r,
			values{
				"sha":    "s",
				"path":   "p",
				"author": "a",
				"since":  "2013-08-01T00:00:00Z",
				"until":  "2013-09-03T00:00:00Z",
			})
		fmt.Fprintf(w, `[{"sha": "s"}]`)
	})

	opt := &CommitsListOptions{
		SHA:    "s",
		Path:   "p",
		Author: "a",
		Since:  time.Date(2013, time.August, 1, 0, 0, 0, 0, time.UTC),
		Until:  time.Date(2013, time.September, 3, 0, 0, 0, 0, time.UTC),
	}
	commits, _, err := client.Repositories.ListCommits("o", "r", opt)
	if err != nil {
		t.Errorf("Repositories.ListCommits returned error: %v", err)
	}

	want := []*RepositoryCommit{{SHA: String("s")}}
	if !reflect.DeepEqual(commits, want) {
		t.Errorf("Repositories.ListCommits returned %+v, want %+v", commits, want)
	}
}

示例#5
文件: callcost_test.go 项目: eloycoto/cgrates

func TestMultipleResultMerge(t *testing.T) {
	t1 := time.Date(2012, time.February, 2, 17, 59, 0, 0, time.UTC)
	t2 := time.Date(2012, time.February, 2, 18, 0, 0, 0, time.UTC)
	cd := &CallDescriptor{Direction: utils.OUT, Category: "0", Tenant: "vdf", Subject: "rif", Destination: "0256", TimeStart: t1, TimeEnd: t2}
	cc1, _ := cd.getCost()
	if cc1.Cost != 61 {
		//ils.LogFull(cc1)
		t.Errorf("expected 61 was %v", cc1.Cost)
		for _, ts := range cc1.Timespans {
			t.Log(ts.RateInterval)
		}
	}
	t1 = time.Date(2012, time.February, 2, 18, 00, 0, 0, time.UTC)
	t2 = time.Date(2012, time.February, 2, 18, 01, 0, 0, time.UTC)
	cd = &CallDescriptor{Direction: utils.OUT, Category: "0", Tenant: "vdf", Subject: "rif", Destination: "0256", TimeStart: t1, TimeEnd: t2}
	cc2, _ := cd.getCost()
	if cc2.Cost != 30 {
		t.Errorf("expected 30 was %v", cc2.Cost)
		for _, ts := range cc1.Timespans {
			t.Log(ts.RateInterval)
		}
	}
	cc1.Merge(cc2)
	if len(cc1.Timespans) != 2 || cc1.Timespans[0].GetDuration().Seconds() != 60 {
		t.Error("wrong resulted timespans: ", len(cc1.Timespans))
	}
	if cc1.Cost != 91 {
		t.Errorf("Exdpected 91 was %v", cc1.Cost)
	}
}

示例#6
文件: ddazmbl2_test.go 项目: bhepp/cgrates

func TestDebit2(t *testing.T) {
	cd := &engine.CallDescriptor{
		Direction:   "*out",
		Category:    "call",
		Tenant:      "cgrates.org",
		Subject:     "12345",
		Account:     "12345",
		Destination: "447956933443",
		TimeStart:   time.Date(2014, 3, 4, 6, 0, 0, 0, time.UTC),
		TimeEnd:     time.Date(2014, 3, 4, 6, 0, 10, 0, time.UTC),
	}
	if cc, err := cd.Debit(); err != nil {
		t.Error(err)
	} else if cc.Cost != 0.01 {
		t.Error("Wrong cost returned: ", cc.Cost)
	}
	acnt, err := acntDb2.GetAccount("cgrates.org:12345")
	if err != nil {
		t.Error(err)
	}
	if len(acnt.BalanceMap) != 2 {
		t.Error("Wrong number of user balances found", acnt.BalanceMap)
	}
	if acnt.BalanceMap[utils.VOICE][0].Value != 20 {
		t.Error("Account does not have expected minutes in balance", acnt.BalanceMap[utils.VOICE][0].Value)
	}
	for _, blnc := range acnt.BalanceMap[utils.MONETARY] { // Test negative balance for default one
		if blnc.Weight == 10 && blnc.Value != 0 {
			t.Errorf("Balance with weight: %f, having value: %f  ", blnc.Weight, blnc.Value)
		} else if blnc.Weight == 0 && blnc.Value != -0.01 {
			t.Errorf("Balance with weight: %f, having value: %f  ", blnc.Weight, blnc.Value)
		}
	}
}

示例#7
文件: helper.go 项目: Pym/TwitterBot

func hasReachDailyTweetLimit() (bool, error) {
	var from time.Time
	var to time.Time

	now := time.Now()

	if now.Hour() >= WAKE_UP_HOUR {
		from = time.Date(now.Year(), now.Month(), now.Day(), WAKE_UP_HOUR, 0, 0, 0, now.Location())
	} else {
		yesterday := now.Add(-time.Duration(24) * time.Hour)
		from = time.Date(yesterday.Year(), yesterday.Month(), yesterday.Day(), WAKE_UP_HOUR, 0, 0, 0, yesterday.Location())
	}

	if now.Hour() < GO_TO_BED_HOUR {
		to = time.Date(now.Year(), now.Month(), now.Day(), GO_TO_BED_HOUR, 0, 0, 0, now.Location())
	} else {
		tomorrow := now.Add(time.Duration(24) * time.Hour)
		to = time.Date(tomorrow.Year(), tomorrow.Month(), tomorrow.Day(), GO_TO_BED_HOUR, 0, 0, 0, tomorrow.Location())
	}

	count, err := db.GetNumberOfTweetsBetweenDates(from, to)
	if err != nil {
		return true, err
	}

	return count >= MAX_TWEET_IN_A_DAY, nil
}

示例#8
文件: data_test.go 项目: kunapuli09/morgoth

// Ensure that a shard group can be created on a database for a given timestamp.
func TestData_CreateShardGroup(t *testing.T) {
	var data meta.Data
	if err := data.CreateNode("node0"); err != nil {
		t.Fatal(err)
	} else if err = data.CreateNode("node1"); err != nil {
		t.Fatal(err)
	} else if err = data.CreateDatabase("db0"); err != nil {
		t.Fatal(err)
	} else if err = data.CreateRetentionPolicy("db0", &meta.RetentionPolicyInfo{Name: "rp0", ReplicaN: 2, Duration: 1 * time.Hour}); err != nil {
		t.Fatal(err)
	}

	// Create shard group.
	if err := data.CreateShardGroup("db0", "rp0", time.Date(2000, time.January, 1, 0, 0, 0, 0, time.UTC)); err != nil {
		t.Fatal(err)
	}

	// Verify the shard group was created.
	if sgi, _ := data.ShardGroupByTimestamp("db0", "rp0", time.Date(2000, time.January, 1, 0, 0, 0, 0, time.UTC)); !reflect.DeepEqual(sgi, &meta.ShardGroupInfo{
		ID:        1,
		StartTime: time.Date(2000, time.January, 1, 0, 0, 0, 0, time.UTC),
		EndTime:   time.Date(2000, time.January, 1, 1, 0, 0, 0, time.UTC),
		Shards: []meta.ShardInfo{
			{ID: 1, OwnerIDs: []uint64{1, 2}},
		},
	}) {
		t.Fatalf("unexpected shard group: %#v", sgi)
	} else if !sgi.Shards[0].OwnedBy(1) || !sgi.Shards[0].OwnedBy(2) || sgi.Shards[0].OwnedBy(3) {
		// Verify shard is correctly owned-by the node.
		t.Fatalf("new shard is not owned by correct node")
	}
}

示例#9
文件: strconv_test.go 项目: PlanitarInc/go-simplequery

func TestParseTime(t *testing.T) {
	RegisterTestingT(t)

	var res time.Time
	var err error

	res, err = ParseTime("0")
	Ω(err).Should(BeNil())
	Ω(res).Should(Equal(time.Date(1970, 1, 1, 0, 0, 0, 0, time.UTC)))

	res, err = ParseTime("1445486493")
	Ω(err).Should(BeNil())
	Ω(res).Should(Equal(time.Date(2015, 10, 22, 4, 1, 33, 0, time.UTC)))

	res, err = ParseTime("2524608000")
	Ω(err).Should(BeNil())
	Ω(res).Should(Equal(time.Date(2050, 1, 1, 0, 0, 0, 0, time.UTC)))

	res, err = ParseTime("252460800000")
	Ω(err).Should(BeNil())
	Ω(res).Should(Equal(time.Date(1978, 1, 1, 0, 0, 0, 0, time.UTC)))

	res, err = ParseTime("2016-02-03T15:04:05Z")
	Ω(err).Should(BeNil())
	Ω(res).Should(Equal(time.Date(2016, 2, 3, 15, 4, 5, 0, time.UTC)))
}

示例#10
文件: types_test.go 项目: hvaara/cockroach

// 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)
		}
	}
}

示例#11
文件: suriya.go 项目: splendidmoons/suriya-go

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
}

示例#12
文件: ocsp_test.go 项目: dylanpoe/golang.org

func TestOCSPDecode(t *testing.T) {
	responseBytes, _ := hex.DecodeString(ocspResponseHex)
	resp, err := ParseResponse(responseBytes, nil)
	if err != nil {
		t.Error(err)
	}

	expected := Response{
		Status:           Good,
		SerialNumber:     big.NewInt(0x1d0fa),
		RevocationReason: Unspecified,
		ThisUpdate:       time.Date(2010, 7, 7, 15, 1, 5, 0, time.UTC),
		NextUpdate:       time.Date(2010, 7, 7, 18, 35, 17, 0, time.UTC),
	}

	if !reflect.DeepEqual(resp.ThisUpdate, expected.ThisUpdate) {
		t.Errorf("resp.ThisUpdate: got %d, want %d", resp.ThisUpdate, expected.ThisUpdate)
	}

	if !reflect.DeepEqual(resp.NextUpdate, expected.NextUpdate) {
		t.Errorf("resp.NextUpdate: got %d, want %d", resp.NextUpdate, expected.NextUpdate)
	}

	if resp.Status != expected.Status {
		t.Errorf("resp.Status: got %d, want %d", resp.Status, expected.Status)
	}

	if resp.SerialNumber.Cmp(expected.SerialNumber) != 0 {
		t.Errorf("resp.SerialNumber: got %x, want %x", resp.SerialNumber, expected.SerialNumber)
	}

	if resp.RevocationReason != expected.RevocationReason {
		t.Errorf("resp.RevocationReason: got %d, want %d", resp.RevocationReason, expected.RevocationReason)
	}
}

示例#13
文件: walk_test.go 项目: JoeX2/syncthing

func TestWalk(t *testing.T) {
	m := NewModel("testdata")
	files, ignores := m.Walk(false)

	if l1, l2 := len(files), len(testdata); l1 != l2 {
		t.Fatalf("Incorrect number of walked files %d != %d", l1, l2)
	}

	for i := range testdata {
		if n1, n2 := testdata[i].name, files[i].Name; n1 != n2 {
			t.Errorf("Incorrect file name %q != %q for case #%d", n1, n2, i)
		}

		if h1, h2 := fmt.Sprintf("%x", files[i].Blocks[0].Hash), testdata[i].hash; h1 != h2 {
			t.Errorf("Incorrect hash %q != %q for case #%d", h1, h2, i)
		}

		t0 := time.Date(2010, 1, 1, 0, 0, 0, 0, time.UTC).Unix()
		t1 := time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC).Unix()
		if mt := files[i].Modified; mt < t0 || mt > t1 {
			t.Errorf("Unrealistic modtime %d for test %d", mt, i)
		}
	}

	if !reflect.DeepEqual(ignores, correctIgnores) {
		t.Errorf("Incorrect ignores\n  %v\n  %v", correctIgnores, ignores)
	}
}

示例#14
文件: storage_psql_local_test.go 项目: kevinlovesing/cgrates

func TestPSQLRemStoredCdrs(t *testing.T) {
	if !*testLocal {
		return
	}
	cgrIdB1 := utils.Sha1("bbb1", time.Date(2013, 12, 7, 8, 42, 24, 0, time.UTC).String())
	if err := psqlDb.RemStoredCdrs([]string{cgrIdB1}); err != nil {
		t.Error(err.Error())
	}
	if storedCdrs, _, err := psqlDb.GetStoredCdrs(new(utils.CdrsFilter)); err != nil {
		t.Error(err.Error())
	} else if len(storedCdrs) != 7 {
		t.Error("Unexpected number of StoredCdrs returned: ", storedCdrs)
	}
	tm, _ := utils.ParseTimeDetectLayout("2013-11-08T08:42:20Z", "")
	cgrIdA1 := utils.Sha1("aaa1", tm.String())
	tm, _ = utils.ParseTimeDetectLayout("2013-11-08T08:42:22Z", "")
	cgrIdA2 := utils.Sha1("aaa2", tm.String())
	tm, _ = utils.ParseTimeDetectLayout("2013-11-07T08:42:24Z", "")
	cgrIdA3 := utils.Sha1("aaa3", tm.String())
	tm, _ = utils.ParseTimeDetectLayout("2013-11-07T08:42:21Z", "")
	cgrIdA4 := utils.Sha1("aaa4", tm.String())
	tm, _ = utils.ParseTimeDetectLayout("2013-11-07T08:42:25Z", "")
	cgrIdA5 := utils.Sha1("aaa5", tm.String())
	cgrIdB2 := utils.Sha1("bbb2", time.Date(2013, 12, 7, 8, 42, 24, 0, time.UTC).String())
	cgrIdB3 := utils.Sha1("bbb3", time.Date(2013, 12, 7, 8, 42, 24, 0, time.UTC).String())
	if err := psqlDb.RemStoredCdrs([]string{cgrIdA1, cgrIdA2, cgrIdA3, cgrIdA4, cgrIdA5,
		cgrIdB2, cgrIdB3}); err != nil {
		t.Error(err.Error())
	}
	if storedCdrs, _, err := psqlDb.GetStoredCdrs(new(utils.CdrsFilter)); err != nil {
		t.Error(err.Error())
	} else if len(storedCdrs) != 0 {
		t.Error("Unexpected number of StoredCdrs returned: ", storedCdrs)
	}
}

示例#15
文件: simple_reader_test.go 项目: henrypfhu/hprose-go

func TestSimpleReaderTime(t *testing.T) {
	b := new(bytes.Buffer)
	writer := NewWriter(b, true)
	now := time.Now()
	writer.Serialize(now)
	writer.Serialize(now)
	datetime := time.Date(2014, 1, 21, 12, 13, 14, 0, time.Local)
	writer.Serialize(datetime)
	date := time.Date(2014, 1, 21, 0, 0, 0, 0, time.Local)
	writer.Serialize(date)
	tim := time.Date(1, 1, 1, 19, 23, 19, 123000, time.UTC)
	writer.Serialize(tim)
	// go 1.1 has a bug, 1.2 fixed
	// writer.Serialize(datetime.String())
	reader := NewReader(b, true)
	var x time.Time
	var err error
	if err = reader.Unserialize(&x); err != nil {
		t.Error(err.Error())
	}
	if x != now {
		t.Error(x)
	}
	var p *time.Time
	if err = reader.Unserialize(&p); err != nil {
		t.Error(err.Error())
	}
	if *p != now {
		t.Error(*p)
		t.Error(now)
	}
	if err = reader.Unserialize(&x); err != nil {
		t.Error(err.Error())
	}
	if x != datetime {
		t.Error(x)
	}
	if err = reader.Unserialize(&x); err != nil {
		t.Error(err.Error())
	}
	if x != date {
		t.Error(x)
	}
	if err = reader.Unserialize(&x); err != nil {
		t.Error(err.Error())
	}
	if x != tim {
		t.Error(x)
	}
	// go 1.1 has a bug, 1.2 fixed
	/*
		if err = reader.Unserialize(&x); err != nil {
			t.Error(err.Error())
		}
		if x != datetime {
			t.Error(x)
			t.Error(datetime)
		}
	*/
}

示例#16
文件: ingester_test.go 项目: Tiger66639/skia-buildbot

func TestGetGSResultFileLocations(t *testing.T) {
	testutils.SkipIfShort(t)
	storage, err := storage.New(http.DefaultClient)
	assert.Nil(t, err)

	startTS := time.Date(2014, time.December, 10, 0, 0, 0, 0, time.UTC).Unix()
	endTS := time.Date(2014, time.December, 10, 23, 59, 59, 0, time.UTC).Unix()

	// TODO(stephana): Switch this to a dedicated test bucket, so we are not
	// in danger of removing it.
	resultFiles, err := getGSResultsFileLocations(startTS, endTS, storage, "chromium-skia-gm", "dm-json-v1")
	assert.Nil(t, err)

	// Read the expected list of files and compare them.
	content, err := ioutil.ReadFile("./testdata/filelist_dec_10.txt")
	assert.Nil(t, err)
	lines := strings.Split(strings.TrimSpace(string(content)), "\n")
	sort.Strings(lines)

	resultNames := make([]string, len(resultFiles))
	for idx, rf := range resultFiles {
		resultNames[idx] = rf.Name
	}
	sort.Strings(resultNames)
	assert.Equal(t, len(lines), len(resultNames))
	assert.Equal(t, lines, resultNames)
}

示例#17
文件: models_test.go 项目: exekias/juju

func (s *ModelsSuite) SetUpTest(c *gc.C) {
	s.FakeJujuXDGDataHomeSuite.SetUpTest(c)

	err := modelcmd.WriteCurrentController("fake")
	c.Assert(err, jc.ErrorIsNil)

	last1 := time.Date(2015, 3, 20, 0, 0, 0, 0, time.UTC)
	last2 := time.Date(2015, 3, 1, 0, 0, 0, 0, time.UTC)

	models := []base.UserModel{
		{
			Name:           "test-model1",
			Owner:          "[email protected]",
			UUID:           "test-model1-UUID",
			LastConnection: &last1,
		}, {
			Name:           "test-model2",
			Owner:          "[email protected]",
			UUID:           "test-model2-UUID",
			LastConnection: &last2,
		}, {
			Name:  "test-model3",
			Owner: "[email protected]",
			UUID:  "test-model3-UUID",
		},
	}
	s.api = &fakeModelMgrAPIClient{models: models}
	s.creds = &configstore.APICredentials{User: "[email protected]", Password: "password"}
}

示例#18
文件: ingester_test.go 项目: Tiger66639/skia-buildbot

func TestGetLocalResultFileLocations(t *testing.T) {
	testutils.SkipIfShort(t)

	err := testutils.DownloadTestDataArchive(t, TEST_DATA_STORAGE_PATH, TEST_DATA_DIR)
	assert.Nil(t, err)

	startTS := time.Date(2015, time.May, 5, 0, 0, 0, 0, time.UTC).Unix()
	endTS := time.Date(2015, time.May, 17, 23, 59, 59, 0, time.UTC).Unix()

	resultFiles, err := getLocalResultsFileLocations(startTS, endTS, filepath.Join(TEST_DATA_DIR, "nano-json-v1"))
	assert.Nil(t, err)

	// Read the expected list of files and compare them.
	content, err := ioutil.ReadFile("./testdata/local_ingest_files.txt")
	assert.Nil(t, err)
	lines := strings.Split(strings.TrimSpace(string(content)), "\n")
	sort.Strings(lines)

	resultNames := make([]string, len(resultFiles))
	for idx, rf := range resultFiles {
		resultNames[idx] = rf.Name
	}
	sort.Strings(resultNames)
	assert.Equal(t, len(lines), len(resultNames))
	assert.Equal(t, lines, resultNames)
}

示例#19
文件: now_test.go 项目: sivagollapalli/now

func TestMondayAndSunday(t *testing.T) {
	n := time.Date(2013, 11, 19, 17, 51, 49, 123456789, time.UTC)
	n2 := time.Date(2013, 11, 24, 17, 51, 49, 123456789, time.UTC)

	if New(n).Monday().Format(format) != "2013-11-18 00:00:00" {
		t.Errorf("Monday")
	}

	if New(n2).Monday().Format(format) != "2013-11-18 00:00:00" {
		t.Errorf("Monday")
	}

	if New(n).Sunday().Format(format) != "2013-11-24 00:00:00" {
		t.Errorf("Sunday")
	}

	if New(n2).Sunday().Format(format) != "2013-11-24 00:00:00" {
		t.Errorf("Sunday")
	}

	if New(n).EndOfSunday().Format(format) != "2013-11-24 23:59:59.999999999" {
		t.Errorf("Sunday")
	}

	if New(n).BeginningOfWeek().Format(format) != "2013-11-17 00:00:00" {
		t.Errorf("BeginningOfWeek, FirstDayMonday")
	}

	FirstDayMonday = true
	if New(n).BeginningOfWeek().Format(format) != "2013-11-18 00:00:00" {
		t.Errorf("BeginningOfWeek, FirstDayMonday")
	}
}

示例#20
文件: json_test.go 项目: RomainVabre/origin

func TestFastMarshalJSON(t *testing.T) {
	aTime := time.Date(2015, 5, 29, 11, 1, 2, 3, time.UTC)
	json, err := FastMarshalJSON(aTime)
	if err != nil {
		t.Fatal(err)
	}
	expected := "\"2015-05-29T11:01:02.000000003Z\""
	if json != expected {
		t.Fatalf("Expected %v, got %v", expected, json)
	}

	location, err := time.LoadLocation("Europe/Paris")
	if err != nil {
		t.Fatal(err)
	}
	aTime = time.Date(2015, 5, 29, 11, 1, 2, 3, location)
	json, err = FastMarshalJSON(aTime)
	if err != nil {
		t.Fatal(err)
	}
	expected = "\"2015-05-29T11:01:02.000000003+02:00\""
	if json != expected {
		t.Fatalf("Expected %v, got %v", expected, json)
	}
}

示例#21
文件: holidays_test.go 项目: gophergala2016/festivus

func TestMidnight(t *testing.T) {
	in := time.Date(2016, 1, 23, 1, 2, 3, 4, time.UTC)
	want := time.Date(2016, 1, 23, 0, 0, 0, 0, time.UTC)
	if got := midnight(in); got != want {
		t.Errorf("midnight(%v) = %v; want %v", in, got, want)
	}
}

示例#22
文件: change_test.go 项目: dholbach/snappy

func (cs *clientSuite) TestClientAbort(c *check.C) {
	cs.rsp = `{"type": "sync", "result": {
  "id":   "uno",
  "kind": "foo",
  "summary": "...",
  "status": "Hold",
  "ready": true,
  "spawn-time": "2016-04-21T01:02:03Z",
  "ready-time": "2016-04-21T01:02:04Z"
}}`

	chg, err := cs.cli.Abort("uno")
	c.Assert(err, check.IsNil)
	c.Check(cs.req.Method, check.Equals, "POST")
	c.Check(chg, check.DeepEquals, &client.Change{
		ID:      "uno",
		Kind:    "foo",
		Summary: "...",
		Status:  "Hold",
		Ready:   true,

		SpawnTime: time.Date(2016, 04, 21, 1, 2, 3, 0, time.UTC),
		ReadyTime: time.Date(2016, 04, 21, 1, 2, 4, 0, time.UTC),
	})

	body, err := ioutil.ReadAll(cs.req.Body)
	c.Assert(err, check.IsNil)

	c.Assert(string(body), check.Equals, "{\"action\":\"abort\"}\n")
}

示例#23
文件: callcost_test.go 项目: eloycoto/cgrates

func TestSingleResultMerge(t *testing.T) {
	t1 := time.Date(2012, time.February, 2, 17, 0, 0, 0, time.UTC)
	t2 := time.Date(2012, time.February, 2, 17, 1, 0, 0, time.UTC)
	cd := &CallDescriptor{Direction: utils.OUT, Category: "0", Tenant: "vdf", Subject: "rif", Destination: "0256", TimeStart: t1, TimeEnd: t2}
	cc1, _ := cd.getCost()
	if cc1.Cost != 61 {
		t.Errorf("expected 61 was %v", cc1.Cost)
	}
	t1 = time.Date(2012, time.February, 2, 17, 1, 0, 0, time.UTC)
	t2 = time.Date(2012, time.February, 2, 17, 2, 0, 0, time.UTC)
	cd = &CallDescriptor{Direction: utils.OUT, Category: "0", Tenant: "vdf", Subject: "rif", Destination: "0256", TimeStart: t1, TimeEnd: t2}
	cc2, _ := cd.GetCost()
	if cc2.Cost != 61 {
		t.Errorf("expected 60 was %v", cc2.Cost)
	}
	cc1.Merge(cc2)
	if len(cc1.Timespans) != 2 || cc1.Timespans[0].GetDuration().Seconds() != 60 || cc1.Timespans[1].GetDuration().Seconds() != 60 {
		for _, ts := range cc1.Timespans {
			t.Logf("TS: %+v", ts)
		}
		t.Error("wrong resulted timespan: ", len(cc1.Timespans), cc1.Timespans[0].GetDuration().Seconds())
	}
	if cc1.Cost != 122 {
		t.Errorf("Exdpected 120 was %v", cc1.Cost)
	}
	d := cc1.UpdateRatedUsage()
	if d != 2*time.Minute || cc1.RatedUsage != 120.0 {
		t.Errorf("error updating rating usage: %v, %v", d, cc1.RatedUsage)
	}
}

示例#24
文件: change_test.go 项目: dholbach/snappy

func (cs *clientSuite) TestClientChange(c *check.C) {
	cs.rsp = `{"type": "sync", "result": {
  "id":   "uno",
  "kind": "foo",
  "summary": "...",
  "status": "Do",
  "ready": false,
  "spawn-time": "2016-04-21T01:02:03Z",
  "ready-time": "2016-04-21T01:02:04Z",
  "tasks": [{"kind": "bar", "summary": "...", "status": "Do", "progress": {"done": 0, "total": 1}, "spawn-time": "2016-04-21T01:02:03Z", "ready-time": "2016-04-21T01:02:04Z"}]
}}`

	chg, err := cs.cli.Change("uno")
	c.Assert(err, check.IsNil)
	c.Check(chg, check.DeepEquals, &client.Change{
		ID:      "uno",
		Kind:    "foo",
		Summary: "...",
		Status:  "Do",
		Tasks: []*client.Task{{
			Kind:      "bar",
			Summary:   "...",
			Status:    "Do",
			Progress:  client.TaskProgress{Done: 0, Total: 1},
			SpawnTime: time.Date(2016, 04, 21, 1, 2, 3, 0, time.UTC),
			ReadyTime: time.Date(2016, 04, 21, 1, 2, 4, 0, time.UTC),
		}},

		SpawnTime: time.Date(2016, 04, 21, 1, 2, 3, 0, time.UTC),
		ReadyTime: time.Date(2016, 04, 21, 1, 2, 4, 0, time.UTC),
	})
}

示例#25
文件: callcost_test.go 项目: eloycoto/cgrates

func TestMultipleInputLeftMerge(t *testing.T) {
	t1 := time.Date(2012, time.February, 2, 17, 59, 0, 0, time.UTC)
	t2 := time.Date(2012, time.February, 2, 18, 01, 0, 0, time.UTC)
	cd := &CallDescriptor{Direction: utils.OUT, Category: "0", Tenant: "vdf", Subject: "rif", Destination: "0256", TimeStart: t1, TimeEnd: t2}
	cc1, _ := cd.getCost()
	//log.Printf("Timing: %+v", cc1.Timespans[1].RateInterval.Timing)
	//log.Printf("Rating: %+v", cc1.Timespans[1].RateInterval.Rating)
	if cc1.Cost != 91 {
		t.Errorf("expected 91 was %v", cc1.Cost)
	}
	/*t1 = time.Date(2012, time.February, 2, 18, 01, 0, 0, time.UTC)
	t2 = time.Date(2012, time.February, 2, 18, 02, 0, 0, time.UTC)
	cd = &CallDescriptor{Direction: utils.OUT, TOR: "0", Tenant: "vdf", Subject: "rif", Destination: "0256", TimeStart: t1, TimeEnd: t2}
	cc2, _ := cd.getCost()
	if cc2.Cost != 30 {
		t.Errorf("expected 30 was %v", cc2.Cost)
	}
	cc1.Merge(cc2)
	if len(cc1.Timespans) != 2 || cc1.Timespans[1].GetDuration().Seconds() != 120 {
		t.Error("wrong resulted timespan: ", len(cc1.Timespans))
	}
	if cc1.Cost != 120 {
		t.Errorf("Exdpected 120 was %v", cc1.Cost)
	}*/
}

示例#26
文件: instrumental_test.go 项目: miketonks/telegraf

func TestWrite(t *testing.T) {
	var wg sync.WaitGroup
	wg.Add(1)
	go TCPServer(t, &wg)
	// Give the fake TCP server some time to start:
	time.Sleep(time.Millisecond * 100)

	i := Instrumental{
		Host:     "127.0.0.1",
		ApiToken: "abc123token",
		Prefix:   "my.prefix",
	}
	i.Connect()

	// Default to gauge
	m1, _ := telegraf.NewMetric(
		"mymeasurement",
		map[string]string{"host": "192.168.0.1"},
		map[string]interface{}{"myfield": float64(3.14)},
		time.Date(2010, time.November, 10, 23, 0, 0, 0, time.UTC),
	)
	m2, _ := telegraf.NewMetric(
		"mymeasurement",
		map[string]string{"host": "192.168.0.1", "metric_type": "set"},
		map[string]interface{}{"value": float64(3.14)},
		time.Date(2010, time.November, 10, 23, 0, 0, 0, time.UTC),
	)

	// Simulate a connection close and reconnect.
	metrics := []telegraf.Metric{m1, m2}
	i.Write(metrics)
	i.Close()

	// Counter and Histogram are increments
	m3, _ := telegraf.NewMetric(
		"my_histogram",
		map[string]string{"host": "192.168.0.1", "metric_type": "histogram"},
		map[string]interface{}{"value": float64(3.14)},
		time.Date(2010, time.November, 10, 23, 0, 0, 0, time.UTC),
	)
	// We will drop metrics that simply won't be accepted by Instrumental
	m4, _ := telegraf.NewMetric(
		"bad_values",
		map[string]string{"host": "192.168.0.1", "metric_type": "counter"},
		map[string]interface{}{"value": "\" 3:30\""},
		time.Date(2010, time.November, 10, 23, 0, 0, 0, time.UTC),
	)
	m5, _ := telegraf.NewMetric(
		"my_counter",
		map[string]string{"host": "192.168.0.1", "metric_type": "counter"},
		map[string]interface{}{"value": float64(3.14)},
		time.Date(2010, time.November, 10, 23, 0, 0, 0, time.UTC),
	)

	metrics = []telegraf.Metric{m3, m4, m5}
	i.Write(metrics)

	wg.Wait()
	i.Close()
}

示例#27
文件: csv_test.go 项目: eloycoto/cgrates

func TestCsvPairToRecord(t *testing.T) {
	eRecord := []string{"INVITE", "2daec40c", "548625ac", "[email protected]:0:0:0:0:0:0:0", "200", "OK", "1436454408", "*prepaid", "1001", "1002", "", "3401:2069362475", "2"}
	invPr := &UnpairedRecord{Method: "INVITE", Timestamp: time.Date(2015, 7, 9, 15, 6, 48, 0, time.UTC),
		Values: []string{"INVITE", "2daec40c", "548625ac", "[email protected]:0:0:0:0:0:0:0", "200", "OK", "1436454408", "*prepaid", "1001", "1002", "", "3401:2069362475"}}
	byePr := &UnpairedRecord{Method: "BYE", Timestamp: time.Date(2015, 7, 9, 15, 6, 50, 0, time.UTC),
		Values: []string{"BYE", "2daec40c", "548625ac", "[email protected]:0:0:0:0:0:0:0", "200", "OK", "1436454410", "", "", "", "", "3401:2069362475"}}
	if rec, err := pairToRecord(invPr, byePr); err != nil {
		t.Error(err)
	} else if !reflect.DeepEqual(eRecord, rec) {
		t.Errorf("Expected: %+v, received: %+v", eRecord, rec)
	}
	if rec, err := pairToRecord(byePr, invPr); err != nil {
		t.Error(err)
	} else if !reflect.DeepEqual(eRecord, rec) {
		t.Errorf("Expected: %+v, received: %+v", eRecord, rec)
	}
	if _, err := pairToRecord(byePr, byePr); err == nil || err.Error() != "MISSING_INVITE" {
		t.Error(err)
	}
	if _, err := pairToRecord(invPr, invPr); err == nil || err.Error() != "MISSING_BYE" {
		t.Error(err)
	}
	byePr.Values = []string{"BYE", "2daec40c", "548625ac", "[email protected]:0:0:0:0:0:0:0", "200", "OK", "1436454410", "", "", "", "3401:2069362475"} // Took one value out
	if _, err := pairToRecord(invPr, byePr); err == nil || err.Error() != "INCONSISTENT_VALUES_LENGTH" {
		t.Error(err)
	}
}

示例#28
文件: graphite_test.go 项目: bwolf/telegraf

func TestGraphiteTags(t *testing.T) {
	m1, _ := telegraf.NewMetric(
		"mymeasurement",
		map[string]string{"host": "192.168.0.1"},
		map[string]interface{}{"value": float64(3.14)},
		time.Date(2010, time.November, 10, 23, 0, 0, 0, time.UTC),
	)
	m2, _ := telegraf.NewMetric(
		"mymeasurement",
		map[string]string{"host": "192.168.0.1", "afoo": "first", "bfoo": "second"},
		map[string]interface{}{"value": float64(3.14)},
		time.Date(2010, time.November, 10, 23, 0, 0, 0, time.UTC),
	)
	m3, _ := telegraf.NewMetric(
		"mymeasurement",
		map[string]string{"afoo": "first", "bfoo": "second"},
		map[string]interface{}{"value": float64(3.14)},
		time.Date(2010, time.November, 10, 23, 0, 0, 0, time.UTC),
	)

	tags1 := buildTags(m1)
	tags2 := buildTags(m2)
	tags3 := buildTags(m3)

	assert.Equal(t, "192_168_0_1", tags1)
	assert.Equal(t, "192_168_0_1.first.second", tags2)
	assert.Equal(t, "first.second", tags3)
}

示例#29
文件: github_test.go 项目: MustWin/go-github

func TestRateLimits(t *testing.T) {
	setup()
	defer teardown()

	mux.HandleFunc("/rate_limit", func(w http.ResponseWriter, r *http.Request) {
		if m := "GET"; m != r.Method {
			t.Errorf("Request method = %v, want %v", r.Method, m)
		}
		fmt.Fprint(w, `{"resources":{
			"core": {"limit":2,"remaining":1,"reset":1372700873},
			"search": {"limit":3,"remaining":2,"reset":1372700874}
		}}`)
	})

	rate, _, err := client.RateLimits()
	if err != nil {
		t.Errorf("RateLimits returned error: %v", err)
	}

	want := &RateLimits{
		Core: &Rate{
			Limit:     2,
			Remaining: 1,
			Reset:     Timestamp{time.Date(2013, 7, 1, 17, 47, 53, 0, time.UTC).Local()},
		},
		Search: &Rate{
			Limit:     3,
			Remaining: 2,
			Reset:     Timestamp{time.Date(2013, 7, 1, 17, 47, 54, 0, time.UTC).Local()},
		},
	}
	if !reflect.DeepEqual(rate, want) {
		t.Errorf("RateLimits returned %+v, want %+v", rate, want)
	}
}

示例#30
文件: states_test.go 项目: henryanand/vitess

func TestOneState(t *testing.T) {

	location, _ := time.LoadLocation("") // UTC

	// 2012/12/12 12:00:00 UTC
	now := time.Date(2012, 12, 12, 12, 0, 0, 0, location)
	s := NewStates("", []string{"Init", "Open", "Closed"}, now, 0)

	// get the value a bit later
	now = time.Date(2012, 12, 12, 12, 0, 25, 0, location)
	result := s.stringAt(now)
	if result != "{\"Current\": \"Init\", \"DurationInit\": 25000000000, \"TransitionIntoInit\": 0, \"DurationOpen\": 0, \"TransitionIntoOpen\": 0, \"DurationClosed\": 0, \"TransitionIntoClosed\": 0}" {
		t.Errorf("unexpected result: %v", result)
	}

	// get the value a bit later again
	now = time.Date(2012, 12, 12, 12, 10, 0, 0, location)
	result = s.stringAt(now)
	if result != "{\"Current\": \"Init\", \"DurationInit\": 600000000000, \"TransitionIntoInit\": 0, \"DurationOpen\": 0, \"TransitionIntoOpen\": 0, \"DurationClosed\": 0, \"TransitionIntoClosed\": 0}" {
		t.Errorf("unexpected result: %v", result)
	}

	// get the value a bit later again
	now = time.Date(2012, 12, 12, 12, 11, 0, 0, location)
	result = s.stringAt(now)
	if result != "{\"Current\": \"Init\", \"DurationInit\": 660000000000, \"TransitionIntoInit\": 0, \"DurationOpen\": 0, \"TransitionIntoOpen\": 0, \"DurationClosed\": 0, \"TransitionIntoClosed\": 0}" {
		t.Errorf("unexpected result: %v", result)
	}
}

展开阅读全文