Skip to content

Commit

Permalink
tests
Browse files Browse the repository at this point in the history
  • Loading branch information
liya committed Dec 17, 2024
1 parent 985d765 commit 6905ebd
Show file tree
Hide file tree
Showing 9 changed files with 863 additions and 242 deletions.
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ require (
github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
github.com/go-redis/redismock/v9 v9.2.0 // indirect
github.com/golang/protobuf v1.5.4 // indirect
github.com/josharian/intern v1.0.0 // indirect
github.com/matttproud/golang_protobuf_extensions v1.0.4 // indirect
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78=
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc=
github.com/go-redis/redismock/v9 v9.2.0 h1:ZrMYQeKPECZPjOj5u9eyOjg8Nnb0BS9lkVIZ6IpsKLw=
github.com/go-redis/redismock/v9 v9.2.0/go.mod h1:18KHfGDK4Y6c2R0H38EUGWAdc7ZQS9gfYxc94k7rWT0=
github.com/golang/mock v1.6.0 h1:ErTB+efbowRARo13NNdxyJji2egdxLGQhRaY+DUumQc=
github.com/golang/mock v1.6.0/go.mod h1:p6yTPP+5HYm5mzsMV8JkE6ZKdX+/wYM6Hr+LicevLPs=
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
Expand Down
210 changes: 210 additions & 0 deletions internal/models/models_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,210 @@
package models

import (
"html"
"testing"
"time"
)

func TestUser_Sanitize(t *testing.T) {
user := &User{
ID: 1,
Username: "<script>alert('XSS')</script>",
Email: "<b>[email protected]</b>",
Password: "\" onmouseover=alert('XSS')",
Profile: 10,
}

user.Sanitize()

if user.Username != html.EscapeString("<script>alert('XSS')</script>") {
t.Errorf("Username not sanitized properly: got %v", user.Username)
}
if user.Email != html.EscapeString("<b>[email protected]</b>") {
t.Errorf("Email not sanitized properly: got %v", user.Email)
}
if user.Password != html.EscapeString("\" onmouseover=alert('XSS')") {
t.Errorf("Password not sanitized properly: got %v", user.Password)
}
}

func TestProfile_Sanitize(t *testing.T) {
profile := &Profile{
ID: 2,
FirstName: "<first>name</first>",
LastName: "<last>name</last>",
Age: 30,
BirthdayDate: "<birthday>2000-01-01</birthday>",
Gender: "<gender>male</gender>",
Target: "<target>some target</target>",
About: "<about>something</about>",
}

profile.Sanitize()

if profile.FirstName != html.EscapeString("<first>name</first>") {
t.Errorf("FirstName not sanitized: %v", profile.FirstName)
}
if profile.LastName != html.EscapeString("<last>name</last>") {
t.Errorf("LastName not sanitized: %v", profile.LastName)
}
if profile.BirthdayDate != html.EscapeString("<birthday>2000-01-01</birthday>") {
t.Errorf("BirthdayDate not sanitized: %v", profile.BirthdayDate)
}
if profile.Gender != html.EscapeString("<gender>male</gender>") {
t.Errorf("Gender not sanitized: %v", profile.Gender)
}
if profile.Target != html.EscapeString("<target>some target</target>") {
t.Errorf("Target not sanitized: %v", profile.Target)
}
if profile.About != html.EscapeString("<about>something</about>") {
t.Errorf("About not sanitized: %v", profile.About)
}
}

func TestImage_Sanitize(t *testing.T) {
img := &Image{
Id: 1,
Link: "<img src=x onerror=alert('XSS')>",
Number: 5,
}
img.Sanitize()

if img.Link != html.EscapeString("<img src=x onerror=alert('XSS')>") {
t.Errorf("Link not sanitized: %v", img.Link)
}
}

func TestPersonCard_Sanitize(t *testing.T) {
card := &PersonCard{
UserId: 10,
Username: "<u>user</u>",
Profile: Profile{ID: 1, FirstName: "John", LastName: "Doe"},
Images: []Image{{Id: 1, Link: "<img>", Number: 1}},
}
card.Sanitize()

if card.Username != html.EscapeString("<u>user</u>") {
t.Errorf("Username not sanitized: %v", card.Username)
}
}

func TestSession_Sanitize(t *testing.T) {
session := &Session{
SessionID: "<session>",
UserID: 123,
CreatedAt: time.Now(),
ExpiresAt: time.Now().Add(time.Hour),
}
session.Sanitize()

if session.SessionID != html.EscapeString("<session>") {
t.Errorf("SessionID not sanitized: %v", session.SessionID)
}
}

func TestReport_Sanitize(t *testing.T) {
report := &Report{
ID: 1,
Author: 2,
Receiver: 3,
Reason: "<reason>hack</reason>",
Body: "<body>text</body>",
}
report.Sanitize()

if report.Reason != html.EscapeString("<reason>hack</reason>") {
t.Errorf("Reason not sanitized: %v", report.Reason)
}
if report.Body != html.EscapeString("<body>text</body>") {
t.Errorf("Body not sanitized: %v", report.Body)
}
}

func TestMessage_Sanitize(t *testing.T) {
msg := &Message{
ID: 1,
Author: 10,
Receiver: 20,
Body: "<script>alert('msg')</script>",
Time: "2024-12-17T20:29:10Z",
}
msg.Sanitize()

if msg.Body != html.EscapeString("<script>alert('msg')</script>") {
t.Errorf("Body not sanitized: %v", msg.Body)
}
}

func TestProduct_Sanitize(t *testing.T) {
product := &Product{
Title: "<title>prod</title>",
Description: "<desc>description</desc>",
ImageLink: "<img>image</img>",
Price: 100,
}
product.Sanitize()

if product.Title != html.EscapeString("<title>prod</title>") {
t.Errorf("Title not sanitized: %v", product.Title)
}
if product.Description != html.EscapeString("<desc>description</desc>") {
t.Errorf("Description not sanitized: %v", product.Description)
}
if product.ImageLink != html.EscapeString("<img>image</img>") {
t.Errorf("ImageLink not sanitized: %v", product.ImageLink)
}
}

func TestSurvey_Initialize(t *testing.T) {
survey := Survey{
ID: 1,
Author: 2,
Question: "What is your name?",
Comment: "Nice survey",
Rating: 5,
Grade: 2,
}
// Здесь нет Sanitize(), просто проверим, что поля корректно присвоены
if survey.ID != 1 || survey.Author != 2 || survey.Question != "What is your name?" ||
survey.Comment != "Nice survey" || survey.Rating != 5 || survey.Grade != 2 {
t.Errorf("Survey fields not set correctly: %+v", survey)
}
}

func TestSurveyStat_Initialize(t *testing.T) {
stat := SurveyStat{
Question: "Q?",
Grade: 3,
Rating: 4.5,
Sum: 9,
Count: 2,
}
// Проверим базовую инициализацию
if stat.Question != "Q?" || stat.Grade != 3 || stat.Rating != 4.5 ||
stat.Sum != 9 || stat.Count != 2 {
t.Errorf("SurveyStat fields not set correctly: %+v", stat)
}
}

func TestAdminQuestion_Initialize(t *testing.T) {
aq := AdminQuestion{
Content: "Q content",
Grade: 1,
}
if aq.Content != "Q content" || aq.Grade != 1 {
t.Errorf("AdminQuestion fields not set correctly: %+v", aq)
}
}

func TestReaction_Initialize(t *testing.T) {
reaction := Reaction{
Id: 10,
Author: 20,
Receiver: 30,
Type: true,
}
if reaction.Id != 10 || reaction.Author != 20 || reaction.Receiver != 30 || reaction.Type != true {
t.Errorf("Reaction fields not set correctly: %+v", reaction)
}
}
160 changes: 160 additions & 0 deletions internal/pkg/auth/repo/memory_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
package auth

import (
"context"
"errors"
"testing"
"time"

sparkiterrors "github.com/go-park-mail-ru/2024_2_SaraFun/internal/errors"
"github.com/go-park-mail-ru/2024_2_SaraFun/internal/models"
"github.com/go-redis/redismock/v9"
"go.uber.org/zap"
)

func TestInMemoryStorage_AddSession(t *testing.T) {
logger := zap.NewNop()
db, mock := redismock.NewClientMock()
repo := New(db, logger)

ctx := context.Background()
session := models.Session{
SessionID: "session123",
UserID: 10,
CreatedAt: time.Now(),
ExpiresAt: time.Now().Add(24 * time.Hour),
}

t.Run("error", func(t *testing.T) {
mock.ExpectSet("session123", "10", 24*time.Hour).SetErr(errors.New("set error"))

err := repo.AddSession(ctx, session)
if err == nil || !contains(err.Error(), "add session failed") {
t.Errorf("expected error got %v", err)
}
})
}

func TestInMemoryStorage_GetUserIDBySessionID(t *testing.T) {
logger := zap.NewNop()
db, mock := redismock.NewClientMock()
repo := New(db, logger)

ctx := context.Background()
sessionID := "sessionXYZ"

t.Run("success", func(t *testing.T) {
mock.ExpectGet(sessionID).SetVal("123")

userID, err := repo.GetUserIDBySessionID(ctx, sessionID)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
if userID != 123 {
t.Errorf("got %d, want 123", userID)
}
if err := mock.ExpectationsWereMet(); err != nil {
t.Errorf("unmet expectations: %v", err)
}
})

t.Run("not found", func(t *testing.T) {
mock.ExpectGet(sessionID).RedisNil()

_, err := repo.GetUserIDBySessionID(ctx, sessionID)
if err == nil || !errors.Is(err, sparkiterrors.ErrInvalidSession) {
t.Errorf("expected ErrInvalidSession got %v", err)
}
})

t.Run("invalid value", func(t *testing.T) {
mock.ExpectGet(sessionID).SetVal("not-a-number")

_, err := repo.GetUserIDBySessionID(ctx, sessionID)
if err == nil || !contains(err.Error(), "convert session id") {
t.Errorf("expected convert error got %v", err)
}
})
}

func TestInMemoryStorage_CheckSession(t *testing.T) {
logger := zap.NewNop()
db, mock := redismock.NewClientMock()
repo := New(db, logger)

ctx := context.Background()
sessionID := "checkSession"

t.Run("valid session", func(t *testing.T) {
mock.ExpectGet(sessionID).SetVal("456")

err := repo.CheckSession(ctx, sessionID)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
if err := mock.ExpectationsWereMet(); err != nil {
t.Errorf("unmet expectations: %v", err)
}
})

t.Run("not found", func(t *testing.T) {
mock.ExpectGet(sessionID).RedisNil()

err := repo.CheckSession(ctx, sessionID)
if err == nil || !errors.Is(err, sparkiterrors.ErrInvalidSession) {
t.Errorf("expected ErrInvalidSession got %v", err)
}
})

t.Run("invalid value", func(t *testing.T) {
mock.ExpectGet(sessionID).SetVal("abc")

err := repo.CheckSession(ctx, sessionID)
if err == nil || !contains(err.Error(), "convert session id") {
t.Errorf("expected convert error got %v", err)
}
})
}

func TestInMemoryStorage_DeleteSession(t *testing.T) {
logger := zap.NewNop()
db, mock := redismock.NewClientMock()
repo := New(db, logger)

ctx := context.Background()
sessionID := "deleteSession"

t.Run("success", func(t *testing.T) {
mock.ExpectDel(sessionID).SetVal(1)

err := repo.DeleteSession(ctx, sessionID)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
if err := mock.ExpectationsWereMet(); err != nil {
t.Errorf("unmet expectations: %v", err)
}
})

t.Run("error", func(t *testing.T) {
mock.ExpectDel(sessionID).SetErr(errors.New("del error"))

err := repo.DeleteSession(ctx, sessionID)
if err == nil || !contains(err.Error(), "delete session failed") {
t.Errorf("expected error got %v", err)
}
})
}

func contains(s, substr string) bool {
return len(s) >= len(substr) && searchSubstring(s, substr)
}

func searchSubstring(s, sub string) bool {
for i := 0; i+len(sub) <= len(s); i++ {
if s[i:i+len(sub)] == sub {
return true
}
}
return false
}
1 change: 1 addition & 0 deletions internal/pkg/message/delivery/grpc/handlers_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
package grpc_test
Loading

0 comments on commit 6905ebd

Please sign in to comment.