Exemple #1
0
func TestCreateFeed(t *testing.T) {
	feedTitle := fmt.Sprintf("test-feed-%d", rand.Intn(1000000000))
	url := _url("/feeds/" + feedTitle)

	res, err := http.Get(url)
	require.Nil(t, err)
	require.Equal(t, res.StatusCode, 404)

	entryStr := "<entry><title>foo</title><content>bar</content></entry>"
	buf := bytes.NewBufferString(entryStr)
	res, err = http.Post(url, "application/atom+xml", buf)
	require.Nil(t, err)
	require.Equal(t, res.StatusCode, 201, "created feed")

	res, err = http.Get(url)
	require.Nil(t, err)
	require.Equal(t, res.StatusCode, 200, "got feed")

	feed, err := atom.DecodeFeed(res.Body)
	require.Nil(t, err, "parsed feed")
	assert.Equal(t, feed.Title.Raw, feedTitle, "feed title")
	require.NotNil(t, feed.Updated, "feed.updated")
	assert.Regexp(t, timeRe, *feed.Updated, "feed.updated")

	require.Equal(t, len(feed.Entries), 1, "got 1 entry")
	entry := feed.Entries[0]
	assert.Equal(t, entry.Content.Raw, "bar", "entry content")
	require.NotNil(t, entry.Updated, "entry.updated")
	assert.Regexp(t, timeRe, *entry.Updated, "entry.updated")
}
func TestRecognizesDateStringAboveQuote(t *testing.T) {
	e := email(t, "email_1_4")

	assert.Regexp(t, regexp.MustCompile(`^Awesome`), e.Fragments[0].String())
	assert.Regexp(t, regexp.MustCompile(`(?m)^On`), e.Fragments[1].String())
	assert.Regexp(t, regexp.MustCompile(`Loader`), e.Fragments[1].String())
}
Exemple #3
0
func TestLoggly(t *testing.T) {
	var buf bytes.Buffer
	var result map[string]interface{}
	loggly := loggly.New("token not required")
	loggly.Writer = &buf
	lw := logglyErrorWriter{client: loggly}
	golog.SetOutputs(lw, nil)
	log := golog.LoggerFor("test")

	log.Error("")
	if assert.NoError(t, json.Unmarshal(buf.Bytes(), &result), "Unmarshal error") {
		assert.Equal(t, "ERROR test", result["locationInfo"])
		assert.Regexp(t, regexp.MustCompile("logging_test.go:([0-9]+)"), result["message"])
	}

	buf.Reset()
	log.Error("short message")
	if assert.NoError(t, json.Unmarshal(buf.Bytes(), &result), "Unmarshal error") {
		assert.Equal(t, "ERROR test", result["locationInfo"])
		assert.Regexp(t, regexp.MustCompile("logging_test.go:([0-9]+) short message"), result["message"])
	}

	buf.Reset()
	log.Error("message with: reason")
	if assert.NoError(t, json.Unmarshal(buf.Bytes(), &result), "Unmarshal error") {
		assert.Equal(t, "ERROR test", result["locationInfo"])
		assert.Regexp(t, "logging_test.go:([0-9]+) message with: reason", result["message"])
	}

	buf.Reset()
	log.Error("deep reason: message with: reason")
	if assert.NoError(t, json.Unmarshal(buf.Bytes(), &result), "Unmarshal error") {
		assert.Equal(t, "ERROR test", result["locationInfo"])
		assert.Equal(t, "message with: reason", result["message"], "message should be last 2 chunks")
	}

	buf.Reset()
	log.Error("deep reason: an url https://a.com in message: reason")
	if assert.NoError(t, json.Unmarshal(buf.Bytes(), &result), "Unmarshal error") {
		assert.Equal(t, "an url https://a.com in message: reason", result["message"], "should not truncate url")
	}

	buf.Reset()
	log.Error("deep reason: an url 127.0.0.1:8787 in message: reason")
	if assert.NoError(t, json.Unmarshal(buf.Bytes(), &result), "Unmarshal error") {
		assert.Equal(t, "ERROR test", result["locationInfo"])
		assert.Equal(t, "an url 127.0.0.1:8787 in message: reason", result["message"], "should not truncate url")
	}

	buf.Reset()
	longPrefix := "message with: really l"
	longMsg := longPrefix + strings.Repeat("o", 100) + "ng reason"
	log.Error(longMsg)
	if assert.NoError(t, json.Unmarshal(buf.Bytes(), &result), "Unmarshal error") {
		assert.Equal(t, "ERROR test", result["locationInfo"])

		assert.Regexp(t, regexp.MustCompile("logging_test.go:([0-9]+) "+longPrefix+"(o+)"), result["message"])
		assert.Equal(t, 100, len(result["message"].(string)))
	}
}
func TestDealsWithMultilineReplyHeaders(t *testing.T) {
	e := email(t, "email_1_6")

	assert.Regexp(t, regexp.MustCompile(`^I get`), e.Fragments[0].String())
	assert.Regexp(t, regexp.MustCompile(`(?m)^On`), e.Fragments[1].String())
	assert.Regexp(t, regexp.MustCompile(`Was this`), e.Fragments[1].String())
}
func TestUploadOrderMulti(t *testing.T) {
	s, ops, args := loggingSvc()
	resp, err := s3manager.Upload(s, &s3manager.UploadInput{
		Bucket:               aws.String("Bucket"),
		Key:                  aws.String("Key"),
		Body:                 bytes.NewReader(buf12MB),
		ServerSideEncryption: aws.String("AES256"),
		ContentType:          aws.String("content/type"),
	}, nil)

	assert.NoError(t, err)
	assert.Equal(t, []string{"CreateMultipartUpload", "UploadPart", "UploadPart", "UploadPart", "CompleteMultipartUpload"}, *ops)
	assert.Equal(t, "https://location", resp.Location)
	assert.Equal(t, "UPLOAD-ID", resp.UploadID)

	// Validate input values

	// UploadPart
	assert.Equal(t, "UPLOAD-ID", val((*args)[1], "UploadID"))
	assert.Equal(t, "UPLOAD-ID", val((*args)[2], "UploadID"))
	assert.Equal(t, "UPLOAD-ID", val((*args)[3], "UploadID"))

	// CompleteMultipartUpload
	assert.Equal(t, "UPLOAD-ID", val((*args)[4], "UploadID"))
	assert.Equal(t, int64(1), val((*args)[4], "MultipartUpload.Parts[0].PartNumber"))
	assert.Equal(t, int64(2), val((*args)[4], "MultipartUpload.Parts[1].PartNumber"))
	assert.Equal(t, int64(3), val((*args)[4], "MultipartUpload.Parts[2].PartNumber"))
	assert.Regexp(t, `^ETAG\d+$`, val((*args)[4], "MultipartUpload.Parts[0].ETag"))
	assert.Regexp(t, `^ETAG\d+$`, val((*args)[4], "MultipartUpload.Parts[1].ETag"))
	assert.Regexp(t, `^ETAG\d+$`, val((*args)[4], "MultipartUpload.Parts[2].ETag"))

	// Custom headers
	assert.Equal(t, "AES256", val((*args)[0], "ServerSideEncryption"))
	assert.Equal(t, "content/type", val((*args)[0], "ContentType"))
}
func TestDealsWithWindowsLineEndings(t *testing.T) {
	e := email(t, "email_1_7")

	assert.Regexp(t, regexp.MustCompile(`:\+1:`), e.Fragments[0].String())
	assert.Regexp(t, regexp.MustCompile(`(?m)^On`), e.Fragments[1].String())
	assert.Regexp(t, regexp.MustCompile(`Steps 0-2`), e.Fragments[1].String())
}
Exemple #7
0
func TestPolygonLayer(t *testing.T) {
	m := New(&locator)
	m.SetNoMapBlock(true)

	m.AddLayer(mml.Layer{ID: "test", SRS: "4326", Type: mml.Polygon},
		[]mss.Rule{
			{Layer: "test", Properties: mss.NewProperties(
				"line-width", 1.0,
				"line-color", color.MustParse("red"),
				"line-opacity", 0.5,
				"line-dasharray", []mss.Value{3.0, 5.0},
				"polygon-fill", color.MustParse("blue"),
				"polygon-opacity", 0.2,
				"text-size", 10.0,
				"text-name", []mss.Value{mss.Field("name")},
			)},
		})
	result := m.String()
	assert.Contains(t, result, "WIDTH 1\n")
	assert.Contains(t, result, "OUTLINECOLOR \"#ff000080\"\n")
	assert.Regexp(t, `PATTERN\s+3\s+5\s+END`, result)
	assert.Contains(t, result, "COLOR \"#0000ff\"\n")
	assert.Contains(t, result, "OPACITY 20\n")
	assert.Regexp(t, `LABEL\s+ SIZE 7.4\d+`, result)
	assert.Regexp(t, `TEXT 'name'`, result)
}
Exemple #8
0
func TestScaledLineStringLayer(t *testing.T) {
	m := New(&locator)
	m.SetNoMapBlock(true)

	m.AddLayer(mml.Layer{ID: "test", SRS: "4326", Type: mml.LineString, ScaleFactor: 2.0},
		[]mss.Rule{
			{Layer: "test", Properties: mss.NewProperties(
				"line-width", 3.0,
				"line-opacity", 0.2,
				"line-dasharray", []mss.Value{2.0, 7.0},
			)},
		})
	m.AddLayer(mml.Layer{ID: "test", SRS: "4326", Type: mml.LineString},
		[]mss.Rule{
			{Layer: "test", Properties: mss.NewProperties(
				"line-width", 1.0,
				"line-color", color.MustParse("red"),
				"line-opacity", 0.5,
				"line-dasharray", []mss.Value{3.0, 5.0},
			)},
		})
	result := m.String()
	assert.Contains(t, result, "WIDTH 6\n")
	assert.Contains(t, result, "OPACITY 20\n")
	assert.Regexp(t, `PATTERN\s+4\s+14\s+END`, result)

	assert.Contains(t, result, "WIDTH 1\n")
	assert.Contains(t, result, "COLOR \"#ff0000\"\n")
	assert.Contains(t, result, "OPACITY 50\n")
	assert.Regexp(t, `PATTERN\s+3\s+5\s+END`, result)
}
Exemple #9
0
func TestUniqueId(t *testing.T) {
	h, err := newTestHub()
	assert.NoError(t, err)
	defer h.Close()

	assert.Regexp(t, regexp.MustCompile(`^[0-9a-zA-Z]{10}-1$`), h.UniqueId())
	assert.Regexp(t, regexp.MustCompile(`^[0-9a-zA-Z]{10}-2$`), h.UniqueId())
	assert.Regexp(t, regexp.MustCompile(`^[0-9a-zA-Z]{10}-3$`), h.UniqueId())

}
func TestMultipleOn(t *testing.T) {
	e := email(t, "greedy_on")

	assert.Regexp(t, regexp.MustCompile(`(?m)^On your remote host`), e.Fragments[0].String())
	assert.Regexp(t, regexp.MustCompile(`(?m)^On 9 Jan 2014`), e.Fragments[1].String())
	assert.Equal(t, []bool{false, true, false}, quoteds(e.Fragments))
	assert.Equal(t, []bool{false, false, false}, signatures(e.Fragments))
	assert.Equal(t, []bool{false, true, true}, hiddens(e.Fragments))

}
func TestResultsReportsFailures(t *testing.T) {
	results := NewDetectionResults()
	results.Fail("some_filename", "Bomb")
	results.Fail("some_filename", "Complete & utter failure")
	results.Fail("another_filename", "Complete & utter failure")

	actualErrorReport := results.ReportFileFailures("some_filename")
	assert.Regexp(t, "The following errors were detected in some_filename", actualErrorReport, "Error report does not contain expected output")
	assert.Regexp(t, "Bomb", actualErrorReport, "Error report does not contain expected output")
	assert.Regexp(t, "Complete & utter failure", actualErrorReport, "Error report does not contain expected output")
}
func TestLoggingIgnoredFilesDoesNotCauseFailure(t *testing.T) {
	results := NewDetectionResults()
	results.Ignore("some_file", "Ignoring this file, just because")
	results.Ignore("some/other_file", "Ignoring this file too")
	assert.True(t, results.Successful(), "Calling ignore should keep the result successful.")
	assert.True(t, results.HasIgnores(), "Calling ignore should be logged.")
	assert.False(t, results.HasFailures(), "Calling ignore should not cause a result to fail.")

	assert.Regexp(t, "Ignoring this file, just because", results.Report(), "foo")
	assert.Regexp(t, "Ignoring this file too", results.Report(), "foo")
}
Exemple #13
0
func TestOAuth(t *testing.T) {
	oauthResponse, err := ccApi.OAuthToken(Password)
	assert.Nil(t, err)
	if assert.NotNil(t, oauthResponse) {
		assert.Regexp(t, md5Regex, oauthResponse.AccessToken)
		assert.Equal(t, oauthResponse.TokenType, "bearer")
		assert.Regexp(t, md5Regex, oauthResponse.RefreshToken)
		assert.True(t, oauthResponse.ExpiresIn > 0, "expires must be a non-negative integer")
		assert.Equal(t, "read write payments accounts export", oauthResponse.Scope)
	}
}
func TestReadsTopPost(t *testing.T) {
	e := email(t, "email_1_3")

	assert.Len(t, e.Fragments, 5)
	assert.Equal(t, []bool{false, false, true, false, false}, quoteds(e.Fragments))
	assert.Equal(t, []bool{false, true, true, true, true}, hiddens(e.Fragments))
	assert.Equal(t, []bool{false, true, false, false, true}, signatures(e.Fragments))
	assert.Regexp(t, regexp.MustCompile(`^Oh thanks.\n\nHaving`), e.Fragments[0].String())
	assert.Regexp(t, regexp.MustCompile(`^-A`), e.Fragments[1].String())
	assert.Regexp(t, regexp.MustCompile(`(?m)^On [^\:]+\:`), e.Fragments[2].String())
	assert.Regexp(t, regexp.MustCompile(`^_`), e.Fragments[4].String())
}
func TestHTTP(t *testing.T) {
	ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		time.Sleep(time.Second / 5)
		w.WriteHeader(200)
		w.Header().Set("Content-Type", "text/plain")
		fmt.Fprint(w, "OKOK")
	}))
	defer ts.Close()

	u, _ := url.Parse(ts.URL)

	host, port, _ := net.SplitHostPort(u.Host)

	testOk := func() {
		opts, err := parseArgs([]string{"-H", host, "-p", port, "--send", `GET / HTTP/1.0\r\n\r\n`, "-E", "-e", "OKOK"})
		assert.Equal(t, nil, err, "no errors")
		ckr := opts.run()
		fmt.Println(ckr)
		assert.Equal(t, checkers.OK, ckr.Status, "should be OK")
		assert.Regexp(t, `seconds response time on`, ckr.Message, "Unexpected response")
	}
	testOk()

	testUnexpected := func() {
		opts, err := parseArgs(
			[]string{"-H", host, "-p", port, "--send", `GET / HTTP/1.0\r\n\r\n`, "-E", "-e", "OKOKOK"})
		assert.Equal(t, nil, err, "no errors")
		ckr := opts.run()
		assert.Equal(t, checkers.CRITICAL, ckr.Status, "should be CRITICAL")
		assert.Regexp(t, `Unexpected response from`, ckr.Message, "Unexpected response")
	}
	testUnexpected()

	testOverWarn := func() {
		opts, err := parseArgs(
			[]string{"-H", host, "-p", port, "--send", `GET / HTTP/1.0\r\n\r\n`, "-E", "-e", "OKOK", "-w", "0.1"})
		assert.Equal(t, nil, err, "no errors")
		ckr := opts.run()
		assert.Equal(t, checkers.WARNING, ckr.Status, "should be Warning")
		assert.Regexp(t, `seconds response time on`, ckr.Message, "Unexpected response")
	}
	testOverWarn()

	testOverCrit := func() {
		opts, err := parseArgs(
			[]string{"-H", host, "-p", port, "--send", "GET / HTTP/1.0\r\n\r\n", "-e", "OKOK", "-c", "0.1"})
		assert.Equal(t, nil, err, "no errors")
		ckr := opts.run()
		assert.Equal(t, checkers.CRITICAL, ckr.Status, "should be Critical")
		assert.Regexp(t, `seconds response time on`, ckr.Message, "Unexpected response")
	}
	testOverCrit()
}
func TestReadsBottomPost(t *testing.T) {
	e := email(t, "email_1_2")

	assert.Len(t, e.Fragments, 6)
	assert.Equal(t, []bool{false, true, false, true, false, false}, quoteds(e.Fragments))
	assert.Equal(t, []bool{false, false, false, false, false, true}, signatures(e.Fragments))
	assert.Equal(t, []bool{false, false, false, true, true, true}, hiddens(e.Fragments))
	assert.Equal(t, "Hi,", e.Fragments[0].String())
	assert.Regexp(t, regexp.MustCompile(`^On [^\:]+\:`), e.Fragments[1].String())
	assert.Regexp(t, regexp.MustCompile(`(?m)^You can list`), e.Fragments[2].String())
	assert.Regexp(t, regexp.MustCompile(`(?m)^> `), e.Fragments[3].String())
	assert.Regexp(t, regexp.MustCompile(`^_`), e.Fragments[5].String())
}
Exemple #17
0
func TestTreeDel(t *testing.T) {
	existingNodes := []string{
		"root/only/two",
		"root/only/three",
		"root/only/one/child/here",
	}
	tree := newTree()
	for _, p := range existingNodes {
		tree.add(p, newNode(1))
	}

	// listen for notifications
	notifications := tree.watch("")
	exited := make(chan struct{})
	go func() {
		regex := regexp.MustCompile("(root/only/one/child|root)")
		n, ok := <-notifications
		assert.True(t, ok)
		assert.Equal(t, "put", n.Name)
		assert.Regexp(t, regex, n.Data.Path)

		n, ok = <-notifications
		assert.True(t, ok)
		assert.Equal(t, "put", n.Name)
		assert.Regexp(t, regex, n.Data.Path)
		close(exited)
	}()

	tree.del("root/only/one/child")
	assert.Nil(t, tree.get("root/only/one/child/here"))
	assert.Nil(t, tree.get("root/only/one/child"))
	assert.Nil(t, tree.get("root/only/one"))
	n := tree.get("root/only")
	require.NotNil(t, n)
	assert.Len(t, n.children, 2)
	_, exists := n.children["one"]
	assert.False(t, exists)

	tree.del("root")
	n = tree.get("")
	require.NotNil(t, n)
	assert.Len(t, n.children, 0)

	select {
	case <-exited:
	case <-time.After(250 * time.Millisecond):
	}
	tree.stopWatching("", notifications)
}
func TestReadsInlineReplies(t *testing.T) {
	e := email(t, "email_1_8")

	assert.Len(t, e.Fragments, 7)
	assert.Equal(t, []bool{true, false, true, false, true, false, false}, quoteds(e.Fragments))
	assert.Equal(t, []bool{false, false, false, false, false, false, true}, signatures(e.Fragments))
	assert.Equal(t, []bool{false, false, false, false, true, true, true}, hiddens(e.Fragments))
	assert.Regexp(t, regexp.MustCompile(`^On [^\:]+\:`), e.Fragments[0].String())
	assert.Regexp(t, regexp.MustCompile(`(?m)^I will reply`), e.Fragments[1].String())
	assert.Regexp(t, regexp.MustCompile(`okay?`), e.Fragments[2].String())
	assert.Regexp(t, regexp.MustCompile(`(?m)^and under this.`), e.Fragments[3].String())
	assert.Regexp(t, regexp.MustCompile(`inline`), e.Fragments[4].String())
	assert.Equal(t, "\n", e.Fragments[5].String())
	assert.Equal(t, e.Fragments[6].String(), "--\nHey there, this is my signature\n")
}
Exemple #19
0
func TestURL(t *testing.T) {
	ft := New()
	ft.Start()
	assert.Regexp(t, regexp.MustCompile(`https?://127.0.0.1:\d+`), ft.URL)

	ft.Close()
}
Exemple #20
0
func TestNewID(t *testing.T) {

	id, err := newID()
	assert.NoError(t, err)

	assert.Regexp(t, regexp.MustCompile(`([0-9a-f]{64})`), id)
}
Exemple #21
0
func TestSnapshot(t *testing.T) {
	a := Snapshot{
		"package1": SnapshotEntry{
			"a": "chksum1",
			"b": "chksum2",
		},
		"package2": SnapshotEntry{
			"c": "chksum3",
			"d": "chksum4",
		},
	}
	b := a.Clone()
	assert.True(t, &a != &b)
	assert.Equal(t, a, b)
	assert.True(t, a.Equal(a))
	assert.True(t, a.Equal(b))
	assert.True(t, b.Equal(a))
	assert.True(t, b.Equal(b))

	data, err := a.Marshal()
	assert.NoError(t, err)
	assert.Regexp(t, `(?s).*"package1":.*"package2":.*`, string(data))
	var c Snapshot
	err = c.Unmarshal(data)
	assert.NoError(t, err)
	assert.True(t, c.Equal(a))
	assert.Equal(t, a, c)
}
func TestMakeEdgeTimeStamp(t *testing.T) {
	actual := makeEdgeTimeStamp()
	expected := regexp.MustCompile(`^\d{4}[0-1][0-9][0-3][0-9]T[0-2][0-9]:[0-5][0-9]:[0-5][0-9]\+0000$`)
	if assert.Regexp(t, expected, actual, "Fail: Regex do not match") {
		t.Log("Pass: Regex matches")
	}
}
func TestProcExe(t *testing.T) {
	skipWindows(t)
	exe := ProcExe{}
	if assert.NoError(t, exe.Get(os.Getppid())) {
		assert.Regexp(t, "go(.exe)?", filepath.Base(exe.Name))
	}
}
Exemple #24
0
func TestPlayerInfoFetching(t *testing.T) {
	testhelpers.CleanupDB()

	if config.Constants.SteamDevApiKey == "your steam dev api key" {
		return
	}

	// disable mock mode because we're actually testing it
	config.Constants.SteamApiMockUp = false

	player, playErr := models.NewPlayer("76561197999073985")
	assert.Nil(t, playErr)

	assert.Equal(t, "http://steamcommunity.com/id/nonagono/", player.Profileurl)
	assert.Regexp(t, "(.*)steamcommunity/public/images/avatars/(.*).jpg", player.Avatar)

	assert.True(t, player.GameHours >= 3000)

	player.Stats.PlayedCountSet(models.LobbyTypeSixes, 3)
	player.Stats.PlayedCountSet(models.LobbyTypeHighlander, 7)
	player.Stats.PlayedCountIncrease(models.LobbyTypeSixes) // sixes: 3 -> 4

	assert.Equal(t, 4, player.Stats.PlayedCountGet(models.LobbyTypeSixes))
	assert.Equal(t, 7, player.Stats.PlayedCountGet(models.LobbyTypeHighlander))

	database.DB.Save(player)

	player2, err := models.GetPlayerWithStats(player.SteamId)
	assert.Nil(t, err)

	assert.Equal(t, 4, player2.Stats.PlayedCountGet(models.LobbyTypeSixes))
	assert.Equal(t, 7, player2.Stats.PlayedCountGet(models.LobbyTypeHighlander))
	assert.Equal(t, "http://steamcommunity.com/id/nonagono/", player2.Profileurl)
}
Exemple #25
0
func TestManifestInvalid(t *testing.T) {
	manifest, err := LoadManifest("invalid-manifest", nil)

	assert.Nil(t, manifest)
	assert.NotNil(t, err)
	assert.Regexp(t, "^invalid manifest: ", err.Error())
}
func TestProcessDataFromBufferedString(t *testing.T) {
	// given
	ip := net.IPv4(127, 0, 0, 1)
	port := 45678
	timeout := 2 * time.Second
	options := newMockedTelnetClientOptions(ip.String(), uint64(port), timeout)
	sut := NewTelnetClient(options)

	request := "GET /first HTTP/1.1\nHost: localhost\n\n"
	buffer := bytes.NewBuffer([]byte(request))
	localServer := localserver.NewLocalServer(fmt.Sprintf("%v:%d", ip.String(), port), "http")
	http.HandleFunc("/first", func(response http.ResponseWriter, request *http.Request) {
		response.Write([]byte("a_response\n"))
	})
	localServer.StartHTTP()

	var response = new(bytes.Buffer)

	// when
	sut.ProcessData(buffer, response)

	// then
	localServer.Stop()
	http.DefaultServeMux = http.NewServeMux()

	assert := assert.New(t)
	assert.Regexp("HTTP/1.1 200 OK\r\nDate: Mon, .+ GMT\r\nContent-Length: 11\r\nContent-Type: text/plain; charset=utf-8\r\n\r\na_response\n", response.String(), "Expected different response.")
}
func TestProcessDataFromFile(t *testing.T) {
	// given
	ip := net.IPv4(127, 0, 0, 1)
	port := 45679
	timeout := 2 * time.Second
	options := newMockedTelnetClientOptions(ip.String(), uint64(port), timeout)
	sut := NewTelnetClient(options)

	fi, err := os.Open("../resources/input-data/localhost_1.bin")
	if err != nil {
		panic(err)
	}
	defer fi.Close()
	buffer := bufio.NewReader(fi)

	localServer := localserver.NewLocalServer(fmt.Sprintf("%v:%d", ip.String(), port), "http")
	http.HandleFunc("/second", func(response http.ResponseWriter, request *http.Request) {
		response.Write([]byte("b_response\n"))
	})
	localServer.StartHTTP()

	var response = new(bytes.Buffer)

	// when
	sut.ProcessData(buffer, response)

	// then
	localServer.Stop()
	http.DefaultServeMux = http.NewServeMux()

	assert := assert.New(t)
	assert.Regexp("HTTP/1.1 200 OK\r\nDate: Mon, .+ GMT\r\nContent-Length: 11\r\nContent-Type: text/plain; charset=utf-8\r\n\r\nb_response\n", response.String(), "Expected different response.")
}
Exemple #28
0
func TestTraceEnabled(t *testing.T) {
	originalTrace := os.Getenv("TRACE")
	err := os.Setenv("TRACE", "true")
	if err != nil {
		t.Fatalf("Unable to set trace to true")
	}
	defer func() {
		if err := os.Setenv("TRACE", originalTrace); err != nil {
			t.Fatalf("Unable to set TRACE environment variable: %v", err)
		}
	}()

	out := bytes.NewBuffer(nil)
	SetOutputs(ioutil.Discard, out)
	l := LoggerFor("myprefix")
	l.Trace("Hello world")
	l.Tracef("Hello %d", 5)
	tw := l.TraceOut()
	if _, err := tw.Write([]byte("Gravy\n")); err != nil {
		t.Fatalf("Unable to write: %v", err)
	}
	if err := tw.(io.Closer).Close(); err != nil {
		t.Fatalf("Unable to close: %v", err)
	}

	// Give trace writer a moment to catch up
	time.Sleep(50 * time.Millisecond)
	assert.Regexp(t, severitize("TRACE", expectedTraceLog), string(out.Bytes()))
}
Exemple #29
0
func TestPlayerInfoFetching(t *testing.T) {
	t.Parallel()

	if config.Constants.SteamDevApiKey == "your steam dev api key" {
		return
	}

	// disable mock mode because we're actually testing it
	config.SteamApiMockUp = false

	player, playErr := NewPlayer("76561197999073985")
	assert.Nil(t, playErr)

	assert.Equal(t, "http://steamcommunity.com/id/nonagono/", player.Profileurl)
	assert.Regexp(t, "(.*)steamcommunity/public/images/avatars/(.*).jpg", player.Avatar)

	assert.True(t, player.GameHours >= 3000)

	player.Stats.PlayedCountIncrease(LobbyTypeSixes)
	player.Stats.PlayedCountIncrease(LobbyTypeHighlander)
	player.Stats.PlayedCountIncrease(LobbyTypeSixes) // sixes: 1 -> 2

	database.DB.Save(player)

	player2, err := GetPlayerWithStats(player.SteamID)
	assert.Nil(t, err)

	assert.Equal(t, 2, player2.Stats.PlayedSixesCount)
	assert.Equal(t, 1, player2.Stats.PlayedHighlanderCount)
	assert.Equal(t, "http://steamcommunity.com/id/nonagono/", player2.Profileurl)
}
func (s *S3SigningSuite) TestBuildSignedS3URLUSWest2WithEndpoint() {
	signedURL, err := BuildSignedS3URL(VALID_S3_URL, VALID_S3_REGION_US_WEST_2, VALID_S3_EXPIRY, VALID_S3_LOCAL_ENDPOINT)
	assert.Nil(s.T(), err)

	urlRegexp := fmt.Sprintf("^%s/bucketname/path/file.json\\?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=.*&X-Amz-Date=.*&X-Amz-Expires=%d&X-Amz-SignedHeaders=host&X-Amz-Signature=.*$", VALID_S3_LOCAL_ENDPOINT, VALID_S3_EXPIRY)
	assert.Regexp(s.T(), urlRegexp, signedURL)
}