WIP: Add server unit testing #73

Draft
luca0N wants to merge 14 commits from dev_server_tests into dev
Owner

Create tests in the server project, as required by issue #11.

  • account.go
  • api.go
  • config.go
  • crypto.go
  • db.go
  • env.go
  • lib.go
  • main.go
  • net.go
  • ws.go
Create tests in the server project, as required by issue #11. - [x] `account.go` - [ ] `api.go` - [x] `config.go` - [x] `crypto.go` - [x] `db.go` - [x] `env.go` - [ ] `lib.go` - [ ] `main.go` - [x] `net.go` - [x] `ws.go`
luca0N self-assigned this 2026-05-12 23:21:52 +00:00
Create tests for private functions in the `account.go' source file.
Create tests for private functions in the `net.go' source file.  The
`isHostAuthorized()` function has been omitted in the tests for this
commit, as it requires configuration parsing.
Create tests for private functions in the `crypto.go' source file, and
add new variable to `crypto.go' to prevent double initialization via
`initCrypto()'.
Create tests for private functions in the `config.go' source file, and
fix an issue which caused the default value for the
`config.Accounts.RequireAuth' option to be `true' instead of `false'.
Create tests for some functions in the `ws.go' source file.  Functions
that require mocking (those that invoke `net/http', WebSockets, and
`db.go') have not been worked on for now, and will be addressed in a
future commit.
Instead of printing with a `\n' line break at the end of a string when
calling `fmt.Println', remove it and call the function with an empty
string afterwards.  This is needed, as `go test' complains about the
extra line break being unneeded (which, in this case, it wasn't).
Author
Owner

Some testing will require mocks to simulate things like database connections, and WebSocket connections.

Some testing will require mocks to simulate things like database connections, and WebSocket connections.
Create a test for a function in the `env.go' source file.  Since
environment key values are retrived using the `os' package from the Go
standard library directly, the main function for the source file was not
included in the test.
Create tests for functions in the `db.go' source file by adding
`go-sqlmock' as a new dependency.  SQL statements are now mocked in this
new source file for unit tests.
luca0N left a comment

Some changes are needed in this file.

Some changes are needed in this file.
@ -0,0 +63,4 @@
rows := sqlmock.NewRows([]string{"id"}).
AddRow(id)
// FIXME: make this a LIMIT 1!
mock.ExpectQuery("SELECT id FROM users WHERE username = (.+);").WillReturnRows(rows)
Author
Owner

As the comment suggests, this (and the original source file from which this statement was based upon) need to be updated to include LIMIT 1.

As the comment suggests, this (and the original source file from which this statement was based upon) need to be updated to include `LIMIT 1`.
luca0N marked this conversation as resolved
@ -0,0 +77,4 @@
// TODO: actually check the sessionToken in the query
rows := sqlmock.NewRows([]string{"user_id"}).
AddRow(userId)
mock.ExpectQuery(`SELECT user_id FROM sessions WHERE token = UNHEX(\(.+)\) LIMIT 1;`).WillReturnRows(rows)
Author
Owner

This whole source file makes use of regular expressions for expected statements. A lot of them could use some work to account for the testing of more issues, with this token being an example. The expected query should contain sessionToken.

This whole source file makes use of regular expressions for expected statements. A lot of them could use some work to account for the testing of more issues, with this `token` being an example. The expected query should contain `sessionToken`.
Author
Owner

Fixed by using .WithArgs().

Fixed by using `.WithArgs()`.
luca0N marked this conversation as resolved
@ -0,0 +118,4 @@
func TestCheckSchema(t *testing.T) {
mock, err := initDatabaseMock()
if err != nil {
t.Errorf(`initDatabaseMock() = "%s", want nil`, err)
Author
Owner

The possibility of using the %v format for errors should be evaluated. Additionally, having the error message in quotes here is misleading, as it could imply that the function has returned a string type instead of an error.

The possibility of using the `%v` format for errors should be evaluated. Additionally, having the error message in quotes here is misleading, as it could imply that the function has returned a string type instead of an error.
luca0N marked this conversation as resolved
@ -0,0 +125,4 @@
mockCheckDatabaseSchemaExists(mock)
mockGetDatabaseSchemaVersion(mock)
checkSchema()
Author
Owner

To preserve consistency with the rest of the file, the blank line between the mock functions and checkSchema() must be removed.

To preserve consistency with the rest of the file, the blank line between the mock functions and `checkSchema()` must be removed.
luca0N marked this conversation as resolved
Refactor unit tests for the `db.go' source file.  This commit makes SQL
mocks more strict by adding argument constraints (where possible), and
adds `LIMIT 1' to a query statement, which only expects upwards of one
result.
Add unit testing functions that check the preflight response for API
endpoints in the server.
Add new unit testing functions to check for API route support (since
some of them may be disabled depending on the server configuration), add
checks for common headers (that must be present in all responses), and
perform some minor code refactoring by creating a new common internal
function (`checkPreflight').
@ -0,0 +84,4 @@
return fmt.Errorf(`len(data) = %d, want 0`, len(data))
}
got := res.Header.Get("Access-Control-Allow-Methods")
Author
Owner

This function should check for other preflight headers, such as Access-Control-Allow-Origin, and Access-Control-Allow-Headers.

Additionally, this function should also check for a 204 No Content response status code.

This function should check for other preflight headers, such as `Access-Control-Allow-Origin`, and `Access-Control-Allow-Headers`. Additionally, this function should also check for a 204 No Content response status code.
luca0N changed title from Add server unit testing to WIP: Add server unit testing 2026-06-05 11:19:08 +00:00
Add new test functions that send malformed requests to the API route
handler functions, and checks whether their behavior is expected (which
is to fail with an HTTP 400 Bad Request status code, and the response
should have LANBASSADOR_RESPONSE_CODE_ERROR_MALFORMED_REQUEST as the
`response_code' field).

There were two tests created for both the `/account' and `/session'
routes, one that sends a request with payload but without the
Content-Type header, and another that does the opposite: it sends a
request without a payload, and correctly sets the Content-Type header.

At this time, the two tests that send empty request payloads will fail,
as there seems to be an issue with their respective API route request
handlers.  This issue will be addressed in a separate commit.
@ -0,0 +297,4 @@
if err != nil || !got {
t.Errorf(`checkEndpointMalformed(%v, "%s", %v) = (%t, %v), want (true, nil)`, http.HandlerFunc(handleEndpointApiSession), contentType, payloadBytes, got, err)
}
}
Author
Owner

Both the TestEndpointApiAccountPostNoPayload and the TestEndpointApiSessionPostNoPayload tests fail, as explained in the commit message for 2a3d557720.

The issue needs to be investigated.

Both the `TestEndpointApiAccountPostNoPayload` and the `TestEndpointApiSessionPostNoPayload` tests fail, as explained in the commit message for 2a3d557720eee2426b03e425da139d993552dc8e. The issue needs to be investigated.
Add missing code that checks for all CORS headers set in preflight
requests.

This code does not check for CORS headers set in non-preflight requests.
Fix an issue which caused the server to incorrectly send API responses
indicating an internal server error to requests with malformed JSON
payloads.

This commit fixes the issue mentioned in
2a3d557720.
This pull request is marked as a work in progress.
This branch is out-of-date with the base branch
View command line instructions

Checkout

From your project repository, check out a new branch and test the changes.
git fetch -u origin dev_server_tests:dev_server_tests
git switch dev_server_tests

Merge

Merge the changes and update on Forgejo.
git switch dev
git merge --no-ff dev_server_tests
git switch dev_server_tests
git rebase dev
git switch dev
git merge --ff-only dev_server_tests
git switch dev_server_tests
git rebase dev
git switch dev
git merge --no-ff dev_server_tests
git switch dev
git merge --squash dev_server_tests
git switch dev
git merge --ff-only dev_server_tests
git switch dev
git merge dev_server_tests
git push origin dev
Sign in to join this conversation.
No reviewers
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Blocks
#11 Add tests
luca0N/lanbassador
Reference
luca0N/lanbassador!73
No description provided.