cacert-boardvoting/cmd/boardvoting/handlers_test.go
Jan Dittberner 335ce16547 Add tests for handlers and middleware
- drop migration 2022052601_drop_unused_decisions_colums because it was implicitly part of an earlier migration
- add /health endpoint for database health check
- add tests for the health check endpoint
- add tests for middleware secureHeaders, logRequest and tryAuthenticate
- add models.UserModel.CreateUser method
2022-05-26 19:22:56 +02:00

92 lines
2 KiB
Go

/*
Copyright 2022 CAcert Inc.
SPDX-License-Identifier: Apache-2.0
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package main
import (
"database/sql"
"net/http"
"net/http/httptest"
"path"
"testing"
"github.com/jmoiron/sqlx"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"git.cacert.org/cacert-boardvoting/internal/models"
)
func prepareTestDb(t *testing.T) *sqlx.DB {
t.Helper()
testDir := t.TempDir()
db, err := sql.Open("sqlite3", path.Join(testDir, "test.sqlite"))
require.NoError(t, err)
dbx := sqlx.NewDb(db, "sqlite3")
return dbx
}
func TestApplication_healthCheck(t *testing.T) {
t.Run("check with valid DB", func(t *testing.T) {
rr := httptest.NewRecorder()
r, err := http.NewRequest(http.MethodGet, "/health", nil)
require.NoError(t, err)
testDB := prepareTestDb(t)
app := &application{
motions: &models.MotionModel{DB: testDB},
}
app.healthCheck(rr, r)
rs := rr.Result()
assert.Equal(t, http.StatusOK, rs.StatusCode)
})
t.Run("check with broken DB", func(t *testing.T) {
rr := httptest.NewRecorder()
r, err := http.NewRequest(http.MethodGet, "/health", nil)
require.NoError(t, err)
testDir := t.TempDir()
db, err := sql.Open("sqlite3", path.Join(testDir, "test.sqlite"))
require.NoError(t, err)
testDB := sqlx.NewDb(db, "sqlite3")
_ = db.Close()
app := &application{
motions: &models.MotionModel{DB: testDB},
}
app.healthCheck(rr, r)
rs := rr.Result()
assert.Equal(t, http.StatusInternalServerError, rs.StatusCode)
})
}