Adds the database abstraction layer (DAL) with a Transactions method and a Connection object to encapsulate the DB open connection. Includes a DAL unit test using the go-sqlmock library. Connection to a PostgreSQL database using environment variables to store the secrets. Overall, with the /transactions endpoint requesting directly to the DB, this patch finish the tracer bullet project. Issues #1, #5, #6 and #7
44 lines
877 B
Go
44 lines
877 B
Go
package dal
|
|
|
|
import (
|
|
"database/sql/driver"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/DATA-DOG/go-sqlmock"
|
|
)
|
|
|
|
type AnyTime struct{}
|
|
|
|
func (t AnyTime) Match(v driver.Value) bool {
|
|
_, ok := v.(time.Time)
|
|
return ok
|
|
}
|
|
|
|
// type AnyDecimal struct{}
|
|
|
|
func TestTransactions(t *testing.T) {
|
|
db, mock, err := sqlmock.New()
|
|
if err != nil {
|
|
t.Fatalf("failed to create a mock DB: %s", err)
|
|
}
|
|
defer db.Close()
|
|
|
|
conn := Connection{db}
|
|
|
|
rows := sqlmock.NewRows([]string{"date", "description", "amount"}).
|
|
AddRow(time.Now(), "income", 1000).
|
|
AddRow(time.Now(), "expense", -500)
|
|
|
|
mock.ExpectQuery("SELECT t.date, t.description, t.amount").WithoutArgs().WillReturnRows(rows)
|
|
|
|
transactions := conn.Transactions()
|
|
if len(transactions) <= 0 {
|
|
t.Error("No transactions returned")
|
|
}
|
|
|
|
if err := mock.ExpectationsWereMet(); err != nil {
|
|
t.Errorf("unfulfilled expectations: %s", err)
|
|
}
|
|
}
|