Adding tests

This commit is contained in:
2025-11-04 14:41:49 -05:00
parent 13e0efb67c
commit 3e2efae4ce
3 changed files with 37 additions and 17 deletions

View File

@@ -2,31 +2,28 @@ package db
import (
"database/sql"
"fmt"
"io/ioutil"
"go-sjles-pta-vote/config"
"os"
_ "github.com/glebarez/go-sqlite"
)
var db *sql.DB
func Connect() error {
func Connect(db_path string) error {
var err error
db, err = sql.Open("sqlite", dbConfig.DBPath)
db, err = sql.Open("sqlite", db_path)
if err != nil {
return err
}
sql_create, err := ioutil.ReadFile("./db_format.sql")
sql_create, err := os.ReadFile("./db_format.sql")
if err != nil {
return err
}
_, err = db.Exec(sql_create)
_, err = db.Exec(string(sql_create))
return err
}
@@ -35,4 +32,4 @@ func Close() {
if db != nil {
_ = db.Close()
}
}
}

View File

@@ -1,5 +1,5 @@
CREATE TABLE IF NOT EXISTS poll (
id UNSIGNED INT NOT NULL AUTOINCREMENT,
CREATE TABLE IF NOT EXISTS polls (
id INTEGER PRIMARY KEY,
question TEXT NOT NULL,
member_yes_votes UNSIGNED INT NOT NULL,
member_no_votes UNSIGNED INT NOT NULL,
@@ -7,19 +7,18 @@ CREATE TABLE IF NOT EXISTS poll (
non_member_no_votes UNSIGNED INT NOT NULL,
created_at DATETIME,
updated_at DATETIME,
expires_at DATETIME,
PRIMARY KEY (id)
)
expires_at DATETIME
);
CREATE TABLE IF NOT EXISTS voters (
poll_id UNSIGNED INT NOT NULL,
voter_email TEXT NOT NULL,
FOREIGN KEY (poll_id) poll(id),
FOREIGN KEY (poll_id) REFERENCES polls(id),
PRIMARY KEY (poll_id, voter_email)
)
);
CREATE TABLE IF NOT EXISTS members (
email TEXT NOT NULL,
member_name TEXT,
PRIMARY KEY (email)
)
);

24
server/db/db_test.go Normal file
View File

@@ -0,0 +1,24 @@
package db
import (
"os"
"testing"
)
func TestConnect(t *testing.T) {
tmp_db, err := os.CreateTemp("", "vote_test.*.db")
tmp_db_name := tmp_db.Name()
tmp_db.Close()
defer os.Remove(tmp_db_name)
if err != nil {
t.Errorf(`Failed to create temporary db: %v`, err)
}
if err := Connect(tmp_db_name); err != nil {
t.Errorf(`Failed to create the database at %s: %v`, tmp_db_name, err)
}
defer Close()
}