You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
70 lines
2.2 KiB
Go
70 lines
2.2 KiB
Go
package security
|
|
|
|
// Tests for input sanitization utilities and validation helpers.
|
|
|
|
import (
|
|
"regexp"
|
|
"testing"
|
|
|
|
"github.com/stretchr/testify/require"
|
|
)
|
|
|
|
// TestSanitize_Options verifies trimming, space collapsing, escaping, max length, and allowed patterns.
|
|
func TestSanitize_Options(t *testing.T) {
|
|
opts := SanitizeOptions{
|
|
TrimWhitespace: true,
|
|
RemoveMultipleSpaces: true,
|
|
HTMLEscape: true,
|
|
MaxLength: 0,
|
|
AllowedPattern: nil,
|
|
}
|
|
|
|
result := Sanitize(" Hello <b>World</b> ", opts)
|
|
require.Equal(t, "Hello <b>World</b>", result)
|
|
|
|
opts.MaxLength = 5
|
|
require.Equal(t, "Hello", Sanitize("Hello World", opts))
|
|
|
|
opts.AllowedPattern = regexp.MustCompile(`^[a-z]+$`)
|
|
require.Equal(t, "", Sanitize("Hello123", opts))
|
|
}
|
|
|
|
// TestSanitizePlayerName verifies player name normalization and invalid input rejection.
|
|
func TestSanitizePlayerName(t *testing.T) {
|
|
require.Equal(t, "Alice Bob", SanitizePlayerName(" Alice Bob "))
|
|
require.Equal(t, "", SanitizePlayerName("Alice <"))
|
|
}
|
|
|
|
// TestSanitizeAnswer verifies lowercasing and whitespace normalization.
|
|
func TestSanitizeAnswer(t *testing.T) {
|
|
require.Equal(t, "hello", SanitizeAnswer(" HeLLo "))
|
|
}
|
|
|
|
// TestSanitizeQuestionText verifies script tags are removed from question text.
|
|
func TestSanitizeQuestionText(t *testing.T) {
|
|
result := SanitizeQuestionText("<script>alert(1)</script> Question")
|
|
require.NotContains(t, result, "<script")
|
|
}
|
|
|
|
// TestSanitizeTheme verifies theme normalization and title casing.
|
|
func TestSanitizeTheme(t *testing.T) {
|
|
require.Equal(t, "Science Fiction", SanitizeTheme(" science fiction "))
|
|
}
|
|
|
|
// TestRemoveHTMLTags verifies all HTML tags are stripped from input.
|
|
func TestRemoveHTMLTags(t *testing.T) {
|
|
require.Equal(t, "Hi", RemoveHTMLTags("<b>Hi</b>"))
|
|
}
|
|
|
|
// TestContainsDangerousPatterns detects known dangerous substrings.
|
|
func TestContainsDangerousPatterns(t *testing.T) {
|
|
require.True(t, ContainsDangerousPatterns("javascript:alert(1)"))
|
|
require.False(t, ContainsDangerousPatterns("hello"))
|
|
}
|
|
|
|
// TestIsValidEmail verifies basic email pattern validation.
|
|
func TestIsValidEmail(t *testing.T) {
|
|
require.True(t, IsValidEmail("a@b.com"))
|
|
require.False(t, IsValidEmail("bad@"))
|
|
}
|