So far, every rule in TaskFlow was checked by sending curl requests by hand. After twelve parts there are many rules, and a change in one part can break a rule from another, for example a policy change that lets Ben delete Ana’s tasks. This part adds tests that send the same requests and check the answers, so one go test run checks the rules again after any change.
The tests need a database of their own. Each feature test starts from empty tables, by rolling the migrations back and running them again, and on the dev database that would wipe Ana, her tasks and everything else, so the tests get their own database, taskflow_test:
The tests also need settings that point at that database. Goravel reads .env.testing instead of .env when go test gets --env=.env.testing. It starts as a copy of .env.example:
Terminal window
cp.env.example.env.testing
These lines change:
.env.testing
APP_NAME=Goravel
APP_ENV=local
APP_KEY=
APP_ENV=testing
APP_KEY=2Nr9bpCIal8Dj0qYE7IviHcYcwzmVqoh
APP_DEBUG=true
8 collapsed lines
LOG_CHANNEL=stack
LOG_LEVEL=debug
SESSION_DRIVER=file
SESSION_LIFETIME=120
APP_URL=http://localhost
APP_HOST=127.0.0.1
APP_PORT=3000
JWT_SECRET=
JWT_SECRET=xRQKZ4WHIu8bIHANdQVnskdTsa47cya8
DB_CONNECTION=postgres
DB_HOST=127.0.0.1
DB_PORT=5433
DB_DATABASE=taskflow
DB_DATABASE=taskflow_test
DB_USERNAME=goravel
DB_PASSWORD=secret
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=
REDIS_PORT=6380
CACHE_STORE=memory
HASH_ROUNDS=4
The two new settings do nothing yet, since config/cache.go always uses Redis and config/hashing.go always uses 12 rounds. Both now read their value from the env and keep the old value as the default, so only the tests get the new settings:
config/cache.go
9 collapsed lines
packageconfig
import(
"github.com/goravel/framework/contracts/cache"
redisfacades "github.com/goravel/redis/facades"
"taskflow/app/facades"
)
funcinit(){
config := facades.Config()
config.Add("cache",map[string]any{
"default":"redis",
"default": config.Env("CACHE_STORE","redis"),
// Cache Stores
27 collapsed lines
//
// Here you may define all the cache "stores" for your application as
// well as their drivers. You may even define multiple stores for the
// same cache driver to group types of items stored in your caches.
// Available Drivers: "memory", "custom"
"stores":map[string]any{
"memory":map[string]any{
"driver":"memory",
},
"redis":map[string]any{
"driver":"custom",
"connection":"default",
"via":func()(cache.Driver,error){
return redisfacades.Cache("redis")// The `redis` value is the key of `stores`
},
},
},
// Cache Key Prefix
//
// When utilizing a RAM based store such as APC or Memcached, there might
// be other applications utilizing the same cache. So, we'll specify a
// value to get prefixed to all our keys, so we can avoid collisions.
// This option controls the default diver that gets used
// by the framework hash facade.
// Default driver is "bcrypt".
//
// Supported Drivers: "bcrypt", "argon2id"
"driver":"bcrypt",
// Bcrypt Hashing Options
// rounds: The cost factor that should be used to compute the bcrypt hash.
// The cost factor controls how much time is needed to compute a single bcrypt hash.
// The higher the cost factor, the more hashing rounds are done. Increasing the cost
// factor by 1 doubles the necessary time. After a certain point, the returns on
// hashing time versus attacker time are diminishing, so choose your cost factor wisely.
"bcrypt":map[string]any{
"rounds":12,
"rounds": config.Env("HASH_ROUNDS",12),
},
12 collapsed lines
// Argon2id Hashing Options
// memory: A memory cost, which defines the memory usage, given in kibibytes.
// time: A time cost, which defines the amount of computation
// realized and therefore the execution time, given in number of iterations.
// threads: A parallelism degree, which defines the number of parallel threads.
"argon2id":map[string]any{
"memory":65536,
"time":4,
"threads":1,
},
})
}
CACHE_STORE=memory keeps the tests’ cache in memory. The tests empty the cache before each test, and with Redis that would empty the whole Redis server, including the dev app’s logged-out tokens and login counts.
HASH_ROUNDS=4 makes bcrypt cheap. Every test user and every login hashes a password, and at the usual 12 rounds the suite takes about 6 seconds instead of 1.
.env.testing goes into git, so a fresh clone can run the tests once the database exists. Its APP_KEY and JWT_SECRET are made up, and any 32 characters work, so nothing in it is a real secret. .gitignore skips every .env.* file except .env.example, so add an exception:
.gitignore
.idea
.vscode
.DS_Store
.env
.env.*
!.env.example
!.env.testing
storage
tmp
A test case that boots the app
A test needs the app started the way main.go starts it, with its config, database and routes. Goravel’s Testing package does that. Lite only installs the facades picked when the project is created, and Installation & Project Architecture didn’t pick Testing, so install it now with package:install:
panic("the tests drop every table, so they only run on a database whose name ends in _test: go test ./tests/... --env=.env.testing")
}
}
typeTestCasestruct{
testing.TestCase
}
Go runs init once in each test package that imports taskflow/tests, before its tests. bootstrap.Boot() is the call main.go makes, so the tests run the real app.
The check reads the database name from the config. If the name doesn’t end in _test, the run stops with the guard’s message. That catches a plain go test without --env, and an .env.testing that still says taskflow.
Embedding Goravel’s testing.TestCase gives every test Http for requests and RefreshDatabase for the empty tables.
Unit tests for the custom rules
A unit test checks one piece of code on its own, without the database or a request. The custom rules fit that well, because a rule’s Passes gets a value and returns true or false. They are MaxBytes from Register & Login with JWT and FutureDate from Validation with Form Requests. make:test creates their test file:
Terminal window
gorun.artisanmake:testunit/RulesTest
SUCCESSTestcreatedsuccessfully
It writes a testify suite, a struct whose methods are the tests:
tests/unit/rules_test.go
packageunit
import(
"testing"
"github.com/stretchr/testify/suite"
"taskflow/tests"
)
typeRulesTestSuitestruct{
suite.Suite
tests.TestCase
}
funcTestRulesTestSuite(t *testing.T){
suite.Run(t,new(RulesTestSuite))
}
// SetupTest will run before each test in the suite.
func(s *RulesTestSuite)SetupTest(){
}
// TearDownTest will run after each test in the suite.
func(s *RulesTestSuite)TearDownTest(){
}
func(s *RulesTestSuite)TestIndex(){
// TODO
}
RulesTestSuite embeds suite.Suite, which gives it testify’s checks like s.Equal, and tests.TestCase from the last section.
TestRulesTestSuite is the only function go test itself runs. Its suite.Run then calls every method on the struct whose name starts with Test.
SetupTest and TearDownTest run before and after each of those methods, and TestIndex is a placeholder.
The rules need no setup, so the file becomes one test per rule:
tests/unit/rules_test.go
packageunit
import(
"context"
"strings"
"testing"
"github.com/goravel/framework/support/carbon"
"github.com/stretchr/testify/suite"
"taskflow/app/rules"
"taskflow/tests"
)
typeRulesTestSuitestruct{
suite.Suite
tests.TestCase
}
funcTestRulesTestSuite(t *testing.T){
suite.Run(t,new(RulesTestSuite))
}
func(s *RulesTestSuite)TestMaxBytes(){
cases :=[]struct{
name string
value any
passes bool
}{
{"72 bytes", strings.Repeat("a",72),true},
{"73 bytes", strings.Repeat("a",73),false},
{"18 emoji are 72 bytes", strings.Repeat("🔒",18),true},
{"19 emoji are 76 bytes", strings.Repeat("🔒",19),false},
Each case has a name, a value, and whether the rule should pass it. This table-driven style is common in Go tests, and when a case fails, s.Equal prints the case’s name.
🔒 is 4 bytes, so 18 of them are exactly 72 bytes and pass. 19 of them are only 19 characters but 76 bytes, and that case fails because the rule counts bytes, not characters.
The tests run with go test ./tests/... --env=.env.testing. Without --env, the guard stops the run before any test, the unit tests included, since they import taskflow/tests too, and its init boots the app. Here and below, the output shows only the test lines:
Note Go also lets a unit test sit next to its code, like app/rules/max_bytes_test.go, and a plain go test ./app/rules/ runs it. Either way works, and TaskFlow keeps every test in tests/ so one command runs them all.
Requests without a token
A feature test sends a request through the routes, the middleware and the handler, as curl did, and checks the answer. The first one checks the simplest rule, that every route behind the auth middleware refuses a request without a valid token. make:test creates its file:
Terminal window
gorun.artisanmake:testfeature/AuthTest
SUCCESSTestcreatedsuccessfully
It writes the same suite as RulesTest. Replace it with the checks:
tests/feature/auth_test.go
packagefeature
import(
"testing"
"github.com/goravel/framework/support/http"
"github.com/stretchr/testify/suite"
"taskflow/app/facades"
"taskflow/app/models"
"taskflow/tests"
)
typeAuthTestSuitestruct{
suite.Suite
tests.TestCase
}
funcTestAuthTestSuite(t *testing.T){
suite.Run(t,new(AuthTestSuite))
}
func(s *AuthTestSuite)SetupTest(){
s.RefreshDatabase()
}
func(s *AuthTestSuite)TestRoutesNeedAToken(){
for _, path :=range[]string{"/api/v1/tasks","/api/v1/tasks/1","/api/v1/users","/api/v1/me"}{
SetupTest calls RefreshDatabase, so every test starts with empty tables in taskflow_test.
s.Http(s.T()) is Goravel’s test client. It hands the request straight to the router, with no server and no port, so air doesn’t need to run.
The login request’s body is built with Goravel’s http.NewBody(): SetFields takes the fields as a map, and Build turns them into JSON, so no JSON is written by hand. body.Reader() is what Post sends, and body.ContentType() is the header that goes with it.
AssertUnauthorized checks for a 401.
The run now includes the feature tests:
Terminal window
gotest./tests/...--env=.env.testing
? taskflow/tests [no test files]
oktaskflow/tests/feature0.769s
oktaskflow/tests/unit0.653s
MoreThe test client and its assertions
s.Http(s.T()) starts a request. These are the methods the tests here use, and Goravel’s HTTP tests docs list the rest:
WithToken sends a Bearer token, and WithHeader any other header.
Get takes the path, and Post, Patch and Delete also take a body, an io.Reader, or nil for none.
Bind fills a struct from the response’s JSON.
AssertStatus checks for any code, and the common ones have their own name, like AssertOk, AssertCreated, AssertUnauthorized and AssertNotFound.
AssertFluentJson checks top-level keys with Where, so a nested value like errors.title needs Bind.
Goravel’s assertions, like testify’s assert, mark a test as failed and let it carry on. testify’s require, called as s.Require(), stops the test at the first failure instead. The tests use it to check each request’s error, since a failed request has no response to check.
Every role rule in one table
The next test checks every role rule from Gates & Policies. Each rule is one row in a table, saying who sends which request and the status it should get, so a broken rule fails under its own name. make:test creates the file:
Terminal window
gorun.artisanmake:testfeature/TaskTest
SUCCESSTestcreatedsuccessfully
Replace the new suite with the table and the users it needs:
SetupTest creates Ana, Ben and Cat with the user factory from Factories & Seeding, so each has the password password. Ben and Cat each get a task.
login logs in through POST /api/v1/login, the way a client does, and reads the token with Bind.
Each row’s body is a map, or nil when the request sends none. Every row builds a body, so the loop stays the same for all of them, but only POST and PATCH send it.
The login limit from Auth Middleware counts attempts in the cache, and RefreshDatabase doesn’t touch the cache. Cache().Flush() resets the counts, so one test’s logins don’t use up the next test’s.
s.Run runs each row as its own test, named after the row.
The rows share the same tasks, so Ana’s delete comes last.
AuthTest logs in too, so it gets the same Flush, and each suite starts with clean counts whichever runs first:
tests/feature/auth_test.go
22 collapsed lines
packagefeature
import(
"testing"
"github.com/goravel/framework/support/http"
"github.com/stretchr/testify/suite"
"taskflow/app/facades"
"taskflow/app/models"
"taskflow/tests"
)
typeAuthTestSuitestruct{
suite.Suite
tests.TestCase
}
funcTestAuthTestSuite(t *testing.T){
suite.Run(t,new(AuthTestSuite))
}
func(s *AuthTestSuite)SetupTest(){
s.RefreshDatabase()
s.Require().True(facades.Cache().Flush())
}
24 collapsed lines
func(s *AuthTestSuite)TestRoutesNeedAToken(){
for _, path :=range[]string{"/api/v1/tasks","/api/v1/tasks/1","/api/v1/users","/api/v1/me"}{
To see the table catch a mistake, in app/policies/task_policy.go, change Delete to return access.NewAllowResponse(), so members may delete, and run the tests again:
Expected response status code [204] but received 404.
FAIL
FAIL taskflow/tests/feature 0.845s
ok taskflow/tests/unit 0.677s
FAIL
The member’s row names the rule and the status it got.
Ana’s delete then gets a 404, because Ben’s went through and the task is gone.
Change Delete back before going on.
Checking the body and the database
A status code doesn’t show everything a request did. A 201 could carry the wrong creator, and a 204 could come back without deleting anything, so most of the new tests check the body or the database, and two more cover a missing task and logging out:
Bind reads the created task into a models.Task, and the test checks that its creator is Ana, its assignee is Ben and its status is pending.
A task id that doesn’t exist gets a 404.
The bad-input test checks which fields have errors, not the messages, so a reworded message doesn’t break it.
The update test uses AssertFluentJson to check that the title and description are still the same after a status-only change.
After the 204, the delete test counts the task’s rows in the test database, and Count must be 0.
In the logout test, Cat logs out and then sends her token again, and that request gets a 401.
The whole suite passes:
Terminal window
gotest./tests/...--env=.env.testing
? taskflow/tests [no test files]
oktaskflow/tests/feature1.071s
oktaskflow/tests/unit0.713s
Gotcha testify keeps one suite struct for all its tests, so after the first test s.ana still holds an id, and that’s why SetupTest creates the users into new variables first. Creating Ana straight into s.ana would save her with that old id, but the emptied tables start their ids from 1 again, so the next new user gets the same id:
New variables start with no id, so the database gives each one a fresh id.
MoreWhy the tests use the real database
Goravel can swap facades.Orm() for a mock, but then every query has to be scripted by hand. These tests run the real app against taskflow_test instead. That’s slower, but the tests get the same answers a client would.
When a test must not touch a service, such as an email provider, Goravel can replace a facade with a mock. Code that takes its dependencies as arguments instead of calling facades can be given a fake directly.
One go test ./tests/... --env=.env.testing now checks every role rule from Gates & Policies, the token checks and the main task endpoints, in about a second.