Skip to content

Commit 674a859

Browse files
committed
test(clap counter): test cases for clap counter GET and POST methods
1 parent 4a153bd commit 674a859

14 files changed

+590
-185
lines changed

go.mod

+1
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ require (
88
)
99

1010
require (
11+
github.com/DATA-DOG/go-sqlmock v1.5.2 // indirect
1112
github.com/didip/tollbooth v4.0.2+incompatible // indirect
1213
github.com/didip/tollbooth/v8 v8.0.1 // indirect
1314
github.com/go-pkgz/expirable-cache/v3 v3.0.0 // indirect

go.sum

+3
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
github.com/DATA-DOG/go-sqlmock v1.5.2 h1:OcvFkGmslmlZibjAjaHm3L//6LiuBgolP7OputlJIzU=
2+
github.com/DATA-DOG/go-sqlmock v1.5.2/go.mod h1:88MAG/4G7SMwSE3CeA0ZKzrT5CiOU3OJ+JlNzwDqpNU=
13
github.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiErDT4WkJ2k=
24
github.com/aymanbagabas/go-osc52/v2 v2.0.1/go.mod h1:uYgXzlJ7ZpABp8OJ+exZzJJhRNQ2ASbcXHWsFqH8hp8=
35
github.com/charmbracelet/lipgloss v0.12.1 h1:/gmzszl+pedQpjCOH+wFkZr/N90Snz40J/NR7A0zQcs=
@@ -18,6 +20,7 @@ github.com/gorilla/handlers v1.5.2 h1:cLTUSsNkgcwhgRqvCNmdbRWG0A3N4F+M2nWKdScwyE
1820
github.com/gorilla/handlers v1.5.2/go.mod h1:dX+xVpaxdSw+q0Qek8SSsl3dfMk3jNddUkMzo0GtH0w=
1921
github.com/gorilla/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY=
2022
github.com/gorilla/mux v1.8.1/go.mod h1:AKf9I4AEqPTmMytcMc0KkNouC66V3BtZ4qD5fmWSiMQ=
23+
github.com/kisielk/sqlstruct v0.0.0-20201105191214-5f3e10d3ab46/go.mod h1:yyMNCyc/Ib3bDTKd379tNMpB/7/H5TjM2Y9QJ5THLbE=
2124
github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY=
2225
github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=
2326
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=

src/app/app.go

+13-4
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import (
77
"fmt"
88
"os"
99
"path/filepath"
10+
fp "path/filepath"
1011
)
1112

1213
type App struct {
@@ -15,10 +16,11 @@ type App struct {
1516
}
1617

1718
type Config struct {
18-
ServerConfig server.ServerConfig
19-
Name string
20-
Version string
21-
Env string
19+
ServerConfig server.ServerConfig
20+
Name string
21+
Version string
22+
Env string
23+
BaseDirectory string
2224
}
2325

2426
func (app *App) Start() {
@@ -32,6 +34,13 @@ func LoadConfig(filepath string) Config {
3234
fmt.Println(err)
3335
return Config{}
3436
}
37+
baseDir, err := os.Getwd()
38+
if err != nil {
39+
panic(err)
40+
}
41+
config.BaseDirectory = baseDir
42+
config.ServerConfig.BaseDirectory = baseDir
43+
config.ServerConfig.DB.DBBaseDirectory = fp.Join(baseDir, "src/db")
3544
return config
3645
}
3746

src/db/db.go

+11-7
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import (
77
"fmt"
88
"log"
99
"os"
10+
"path/filepath"
1011

1112
"github.com/golang-migrate/migrate"
1213
"github.com/golang-migrate/migrate/database/sqlite3"
@@ -16,10 +17,11 @@ import (
1617
)
1718

1819
type DB struct {
19-
DBLocation string
20-
Vacuum string
21-
ForeignKeys bool
22-
Connection *sql.DB
20+
DBLocation string
21+
Vacuum string
22+
ForeignKeys bool
23+
Connection *sql.DB
24+
DBBaseDirectory string
2325
}
2426

2527
func closeDB(new_db *sql.DB) {
@@ -57,7 +59,8 @@ func (db *DB) Initialize() error {
5759
closeDB(new_db)
5860
return err
5961
}
60-
err = runMigrations(new_db)
62+
migrationFiles := filepath.Join(db.DBBaseDirectory, "migrations")
63+
err = runMigrations(new_db, migrationFiles)
6164
if err != nil {
6265
log.Println("Error Running Migrations")
6366
closeDB(new_db)
@@ -67,14 +70,15 @@ func (db *DB) Initialize() error {
6770
return nil
6871
}
6972

70-
func runMigrations(db *sql.DB) error {
73+
func runMigrations(db *sql.DB, migrationFiles string) error {
7174
instance, err := sqlite3.WithInstance(db, &sqlite3.Config{})
7275
if err != nil {
7376
log.Printf("Error Connecting With SQLite Instance: %s", err)
7477
return err
7578
}
7679

77-
fSrc, err := (&file.File{}).Open("./src/db/migrations")
80+
fSrc, err := (&file.File{}).Open(migrationFiles)
81+
print()
7882
if err != nil {
7983
closeFile(fSrc)
8084
log.Printf("Error Getting Migration Files: %s", err)

src/db/query.go

+7
Original file line numberDiff line numberDiff line change
@@ -55,3 +55,10 @@ const updateLike = `INSERT INTO Likes(uri, count, domain_id)
5555
ON CONFLICT(uri)
5656
DO UPDATE
5757
SET count = count + 1`
58+
59+
const addDomainAndSettings = `BEGIN TRANSACTION;
60+
INSERT INTO DomainSettings (likes, comments, created_time)
61+
VALUES (?, ?, datetime());
62+
INSERT INTO Domain (settings_id, domain, created_time)
63+
VALUES (last_insert_rowid(), ?, datetime());
64+
COMMIT TRANSACTION;`

src/db/utils.go

+8-1
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,7 @@ func GetLikedIP(db *sql.DB, domain string, page string, ip string) LikedIPs {
6565
log.Printf("DB: IP %s, Not Found Liked in %s for %s", ip, domain, page)
6666
return LikedIPs{}
6767
}
68-
log.Printf("Error Getting Likes On %s For %s: %v", ip, page, err)
68+
log.Printf("Error Getting LikedIPs On %s For %s: %v", ip, page, err)
6969
return LikedIPs{}
7070
}
7171
return likedIP
@@ -83,3 +83,10 @@ func UpdateLikeCount(db *sql.DB, page string, doamin_id int) error {
8383
_, err := db.Exec(updateLike, page, doamin_id)
8484
return err
8585
}
86+
87+
func AddDomainAndSettings(db *sql.DB, domain string, likes int, comments int) {
88+
_, err := db.Exec(addDomainAndSettings, likes, comments, domain)
89+
if err != nil {
90+
log.Printf("Error Adding Domain %s: %v", domain, err)
91+
}
92+
}

src/server/handlers/clap_counter.go

+5-8
Original file line numberDiff line numberDiff line change
@@ -65,10 +65,7 @@ func get_likes(r *http.Request, clapCounter ClapCounter) db.Likes {
6565
func already_liked_IP(r *http.Request, clapCounter ClapCounter) bool {
6666
db_connection := get_db_connection(r)
6767
liked_ips := db.GetLikedIP(db_connection, clapCounter.URL, clapCounter.Page, clapCounter.remote_addr)
68-
if liked_ips.IsEmpty() {
69-
return false
70-
}
71-
return true
68+
return !liked_ips.IsEmpty()
7269
}
7370

7471
// add_like_to_page updates the like count for the given page and domain ID in the database.
@@ -105,6 +102,10 @@ func add_like_to_page(r *http.Request, clapCounter ClapCounter, doamin_id int) e
105102
func GetClaps(w http.ResponseWriter, r *http.Request) {
106103
var clapCounter ClapCounter
107104
var continue_counting bool = true
105+
content_type_err := check_for_request_content_type(w, r)
106+
if content_type_err != nil {
107+
return
108+
}
108109
clapCounter.remote_addr = r.RemoteAddr
109110
clapCounter.URL = get_domain(r.Referer())
110111
clapCounter.Page = get_path(r, w)
@@ -127,10 +128,6 @@ func GetClaps(w http.ResponseWriter, r *http.Request) {
127128
case http.MethodGet:
128129
clapCounter.SetClapCounter(clapCounter.URL, ClapCount, likes.Count, true)
129130
case http.MethodPost:
130-
content_type_err := check_for_request_content_type(w, r)
131-
if content_type_err != nil {
132-
return
133-
}
134131
if already_liked_IP(r, clapCounter) {
135132
clapCounter.SetClapCounter(clapCounter.URL, ClapAlreadyCounted, likes.Count, false)
136133
} else {

src/server/handlers/ping.go

+15-7
Original file line numberDiff line numberDiff line change
@@ -3,27 +3,35 @@ package handlers
33

44
import (
55
"encoding/json"
6-
"errors"
6+
"log"
77
"net/http"
88
)
99

1010
// Ping is an HTTP handler that responds with a "pong" message.
1111
// It also checks the connection to the database and returns an error if the connection fails.
1212
func Ping(w http.ResponseWriter, r *http.Request) {
13+
msg := "pong"
1314
db := get_db_connection(r)
1415
if db != nil {
1516
err := db.Ping()
1617
if err != nil {
17-
setHTTPError(w, err, "Database Error", http.StatusInternalServerError)
18+
w.WriteHeader(http.StatusInternalServerError)
19+
msg = "Database Ping Error"
1820
}
1921

2022
} else {
21-
msg := "Database Not Found"
22-
setHTTPError(w, errors.New(msg), "Database Error", http.StatusInternalServerError)
23+
w.WriteHeader(http.StatusInternalServerError)
24+
msg = "Database Not Found"
2325
}
24-
p := map[string]string{"message": "pong"}
25-
err := json.NewEncoder(w).Encode(p)
26+
responseBody := map[string]string{"message": msg}
27+
jsonData, err := json.Marshal(responseBody)
2628
if err != nil {
27-
setHTTPError(w, err, "JSON Error", http.StatusInternalServerError)
29+
log.Printf("Error Encoding JSON: %v", err.Error())
30+
return
31+
}
32+
w.Header().Set("Content-Type", "application/json")
33+
_, err = w.Write(jsonData)
34+
if err != nil {
35+
log.Printf("Error writing response: %v", err)
2836
}
2937
}

src/server/handlers/tests/clap_counter_test.go

-115
This file was deleted.

0 commit comments

Comments
 (0)