package model import ( "git.nagee.dev/isthisnagee/diary/db" "runtime/debug" "testing" ) func assert_string(t *testing.T, expected string, actual string) { if actual != expected { t.Log(string(debug.Stack())) t.Fatalf("(%v, %v)", expected, actual) } } func assert_int(t *testing.T, expected int64, actual int64) { if actual != expected { t.Log(string(debug.Stack())) t.Fatalf("(%v, %v)", expected, actual) } } func assert_bool(t *testing.T, expected bool, actual bool) { if actual != expected { t.Log(string(debug.Stack())) t.Fatalf("(%v, %v)", expected, actual) } } func assert_exists(t *testing.T, actual interface{}) { if actual == nil { t.Log(string(debug.Stack())) t.Fatalf("Unexpected nil: %s", actual) } } func setup() App { var db_ctx, err = db.Init(":memory:") if err != nil { panic(err) } return App{db_ctx} } func teardown(app App) { app.Db.Close() } func TestNewDiaryEntry(t *testing.T) { var app = setup() var result = app.NewDiaryEntry("Met with Nagee @ 1PM") assert_string(t, "Met with Nagee @ 1PM", result.Title) assert_exists(t, result.Id) assert_exists(t, result.CreatedAt) assert_exists(t, result.Version) teardown(app) } func TestGetDiaryEntry(t *testing.T) { var app = setup() var inserted_result = app.NewDiaryEntry("Met with Nagee @ 1PM") queried_result, _ := app.GetDiaryEntry(inserted_result.Id) assert_int(t, inserted_result.Id, queried_result.Id) assert_int(t, inserted_result.CreatedAt, queried_result.CreatedAt) assert_int(t, inserted_result.Version, queried_result.Version) assert_string(t, inserted_result.Title, queried_result.Title) teardown(app) } func DeleteDiaryEntry(t *testing.T) { var app = setup() var inserted_result = app.NewDiaryEntry("Met with Nagee @ 1PM") is_deleted, _ := app.DeleteDiaryEntry(inserted_result.Id) assert_bool(t, true, is_deleted) _, err := app.GetDiaryEntry(inserted_result.Id) switch err_type := err.(type) { case *NotFoundError: // Do nothing break default: t.Fatalf("Expected NotFoundError, got %s", err_type) } teardown(app) } func DeleteDiaryEntryNotFound(t *testing.T) { var app = setup() _, err := app.DeleteDiaryEntry(-1) switch err_type := err.(type) { case *NotFoundError: // Do nothing break default: t.Fatalf("Expected NotFoundError, got %s", err_type) } teardown(app) } func TestGetDiaryEntries(t *testing.T) { var app = setup() var result_1 = app.NewDiaryEntry("Met with Nagee @ 1PM") var result_2 = app.NewDiaryEntry("Met with Nagee @ 2PM") // no numEntries entries := app.GetDiaryEntries( GetDiaryEntriesQuery{}, ) assert_int(t, int64(len(entries)), 2) assert_int(t, result_2.Id, entries[0].Id) assert_int(t, result_1.Id, entries[1].Id) var numEntries = new(int64) *numEntries = 1 entries = app.GetDiaryEntries( GetDiaryEntriesQuery{ NumEntries: numEntries, }, ) assert_int(t, int64(len(entries)), 1) assert_int(t, result_2.Id, entries[0].Id) teardown(app) }