func Test_PT1Recorder_Retry(t *testing.T) {
	assert := wcg.NewAssert(t)

	iepg := &pt.IEPG{}
	iepg.ProgramTitle = "test"
	iepg.StartAt = lib.Now()
	iepg.EndAt = lib.Now().Add(3 * time.Second)
	cfg := newPT1RecorderConfig()
	cfg.Recpt1Path = "./fixtures/pt1commands/fail.sh"
	notifier := &testNotifier{}
	recorder := NewPT1Recorder(iepg, cfg, notifier)
	go recorder.Start()
	time.Sleep(500 * time.Millisecond)
	stats := recorder.GetStats()
	assert.EqInt(
		int(pt.IEPGProcessing), int(stats.Status),
		"recorder status should be pt.IEPGCanceled",
	)
	// change the recpt1path to the correct one to succeed.
	cfg.Recpt1Path = "./fixtures/pt1commands/simple.sh"
	time.Sleep(2800 * time.Millisecond)

	assert.EqInt(
		int(pt.IEPGCompleted), int(stats.Status),
		"recorder status should be pt.IEPGCompleted",
	)
	assert.EqInt(3, int(stats.EndAt.Sub(stats.StartAt).Seconds()), "recorder should be cancled in about 3 seconds (actual=%f)", stats.EndAt.Sub(stats.StartAt).Seconds())
	assert.GtInt(0, stats.Retries, "recorder should retry the command")
	assert.OK(notifier.StartNotified, "notifier should be notified on start.")
	assert.OK(notifier.EndNotified, "notifier should be notified on end.")
}
Exemple #2
0
func Test_Do_MaxRetries(t *testing.T) {
	assert := wcg.NewAssert(t)
	var interval = Interval(100 * time.Millisecond)

	var i = 0
	var max = MaxRetries(15)
	err := Do(func() error {
		i++
		if i < 10 {
			return fmt.Errorf("Need retry")
		}
		return nil
	}, interval, max)

	assert.Nil(err)
	assert.EqInt(10, i)

	i = 0
	max = MaxRetries(3)
	err = Do(func() error {
		i++
		if i < 10 {
			return fmt.Errorf("Need retry")
		}
		return nil
	}, interval, max)
	assert.NotNil(err)
	assert.OK(i == 3)
}
func TestSessionSupport(t *testing.T) {
	assert := wcg.NewAssert(t)
	// default configugration
	cfg := SessionConfigIni
	load, save := SessionSupport()
	r, _ := http.NewRequest("GET", "http://example.com/foo", nil)
	req := wcg.NewRequest(r)
	w := httptest.NewRecorder()
	res := wcg.NewResponse(w, req)
	load.Process(res, req)
	assert.NotNil(req.Session, "req.Session with SessionSupport")
	// application set the sessoin data.
	req.Session.Set("foo", "bar")

	// Check set-cookie header on response, which should include signed session id.
	c := wcg.ParseCookie(w.Header().Get("set-cookie"))
	assert.EqStr(cfg.CookieName, c.Name, "Issued cookie name")
	assert.NotZero(c.Value, "Issued cookie value")

	// Run save handler.
	save.Process(res, req)

	// Another request is coming with the same session id.
	r, _ = http.NewRequest("GET", "http://example.com/foo", nil)
	r.Header.Set("cookie", c.String())
	req = wcg.NewRequest(r)
	w = httptest.NewRecorder()
	res = wcg.NewResponse(w, req)
	load.Process(res, req)
	val, _ := req.Session.Get("foo")
	assert.EqStr("bar", val, "Stored value check")
}
func TestSessionSupport_Expire(t *testing.T) {
	assert := wcg.NewAssert(t)
	// default configugration
	cfg := &SessionConfig{
		StoreFactory: nil,
		Key:          "wcgsess",
		MaxAge:       1, // 3 seconds
		CookieName:   "wcgsess",
		Domain:       "",
		HTTPOnly:     true,
		Path:         "/",
	}
	load, save := SessionSupportWithConfig(cfg)
	r, _ := http.NewRequest("GET", "http://example.com/foo", nil)
	req := wcg.NewRequest(r)
	w := httptest.NewRecorder()
	res := wcg.NewResponse(w, req)
	load.Process(res, req)
	req.Session.Set("foo", "bar")
	save.Process(res, req)
	sid1 := req.Session.ID

	time.Sleep(1 * time.Second)
	// Another request is coming with the same cookie.
	c := wcg.ParseCookie(w.Header().Get("set-cookie"))

	r, _ = http.NewRequest("GET", "http://example.com/foo", nil)
	r.Header.Set("cookie", c.String())
	req = wcg.NewRequest(r)
	w = httptest.NewRecorder()
	res = wcg.NewResponse(w, req)
	load.Process(res, req)
	sid2 := req.Session.ID
	assert.Not(sid1 == sid2, "Keep session")
}
Exemple #5
0
func Test_parseUserFeed(t *testing.T) {
	assert := wcg.NewAssert(t)
	f, err := os.Open("./fixtures/Test_parseUserFeed.xml")
	assert.Nil(err, "Open fixture file")
	defer f.Close()
	albums, err := parseUserFeed(f)
	assert.Nil(err, "parseAlbums should return no error.")
	assert.EqInt(2, len(albums), "len(albums)")
	assert.EqStr("1000000487409559", albums[0].ID, "albums[0].ID")
	assert.EqStr("自動バックアップ", albums[0].Title, "albums[0].Title")
	assert.EqStr("109784491874587409559", albums[0].AuthorID, "albums[0].AuthorID")
	assert.EqStr("Yohei Sasaki", albums[0].AuthorName, "albums[0].AuthorName")
	publishedAt, _ := wcg.ParseDateTime("2015-11-29T11:03:42.000Z")
	updatedAt, _ := wcg.ParseDateTime("2015-11-29T15:32:17.582Z")
	assert.EqTime(publishedAt, *albums[0].PublishedAt, "albums[0].PublishedAt")
	assert.EqTime(updatedAt, *albums[0].UpdatedAt, "albums[0].UpdatedAt")

	assert.EqStr("6173825975323480657", albums[1].ID, "albums[0].ID")
	assert.EqStr("2015/07/21", albums[1].Title, "albums[0].Title")
	assert.EqStr("109784491874587409559", albums[1].AuthorID, "albums[0].AuthorID")
	assert.EqStr("Yohei Sasaki", albums[1].AuthorName, "albums[0].AuthorName")
	publishedAt, _ = wcg.ParseDateTime("2015-07-21T05:17:55.000Z")
	updatedAt, _ = wcg.ParseDateTime("2015-07-21T05:38:48.016Z")
	assert.EqTime(publishedAt, *albums[1].PublishedAt, "albums[0].PublishedAt")
	assert.EqTime(updatedAt, *albums[1].UpdatedAt, "albums[0].UpdatedAt")
}
func TestMax(t *testing.T) {
	type TestObject struct {
		Str   string
		Int   int
		Float float32
		Array []string
	}
	assert := wcg.NewAssert(t)
	obj := &TestObject{}
	v := NewObjectValidator()
	v.Field("Str").Max(1)
	v.Field("Int").Max(1)
	v.Field("Float").Max(1)
	v.Field("Array").Max(1)

	obj.Str = "Foo"
	obj.Int = 5
	obj.Float = 5
	obj.Array = []string{"a", "b", "c", "d"}
	result := v.Eval(obj)
	assert.NotNil(result.Errors["Str"], "ValidationError should claims on 'Str'")
	assert.NotNil(result.Errors["Int"], "ValidationError should claims on 'Int'")
	assert.NotNil(result.Errors["Float"], "ValidationError should claims on 'Float'")
	assert.NotNil(result.Errors["Array"], "ValidationError should claims on 'Arrau'")
	assert.EqStr("must be less than or equal to 1", result.Errors["Str"][0].String(), "ValidationError Error message")
	assert.EqStr("must be less than or equal to 1", result.Errors["Int"][0].String(), "ValidationError Error message")
	assert.EqStr("must be less than or equal to 1", result.Errors["Float"][0].String(), "ValidationError Error message")
	assert.EqStr("must be less than or equal to 1", result.Errors["Array"][0].String(), "ValidationError Error message")

	obj.Str = "F"
	obj.Int = 1
	obj.Float = 1
	obj.Array = []string{"a"}
	assert.Nil(v.Eval(obj), "Eval(obj) should return nil when validation passed.")
}
Exemple #7
0
func Test_CollectFilesystemStats(t *testing.T) {
	assert := wcg.NewAssert(t)

	stats, err := CollectFileSystemStats("./fixtures/df.sh")
	assert.Nil(err, "CollectFileSystemStats should not return an error")
	assert.EqInt(2, len(stats), "CollectFileSystemStats should return 2 stats")
}
Exemple #8
0
func TestIOLogSinkFormat(t *testing.T) {
	assert := wcg.NewAssert(t)
	record := NewTestRecord()
	storage := NewTestLogStorage()
	s := NewIOLogSink("", storage, false)
	s.Write(record)
	assert.NotZero(len(storage.GetLines()), "sink.Write should write a log record")
	line := storage.GetLines()[0]
	expect := fmt.Sprintf(
		"1984/09/22 12:01:28 +0000 [TRACE] [1|user1|%s|%s] This is a test (sourec.go#1)",
		record.SessionID.Shorten(),
		record.RequestID.Shorten(),
	)
	assert.EqStr(expect, line, "LogRecord format")

	// custom format
	storage = NewTestLogStorage()
	s = NewIOLogSink("$TIMESTAMP $INVALIDVAR $TEXT", storage, false)
	s.Write(record)
	assert.NotZero(len(storage.GetLines()), "sink.Write should write a log record")

	line = storage.GetLines()[0]
	expect = "1984/09/22 12:01:28 +0000 !UNDEFINED This is a test"
	assert.EqStr(expect, line, "LogRecord format")

	// Data record case.
	storage = NewTestLogStorage()
	s = NewIOLogSink("", storage, false)
	record.Data = wcg.DataBag{}
	s.Write(record)
	assert.Zero(len(storage.GetLines()), "sink.Write should not write anything if the record has DataBag")
}
Exemple #9
0
func Test_Do_Until(t *testing.T) {
	assert := wcg.NewAssert(t)
	var interval = Interval(100 * time.Millisecond)

	var i = 0
	var ut = time.Now().Add(3 * time.Second)
	var until = Until(ut)
	err := Do(func() error {
		i++
		if i < 10 {
			return fmt.Errorf("Need retry")
		}
		return nil
	}, interval, until)

	assert.Nil(err)
	assert.OK(time.Now().Before(ut))
	assert.EqInt(10, i)

	i = 0
	ut = time.Now().Add(500 * time.Millisecond)
	until = Until(ut)
	err = Do(func() error {
		i++
		if i < 10 {
			return fmt.Errorf("Need retry")
		}
		return nil
	}, interval, until)
	assert.NotNil(err)
	assert.OK(time.Now().After(ut))
	assert.OK(i > 1)
	assert.OK(i < 10)
}
func TestMatch(t *testing.T) {
	type TestObject struct {
		Str   string
		Bytes []byte
	}
	assert := wcg.NewAssert(t)
	obj := &TestObject{}
	v := NewObjectValidator()
	v.Field("Str").Match("a+")
	v.Field("Bytes").Match("a+")
	result := v.Eval(obj)
	assert.NotNil(result.Errors["Str"], "ValidationError should claims on 'Str'")
	assert.NotNil(result.Errors["Bytes"], "ValidationError should claims on 'Bytes'")
	assert.EqStr("not match with 'a+'", result.Errors["Str"][0].String(), "ValidationError Error message")
	assert.EqStr("not match with 'a+'", result.Errors["Bytes"][0].String(), "ValidationError Error message")

	obj.Str = "bbb"
	obj.Bytes = []byte(obj.Str)
	result = v.Eval(obj)
	assert.NotNil(result, "Eval(obj) should return ValidationError")
	assert.NotNil(result.Errors["Str"], "ValidationError should claims on 'Str'")
	assert.NotNil(result.Errors["Bytes"], "ValidationError should claims on 'Bytes'")
	assert.EqStr("not match with 'a+'", result.Errors["Str"][0].String(), "ValidationError Error message")
	assert.EqStr("not match with 'a+'", result.Errors["Bytes"][0].String(), "ValidationError Error message")

	obj.Str = "aaa"
	obj.Bytes = []byte(obj.Str)
	assert.Nil(v.Eval(obj), "Eval(obj) should return nil when validation passed.")
}
func Test_PT1Recorder_ShortenTime(t *testing.T) {
	assert := wcg.NewAssert(t)

	iepg := &pt.IEPG{}
	iepg.ProgramTitle = "test"
	iepg.StartAt = lib.Now()
	iepg.EndAt = lib.Now().Add(10 * time.Second)
	iepg2 := &pt.IEPG{}
	iepg2.ProgramTitle = "test"
	iepg2.StartAt = iepg.StartAt
	iepg2.EndAt = iepg.EndAt.Add(-8 * time.Second)
	notifier := &testNotifier{}
	recorder := NewPT1Recorder(iepg, newPT1RecorderConfig(), notifier)
	go recorder.Start()
	stats := recorder.GetStats()

	time.Sleep(500 * time.Millisecond)
	recorder.Update(iepg2)

	time.Sleep(500 * time.Millisecond)
	assert.EqInt(
		int(pt.IEPGProcessing), int(stats.Status),
		"recorder status should be pt.IEPGCanceled",
	)

	time.Sleep(2 * time.Second)
	assert.EqInt(
		int(pt.IEPGCompleted), int(stats.Status),
		"recorder status should be pt.IEPGCompleted",
	)
	assert.EqInt(2, int(stats.EndAt.Sub(stats.StartAt).Seconds()), "recorder should be cancled in about 4 seconds (actual=%f)", stats.EndAt.Sub(stats.StartAt).Seconds())
	assert.OK(notifier.StartNotified, "notifier should be notified on start.")
	assert.OK(notifier.EndNotified, "notifier should be notified on end.")
}
func TestObjectValidation(t *testing.T) {
	type TestObject struct {
		Str1 string
		Str2 string
	}
	assert := wcg.NewAssert(t)
	obj := &TestObject{}
	v := NewObjectValidator()
	v.Func(func(v interface{}) *FieldValidationError {
		obj := v.(*TestObject)
		if obj.Str1 == obj.Str2 {
			return NewFieldValidationError(
				"Same!!", nil,
			)
		}
		return nil
	})

	obj.Str1 = "foo"
	obj.Str2 = "foo"
	result := v.Eval(obj)
	assert.NotNil(result.Errors["."], "ValidationError should claims on 'Str'")
	assert.EqStr("Same!!", result.Errors["."][0].String(), "ValidationError Error message")

	obj.Str2 = "bar"
	assert.Nil(v.Eval(obj), "Eval(obj) should return nil when validation passed.")
}
Exemple #13
0
func Test_Agent_Recorder_Cancel(t *testing.T) {
	var agent *Agent
	var r Recorder
	assert := wcg.NewAssert(t)
	now, _ := wcg.ParseDateTime("2016-05-15T16:05:00Z")

	httptest.StartMockServer(func(mock *httptest.MockServer) {
		mock.Routes().GET("/api/intern/pt/iepg/records/", middleware.ServeFile("./fixtures/mocks/agent_tests.json"))
		agent = NewAgent(mock.BaseURL(), "test-token", nil)
		agent.recorderFactory = func(iepg *pt.IEPG) Recorder {
			return NewMockRecorder(iepg)
		}
		lib.TemporarySetNow(now, func() {
			agent.RunOnce()
			time.Sleep(100 * time.Millisecond)
			r = agent.recorders["200171201605160105"]
			assert.EqInt(1, len(agent.recorders), "agent should have a recorder thread.")
			assert.EqInt(int(pt.IEPGProcessing), int(r.GetStats().Status), "the recorder status should be pt.IEPGProcessing.")
		})
	})

	httptest.StartMockServer(func(mock *httptest.MockServer) {
		// preparation for dummy entry
		mock.Routes().GET("/api/intern/pt/iepg/records/", middleware.ServeFile("./fixtures/mocks/agent_tests_no_data.json"))
		agent.subscriber = NewSubscriber(mock.BaseURL(), "test-token")
		lib.TemporarySetNow(now, func() {
			agent.RunOnce()
			time.Sleep(100 * time.Millisecond)
			assert.EqInt(0, len(agent.recorders), "agent should have no recorder thread.")
			assert.EqInt(int(r.GetStats().Status), int(pt.IEPGCanceled), "the recorder status should be pt.IEPGPRocessing.")
		})
	})
}
Exemple #14
0
func Test_parsePhotoFeed(t *testing.T) {
	assert := wcg.NewAssert(t)
	f, err := os.Open("./fixtures/Test_parsePhotoFeed.xml")
	assert.Nil(err, "Open fixture file")
	defer f.Close()
	media, err := parsePhotoFeed(f)
	assert.Nil(err, "parseMedia should return no error.")
	assert.EqInt(4, len(media.Contents), "len(media[0].Contents)")
}
Exemple #15
0
func Test_TodayInLocation(t *testing.T) {
	assert := wcg.NewAssert(t)
	TemporarySetNow(nowValue, func() {
		now := TodayInLocation(JST)
		assert.EqInt(2015, now.Year(), "Year")
		assert.EqInt(2, int(now.Month()), "Month")
		assert.EqInt(13, now.Day(), "Day")
		assert.EqInt(0, now.Hour(), "Hour")
		assert.EqInt(0, now.Minute(), "Mintues")
		assert.EqStr("JST", now.Location().String(), "Location")
	})
}
Exemple #16
0
func Test_Run_With_404(t *testing.T) {
	assert := wcg.NewAssert(t)
	httptest.StartMockServer(func(s *httptest.MockServer) {
		url := s.BaseURL()

		runner := &Runner{
			Crawler: &testCrawlerImpl{url},
		}
		_, err := runner.Run(url)
		assert.NotNil(err)
	})
}
Exemple #17
0
func Test_SliceParallel(t *testing.T) {
	assert := wcg.NewAssert(t)
	var a = []int{0, 1, 2, 3, 4}
	assert.Nil(
		ParallelSlice(a, func(i int, v int) error {
			a[i] = v + 1
			return nil
		}),
	)
	for i := range a {
		assert.EqInt(i+1, a[i])
	}
}
Exemple #18
0
func Test_CollectSystemStats(t *testing.T) {
	assert := wcg.NewAssert(t)

	stats, err := CollectSystemMetric("./fixtures/sadf.sh")
	assert.Nil(err, "CollectSystemStats should not return an error")
	assert.EqInt(52, len(stats), "CollectSystemStats should return 52 stats")
	assert.EqInt(2016, stats[0].Timestamp.Year(), "timestamp.Year")
	assert.EqInt(6, int(stats[0].Timestamp.Month()), "timestamp.Month")
	assert.EqInt(8, stats[0].Timestamp.Day(), "timestamp.Day")
	assert.EqInt(9, stats[0].Timestamp.Hour(), "timestamp.Hour")
	assert.EqInt(36, stats[0].Timestamp.Minute(), "timestamp.Minute")
	assert.EqInt(1, stats[0].Timestamp.Second(), "timestamp.Second")
}
Exemple #19
0
func TestDatastoreFixture(t *testing.T) {
	filepath := mkTempfile(`[{
    "_kind": "FixtureKind",
    "_key": "key1",
    "IntValue": 10,
    "FloatValue": 2.4,
    "BoolValue": true,
    "StringValue": "foobar",
    "BytesValue": "[]bytesfoobar",
    "DateTimeValue": "2014-01-02T14:02:50Z",
    "DateValue": "2014-01-02",
    "Slice": ["a", "b", "c"],
    "Struct": {
      "Foo": "bar"
    }
  },{
    "_kind": "FixtureKind",
    "_key": "key1",
    "_ns": "ns1",
    "StringValue": "withns1"
  }
]`)

	assert := wcg.NewAssert(t)
	var fk FixtureKind
	assert.Nil(DatastoreFixture(ts.Context, filepath, nil), "DatastoreFixture")

	key := datastore.NewKey(ts.Context, "FixtureKind", "key1", 0, nil)

	wcg.NewLogger(nil).Infof("GET: %s", key)
	assert.Nil(datastore.Get(ts.Context, key, &fk), "datastore.Get('key1') ")

	assert.EqInt(10, fk.IntValue, "IntValue should be 10")
	assert.EqFloat32(2.4, fk.FloatValue, "FloatValue should be 2.4")
	assert.EqStr("foobar", fk.StringValue, "StringValue should be 'foobar'")
	assert.EqStr("bytesfoobar", string(fk.BytesValue), "BytesValue should be 'foobar'")
	assert.EqInt(3, len(fk.Slice), "len(Slice) should be 3")
	assert.EqStr("a", string(fk.Slice[0]), "Slice[0] should be 'a'")
	assert.EqStr("b", string(fk.Slice[1]), "Slice[0] should be 'a'")
	assert.EqStr("c", string(fk.Slice[2]), "Slice[0] should be 'a'")

	assert.EqTime(time.Date(2014, 01, 02, 14, 02, 50, 0, time.UTC), fk.DateTimeValue, "DateTimeValue should be 2014-01-02T14:02:50Z")
	assert.EqTime(time.Date(2014, 01, 02, 0, 0, 0, 0, time.UTC), fk.DateValue, "DateTimeValue should be 2014-01-02T00:00:00Z")
	assert.EqStr("bar", string(fk.Struct.Foo), "Struct.Foo should be 'bar'")

	// namespace
	ns1, _ := appengine.Namespace(ts.Context, "ns1")
	key = datastore.NewKey(ns1, "FixtureKind", "key1", 0, nil)
	assert.Nil(datastore.Get(ns1, key, &fk), "datastore.Get('key1') /w ns1")
	assert.EqStr("withns1", fk.StringValue, "StringValue should be 'withns1'")
}
Exemple #20
0
func Test_ParallelSliceWithMaxConcurrency(t *testing.T) {
	assert := wcg.NewAssert(t)
	var a = []int{0, 1, 2, 3, 4}
	assert.Nil(
		ParallelSliceWithMaxConcurrency(a, 3, func(i int, v int) error {
			assert.EqInt(i, v)
			a[i] = v + 1
			return nil
		}),
	)
	for i := range a {
		assert.EqInt(i+1, a[i])
	}
}
Exemple #21
0
func Test_CollectReadyNASSMART(t *testing.T) {
	assert := wcg.NewAssert(t)
	httptest.StartMockServer(func(mock *httptest.MockServer) {
		mock.Routes().GET("/*", wcg.AnonymousHandler(func(res *wcg.Response, req *wcg.Request) {
			http.ServeFile(res, req.HTTPRequest(), "./fixtures/SMART.xml")
		}))
		stats, err := CollectReadyNASSMART(mock.Addr(), "", "", 6)
		assert.Nil(err, "getReadyNASSMart should not return an error")
		assert.EqInt(6, len(stats), "len(stats)")
		for _, s := range stats {
			assert.EqInt(5, s.StartStopCount, "StartStopCount")
		}
	})
}
Exemple #22
0
func Test_RGP_Parse(t *testing.T) {
	assert := wcg.NewAssert(t)
	rgb, err := ParseRGB("#ff0000")
	assert.Nil(err)
	assert.EqInt(255<<16, int(rgb))

	rgb, err = ParseRGB("ff0000")
	assert.Nil(err)
	assert.EqInt(255<<16, int(rgb))

	rgb, err = ParseRGB("0xff0000")
	assert.Nil(err)
	assert.EqInt(255<<16, int(rgb))
}
Exemple #23
0
func TestFileRotation(t *testing.T) {
	assert := wcg.NewAssert(t)
	p, _ := ioutil.TempDir("", "wcg-logsink-temp")
	os.MkdirAll(p, 0755)
	defer os.RemoveAll(p)
	factory := &rotatedFileFactory{
		PathFormat: filepath.Join(p, "wcg-%Y%m%d.log"),
	}
	f := factory.GetWriter(&wcg.LogRecord{
		Timestamp: time.Date(1984, 9, 22, 12, 01, 28, 20, time.UTC),
	}).(*os.File)
	defer f.Close()
	assert.EqStr(filepath.Join(p, "wcg-19840922.log"), f.Name(), "filepath should be formatted.")
}
Exemple #24
0
func Test_RGP_JSON(t *testing.T) {
	assert := wcg.NewAssert(t)
	type s struct {
		Value RGB `json:"value"`
	}
	obj := &s{RGB(255 << 16)}
	buff, err := json.Marshal(obj)
	assert.Nil(err)
	assert.EqStr("{\"value\":\"#ff0000\"}", string(buff))

	var obj2 s
	assert.Nil(json.Unmarshal(buff, &obj2))
	assert.EqInt(int(obj.Value), int(obj2.Value))
}
Exemple #25
0
func Test_getReadyNASSMART(t *testing.T) {
	assert := wcg.NewAssert(t)
	httptest.StartMockServer(func(mock *httptest.MockServer) {
		mock.Routes().GET("/*", wcg.AnonymousHandler(func(res *wcg.Response, req *wcg.Request) {
			http.ServeFile(res, req.HTTPRequest(), "./fixtures/SMART.xml")
		}))
		s, err := getSMARTStatsFromReadyNAS(mock.BaseURL(), "", "")
		assert.Nil(err, "getReadyNASSMart should not return an error")
		assert.EqInt(1, s.SpinUpTime, "SpinUpTime")
		assert.EqInt(5, s.StartStopCount, "StartStopCount")
		assert.EqInt64(252668631068583, s.HeadFlyingHours, "HeadFlyingHours")
		assert.EqInt64(76931166535, s.TotalLBAsWritten, "TotalLBAsWritten")
		assert.EqInt64(186750896472, s.TotalLBAsRead, "TotalLBAsRead")
	})
}
Exemple #26
0
func Test_Run(t *testing.T) {
	assert := wcg.NewAssert(t)
	httptest.StartMockServer(func(s *httptest.MockServer) {
		s.Routes().GET("/*", wcg.AnonymousHandler(func(res *wcg.Response, req *wcg.Request) {
			res.WriteString("OK")
		}))
		url := s.BaseURL()

		runner := &Runner{
			Crawler: &testCrawlerImpl{url},
		}
		result, err := runner.Run(url)
		assert.Nil(err)
		assert.EqStr("OK", result.Data.(string))
	})
}
Exemple #27
0
func Test_IEPGExclusion_ShouldExclude(t *testing.T) {
	assert := wcg.NewAssert(t)
	iepg := &IEPG{
		CID:          "cid1",
		SID:          "sid1",
		ProgramTitle: "TestTitle",
	}
	exclusion := &IEPGExclusion{
		CID:           "cid1",
		SID:           "sid1",
		TitleText:     "Test",
		TitleTextType: IEPGExclusionTextTypeStartWith,
		Weekday:       -1,
	}
	assert.OK(exclusion.ShouldExclude(iepg))
}
Exemple #28
0
func Test_getReadyNASSMART_With_BasicAuth(t *testing.T) {
	assert := wcg.NewAssert(t)
	httptest.StartMockServer(func(mock *httptest.MockServer) {
		mock.Routes().GET("/*", wcg.AnonymousHandler(func(res *wcg.Response, req *wcg.Request) {
			username, password, _ := req.HTTPRequest().BasicAuth()
			if username == "testuser" && password == "passw0rd" {
				http.ServeFile(res, req.HTTPRequest(), "./fixtures/SMART.xml")
			} else {
				res.WriteHeader(401)
			}
		}))
		_, err := getSMARTStatsFromReadyNAS(mock.BaseURL(), "testuser", "passw0rd")
		assert.Nil(err, "getReadyNASSMart should not return an error")
		_, err = getSMARTStatsFromReadyNAS(mock.BaseURL(), "", "")
		assert.OK(err != nil, "getReadyNASSMart should return an error")
	})
}
Exemple #29
0
func Test_HumanToday(t *testing.T) {
	assert := wcg.NewAssert(t)
	TemporarySetNow(time.Date(
		2015, 5, 12,
		1, 25,
		0, 0,
		UTC,
	), func() {
		now := HumanToday()
		assert.EqInt(2015, now.Year(), "Year")
		assert.EqInt(5, int(now.Month()), "Month")
		assert.EqInt(11, now.Day(), "Day")
		assert.EqInt(4, now.Hour(), "Hour")
		assert.EqInt(0, now.Minute(), "Mintues")
		assert.EqStr("UTC", now.Location().String(), "Location")
	})
}
Exemple #30
0
func Test_parseMessage_Authentication(t *testing.T) {
	assert := wcg.NewAssert(t)

	f, _ := os.Open("./fixtures/authentication.json")
	defer f.Close()
	data, err := parseMessage(f)
	assert.Nil(err, "parseMessage should return no error but %s", err)
	assert.EqInt(1, len(data), "parseMessage should return one message")

	auth, ok := data[0].(*MessageAuthentication)
	assert.OK(ok, "parseMessage should return MessageAuthentication")
	assert.EqStr("339779266223592", auth.PageID, "PageID")
	assert.EqStr("1112333128808549", auth.SenderID, "SenderID")
	assert.EqStr("339779266223592", auth.RecipientID, "RecipientID")
	assert.EqStr("605588b9-4d59-47ac-8d9b-5a998aa30da7", auth.Ref, "Ref")
	assert.EqTime(time.Unix(1463807042, 105000000), auth.UpdateTime, "UpdateTime")
}