saasitone/pkg/tests/tests.go

61 lines
1.7 KiB
Go
Raw Normal View History

package tests
import (
"context"
"fmt"
2021-12-25 18:04:19 -08:00
"math/rand"
"net/http"
"net/http/httptest"
"strings"
2021-12-21 17:29:15 -08:00
"testing"
"time"
2022-01-01 07:44:18 -08:00
"github.com/mikestefanello/pagoda/ent"
2022-01-20 15:02:14 -08:00
"github.com/stretchr/testify/assert"
2021-12-21 17:29:15 -08:00
"github.com/stretchr/testify/require"
"github.com/gorilla/sessions"
"github.com/labstack/echo-contrib/session"
"github.com/labstack/echo/v4"
)
2022-02-10 05:56:07 -08:00
// NewContext creates a new Echo context for tests using an HTTP test request and response recorder
func NewContext(e *echo.Echo, url string) (echo.Context, *httptest.ResponseRecorder) {
req := httptest.NewRequest(http.MethodGet, url, strings.NewReader(""))
rec := httptest.NewRecorder()
return e.NewContext(req, rec), rec
}
2022-02-10 05:56:07 -08:00
// InitSession initializes a session for a given Echo context
func InitSession(ctx echo.Context) {
mw := session.Middleware(sessions.NewCookieStore([]byte("secret")))
_ = ExecuteMiddleware(ctx, mw)
}
2022-02-10 05:56:07 -08:00
// ExecuteMiddleware executes a middleware function on a given Echo context
func ExecuteMiddleware(ctx echo.Context, mw echo.MiddlewareFunc) error {
handler := mw(func(c echo.Context) error {
return nil
})
return handler(ctx)
}
2022-02-10 05:56:07 -08:00
// AssertHTTPErrorCode asserts an HTTP status code on a given Echo HTTP error
2021-12-21 17:29:15 -08:00
func AssertHTTPErrorCode(t *testing.T, err error, code int) {
httpError, ok := err.(*echo.HTTPError)
require.True(t, ok)
assert.Equal(t, code, httpError.Code)
}
2022-02-10 05:56:07 -08:00
// CreateUser creates a random user entity
func CreateUser(orm *ent.Client) (*ent.User, error) {
2021-12-25 18:04:19 -08:00
seed := fmt.Sprintf("%d-%d", time.Now().UnixMilli(), rand.Intn(1000000))
return orm.User.
Create().
SetEmail(fmt.Sprintf("testuser-%s@localhost.localhost", seed)).
SetPassword("password").
SetName(fmt.Sprintf("Test User %s", seed)).
Save(context.Background())
}