Skip to content

Commit

Permalink
Add unit tests
Browse files Browse the repository at this point in the history
  • Loading branch information
jasonmci committed Oct 1, 2024
1 parent c6f5309 commit f3043df
Show file tree
Hide file tree
Showing 9 changed files with 299 additions and 87 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
*.db
*.txt
*.out
test/manualcheck.sql
52 changes: 36 additions & 16 deletions database.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ func initializeDatabase() *sql.DB {
date DATE NOT NULL,
half_hour INTEGER NOT NULL CHECK (half_hour BETWEEN 0 AND 47),
task_name TEXT,
status TEXT DEFAULT 'in progress',
status TEXT DEFAULT 'active',
FOREIGN KEY (task_id) REFERENCES tasks(id) ON DELETE CASCADE
UNIQUE(task_id, date, half_hour)
);`
Expand All @@ -85,6 +85,37 @@ func initializeDatabase() *sql.DB {
return db
}

func getDailyTasks(db *sql.DB) ([]Task, error){
query := `
SELECT id, name, estimate, actual, created_at, updated_at, done
FROM tasks
WHERE DATE(datetime(created_at, 'localtime')) = DATE('now', 'localtime')
ORDER BY created_at;
`

rows, err := db.Query(query)
if err != nil {
log.Fatal(err)
}
defer rows.Close()

var tasks []Task
for rows.Next() {
var id, estimate, actual int
var name string
var createdAt, updatedAt time.Time
var done bool

err := rows.Scan(&id, &name, &estimate, &actual, &createdAt, &updatedAt, &done)
if err != nil {
log.Fatal(err)
}

tasks = append(tasks, Task{ ID: id, Name: name, Estimate: estimate, Actual: actual, CreatedAt: createdAt, UpdatedAt: updatedAt, Done: done })
}
return tasks, nil
}

func getMonthlyData(db *sql.DB) ([]DayAggregate, error) {
query := `
SELECT
Expand Down Expand Up @@ -133,18 +164,6 @@ func getAllDaysOfMonth() []string {
return days
}

// func getAllDaysOfWeek() []string {
// var days []string
// now := time.Now()

// for i := 0; i < 7; i++ {
// day := now.AddDate(0, 0, -int(now.Weekday())+i)
// days = append(days, day.Format("2006-01-02"))
// }

// return days
// }

func getYearlyData(db *sql.DB, year int) ([]TaskTrackingAggregate, error) {
// aggregate half_hours completed for each day for the year
query := fmt.Sprintf(`
Expand Down Expand Up @@ -293,17 +312,19 @@ func addTask(db *sql.DB, name string, estimate int) error {
func activateTask(id int) {
// get current date in yyyy-mm-dd format
// insert into task_tracking table

currentDate := time.Now().Format("2006-01-02")
half_hour := getHalfHour(time.Now().Hour(), time.Now().Minute())
insertTrackingTask(id, currentDate, half_hour)
}

func insertTrackingTask(id int, currentDate string, halfHour int) {
query := `
INSERT INTO task_tracking (task_id, date, half_hour, status)
VALUES (?, ?, ?, 'active')
ON CONFLICT(task_id, date, half_hour)
DO UPDATE SET status = 'done';
`
_, err := db.Exec(query, id, currentDate, half_hour)
_, err := db.Exec(query, id, currentDate, halfHour)
if err != nil {
log.Fatal(err)
}
Expand All @@ -316,7 +337,6 @@ func updateActual(id int) {
if err != nil {
log.Fatal(err)
}


rowsAffected, err := result.RowsAffected()
if err != nil {
Expand Down
142 changes: 142 additions & 0 deletions database_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
package main

import (
"database/sql"
"fmt"
"time"

//"log"
"testing"
//"time"

_ "github.com/mattn/go-sqlite3" // SQLite driver
)

// Mock database connection for tests
var testDB *sql.DB

// Setup test database (in-memory SQLite)
func setupTestDB2(t *testing.T) {
var err error
testDB, err = sql.Open("sqlite3", ":memory:")
if err != nil {
t.Fatalf("failed to open test database: %v", err)
}

// Create tasks table if it doesn't exist
createTableQuery := `
CREATE TABLE IF NOT EXISTS tasks (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
estimate INTEGER NOT NULL,
actual INTEGER DEFAULT 0,
created_at DATETIME DEFAULT (datetime('now', 'localtime')),
updated_at DATETIME DEFAULT (datetime('now', 'localtime')),
done BOOLEAN DEFAULT 0
);`
_, err = testDB.Exec(createTableQuery)
if err != nil {
t.Fatalf("failed to create task_tracking table: %v", err)
}

// Create the task_tracking table schema for testing
query := `
CREATE TABLE task_tracking (
id INTEGER PRIMARY KEY AUTOINCREMENT,
task_id INTEGER NOT NULL,
date TEXT NOT NULL,
half_hour INTEGER NOT NULL,
status TEXT NOT NULL,
UNIQUE(task_id, date, half_hour)
);`
_, err = testDB.Exec(query)
if err != nil {
t.Fatalf("failed to create task_tracking table: %v", err)
}
}

// Helper function to check if a task exists in the database
func taskExists(t *testing.T, taskID int, date string, halfHour int, status string) bool {
var count int
query := `
SELECT COUNT(*) FROM task_tracking
WHERE task_id = ? AND date = ? AND half_hour = ? AND status = ?`

err := testDB.QueryRow(query, taskID, date, halfHour, status).Scan(&count)
if err != nil {
t.Fatalf("failed to query task: %v", err)
}
return count > 0
}

// Function to test activateTask
func TestActivateTask(t *testing.T) {
setupTestDB2(t) // Initialize the test database

db = testDB

mockDate := time.Now().Format("2006-01-02")
mockHalfHour := getHalfHour(time.Now().Hour(), time.Now().Minute())

fmt.Println(mockDate)
fmt.Println(mockHalfHour)

insertTrackingTask(1, mockDate, mockHalfHour)

// Check if the task was inserted with 'active' status
if !taskExists(t, 1, mockDate, mockHalfHour, "active") {
t.Errorf("expected task to be 'active', but it wasn't found")
}

// Test: Update the task to 'done' status
insertTrackingTask(1, mockDate, mockHalfHour)

// Check if the task was updated to 'done' status
if !taskExists(t, 1, mockDate, mockHalfHour, "done") {
t.Errorf("expected task to be updated to 'done', but it wasn't")
}
}

func TestInsertTrackingTask(t *testing.T) {
setupTestDB2(t) // Initialize the test database

db = testDB

mockDate := time.Now().Format("2006-01-02")
mockHalfHour := getHalfHour(time.Now().Hour(), time.Now().Minute())

// Test: Insert a new task with 'active' status
insertTrackingTask(1, mockDate, mockHalfHour)

// Check if the task was inserted with 'active' status
if !taskExists(t, 1, mockDate, mockHalfHour, "active") {
t.Errorf("expected task to be 'active', but it wasn't found")
}

// Test: Update the task to 'done' status
insertTrackingTask(1, mockDate, mockHalfHour)

// Check if the task was updated to 'done' status
if !taskExists(t, 1, mockDate, mockHalfHour, "done") {
t.Errorf("expected task to be updated to 'done', but it wasn't")
}
}

// add test for getDailyTasks
func TestGetDailyTasks(t *testing.T) {
setupTestDB2(t) // Initialize the test database

db = testDB

// Test: Insert a new task with 'active' status
err := addTask(db, "Task 1", 1)
if err != nil {
t.Fatalf("failed to add task: %v", err)
}

// Test: Get all tasks for the day
tasks, _ := getDailyTasks(db)
if len(tasks) != 1 {
t.Errorf("expected 1 task, got %d", len(tasks))
}
}
14 changes: 8 additions & 6 deletions helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,16 @@ import (

// Get start and end dates for the current week (Monday to Sunday)
func getCurrentWeek() (time.Time, time.Time) {
// Get the current date
now := time.Now().Local()
// Find the Monday of the current week
sunday := now.AddDate(0, 0, -int(now.Weekday()))
// Get the Sunday of the current week
saturday := sunday.AddDate(0, 0, 6)

sunday, saturday := getWeek(now)
return sunday, saturday
}

// Format as YYYY-MM-DD
func getWeek(mytime time.Time) (time.Time, time.Time) {

sunday := mytime.AddDate(0, 0, -int(mytime.Weekday()))
saturday := sunday.AddDate(0, 0, 6)
return sunday, saturday
}

Expand Down
30 changes: 30 additions & 0 deletions helpers_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"fmt"
"os"
"testing"
"time"

_ "github.com/mattn/go-sqlite3"
)
Expand Down Expand Up @@ -181,6 +182,35 @@ func TestHalfHour(t *testing.T) {
t.Errorf("getHalfHour(%d, %d) = %d; want %d", tt.hour, tt.minute, result, tt.expected)
}
}
}

// Mock version of time.Now() to simulate a specific date
func mockTimeNow(mockedTime time.Time) func() time.Time {
return func() time.Time {
return mockedTime
}
}

// Test for getCurrentWeek
func TestGetCurrentWeek(t *testing.T) {
// Mock the current date to be a Wednesday, September 20, 2024
mockDate := time.Date(2024, time.September, 20, 0, 0, 0, 0, time.Local)

// Replace time.Now with the mock
timeNow := mockTimeNow(mockDate)

// Call the function to get the week range
sunday, saturday := getWeek(timeNow())

// Expected Sunday and Saturday for the week of September 15–21, 2024
expectedSunday := time.Date(2024, time.September, 15, 0, 0, 0, 0, time.Local)
expectedSaturday := time.Date(2024, time.September, 21, 0, 0, 0, 0, time.Local)

// Check if the calculated Sunday and Saturday match the expected values
if !sunday.Equal(expectedSunday) {
t.Errorf("expected Sunday to be %v, but got %v", expectedSunday, sunday)
}
if !saturday.Equal(expectedSaturday) {
t.Errorf("expected Saturday to be %v, but got %v", expectedSaturday, saturday)
}
}
Loading

0 comments on commit f3043df

Please sign in to comment.