Files
notas-online/internal/api/api_test.go
T
lgcosta 9bc5de4c56 feat: aplicação inicial — gerenciador de notas web estilo Mousepad
- Backend Go: API REST, auth por token (Bearer + cookie HttpOnly), storage em disco
  com revisões content-addressed (estilo Git: hash, autor, data, diff, restauração)
- Editor txt/md/html com preview, tags #tag, categorias, painel de histórico
- Preferências: números de linha, marcador de coluna (padrão 80), quebra de linha,
  fonte/tamanho, 4 temas e colorização de sintaxe (overlay no textarea)
- Frontend vanilla embutido via go:embed; Dockerfile multi-stage + docker-compose
2026-11-04 09:41:46 -03:00

272 lines
8.3 KiB
Go

package api_test
import (
"bytes"
"encoding/json"
"io"
"io/fs"
"net/http"
"net/http/httptest"
"strings"
"testing"
"testing/fstest"
"github.com/lgcosta/notas-online/internal/api"
"github.com/lgcosta/notas-online/internal/store"
)
const testToken = "s3cr3t-token"
func newTestServer(t *testing.T) *httptest.Server {
t.Helper()
st, err := store.New(t.TempDir())
if err != nil {
t.Fatal(err)
}
webFS := fs.FS(fstest.MapFS{"index.html": &fstest.MapFile{Data: []byte("<html>MOUSEPAD-SHELL</html>")}})
srv := httptest.NewServer(api.New(st, testToken, webFS).Handler())
t.Cleanup(srv.Close)
return srv
}
func do(t *testing.T, srv *httptest.Server, method, path, body, bearer, cookie string) *http.Response {
t.Helper()
var rdr io.Reader
if body != "" {
rdr = strings.NewReader(body)
}
req, err := http.NewRequest(method, srv.URL+path, rdr)
if err != nil {
t.Fatal(err)
}
if bearer != "" {
req.Header.Set("Authorization", "Bearer "+bearer)
}
if cookie != "" {
req.Header.Add("Cookie", cookie)
}
resp, err := srv.Client().Do(req)
if err != nil {
t.Fatal(err)
}
return resp
}
func decode(t *testing.T, resp *http.Response, v any) {
t.Helper()
defer resp.Body.Close()
if err := json.NewDecoder(resp.Body).Decode(v); err != nil {
t.Fatalf("decodificando resposta %s %s: %v", resp.Status, resp.Request.URL.Path, err)
}
}
type noteView struct {
ID string `json:"id"`
Title string `json:"title"`
Format string `json:"format"`
Category string `json:"category"`
Tags []string `json:"tags"`
Hash string `json:"hash"`
Content string `json:"content"`
}
func TestAuthRequiredAndLoginFlow(t *testing.T) {
srv := newTestServer(t)
// Sem token: API bloqueia.
if resp := do(t, srv, "GET", "/api/notes", "", "", ""); resp.StatusCode != http.StatusUnauthorized {
t.Fatalf("esperava 401 sem token, obtive %s", resp.Status)
}
resp := do(t, srv, "GET", "/api/notes", "", "token-errado", "")
if resp.StatusCode != http.StatusUnauthorized {
t.Fatalf("bearer errado deveria dar 401, obtive %s", resp.Status)
}
// Login errado.
resp = do(t, srv, "POST", "/api/login", `{"token":"nope"}`, "", "")
if resp.StatusCode != http.StatusUnauthorized {
t.Fatalf("login errado: %s", resp.Status)
}
// Login correto: cookie HttpOnly emitido.
resp = do(t, srv, "POST", "/api/login", `{"token":"`+testToken+`"}`, "", "")
if resp.StatusCode != http.StatusOK {
t.Fatalf("login: %s", resp.Status)
}
sc := resp.Header.Get("Set-Cookie")
if !strings.Contains(sc, "notas_token="+testToken) || !strings.Contains(sc, "HttpOnly") ||
strings.Contains(sc, "Max-Age=0") {
t.Errorf("Set-Cookie inadequado: %q", sc)
}
cookieValue := strings.SplitN(strings.TrimPrefix(sc, "notas_token="), ";", 2)[0]
// /api/me com o cookie.
resp = do(t, srv, "GET", "/api/me", "", "", "notas_token="+cookieValue)
if resp.StatusCode != http.StatusOK {
t.Fatalf("/api/me com cookie: %s", resp.Status)
}
// Logout limpa o cookie.
resp = do(t, srv, "POST", "/api/logout", "", "", "notas_token="+cookieValue)
resp.Body.Close()
sc = resp.Header.Get("Set-Cookie")
if !strings.Contains(sc, "Max-Age=0") && !strings.Contains(sc, "Expires=Thu, 01 Jan 1970") {
t.Errorf("logout deveria expirar o cookie: %q", sc)
}
// Index é público e servido do FS embutido.
resp = do(t, srv, "GET", "/", "", "", "")
var buf bytes.Buffer
_, _ = buf.ReadFrom(resp.Body)
resp.Body.Close()
if !strings.Contains(buf.String(), "MOUSEPAD-SHELL") {
t.Errorf("index não servido: %q", buf.String())
}
}
func TestNoteLifecycleWithHistoryAndRestore(t *testing.T) {
srv := newTestServer(t)
call := func(method, path, body string) *http.Response {
return do(t, srv, method, path, body, testToken, "")
}
// Criar.
resp := call("POST", "/api/notes",
`{"title":"Servidor","format":"md","category":"devops","content":"# Notas\n\n#linux #systemd","author":"lg","message":""}`)
if resp.StatusCode != http.StatusCreated {
t.Fatalf("create: %s", resp.Status)
}
var created noteView
decode(t, resp, &created)
if created.ID == "" || len(created.Tags) != 2 {
t.Fatalf("payload criado: %+v", created)
}
id := created.ID
// Listar com filtro de tag.
resp = call("GET", "/api/notes?tag=linux", "")
var list []noteView
decode(t, resp, &list)
if len(list) != 1 || list[0].Content != "" { // listagem não carrega conteúdo
t.Fatalf("list: %+v", list)
}
// Ler completo.
resp = call("GET", "/api/notes/"+id, "")
var got noteView
decode(t, resp, &got)
if !strings.Contains(got.Content, "#systemd") {
t.Fatalf("get: %+v", got)
}
// Atualizar: nova revisão.
resp = call("PUT", "/api/notes/"+id,
`{"title":"Servidor","format":"md","category":"devops","content":"# Notas\n\n#linux","author":"lg","message":"removi systemd"}`)
var updated noteView
decode(t, resp, &updated)
if updated.Hash == created.Hash {
t.Fatal("hash não mudou após edição de conteúdo")
}
// Histórico: mais recente primeiro, com parent e mensagem.
resp = call("GET", "/api/notes/"+id+"/revisions", "")
var revs []store.Revision
decode(t, resp, &revs)
if len(revs) != 2 || revs[0].Message != "removi systemd" || revs[0].Parent != created.Hash {
t.Fatalf("revisões: %+v", revs)
}
// Diff da revisão atual.
resp = call("GET", "/api/notes/"+id+"/revisions/"+revs[0].Hash+"/diff", "")
var dv struct {
Diff string `json:"diff"`
Added int `json:"added"`
Removed int `json:"removed"`
}
decode(t, resp, &dv)
if !strings.Contains(dv.Diff, "-#linux #systemd") || !strings.Contains(dv.Diff, "+#linux") {
t.Fatalf("diff: %q", dv.Diff)
}
if dv.Added != 1 || dv.Removed != 1 {
t.Fatalf("stats do diff: +%d -%d", dv.Added, dv.Removed)
}
// Restaurar a primeira revisão.
resp = call("POST", "/api/notes/"+id+"/revisions/"+created.Hash+"/restore", `{"author":"lg"}`)
if resp.StatusCode != http.StatusOK {
t.Fatalf("restore: %s", resp.Status)
}
var restored noteView
decode(t, resp, &restored)
if !strings.Contains(restored.Content, "#systemd") {
t.Fatalf("restore não trouxe conteúdo antigo: %+v", restored)
}
// Restaurar de novo → 409.
resp = call("POST", "/api/notes/"+id+"/revisions/"+created.Hash+"/restore", `{"author":"lg"}`)
if resp.StatusCode != http.StatusConflict {
t.Fatalf("esperava 409, obtive %s", resp.Status)
}
resp.Body.Close()
// Download bruto com Content-Disposition.
resp = call("GET", "/api/notes/"+id+"/raw", "")
if cd := resp.Header.Get("Content-Disposition"); !strings.Contains(cd, `attachment; filename="Servidor.md"`) {
t.Errorf("Content-Disposition: %q", cd)
}
resp.Body.Close()
// Deletar → 204, e GET passa a 404.
resp = call("DELETE", "/api/notes/"+id, "")
if resp.StatusCode != http.StatusNoContent {
t.Fatalf("delete: %s", resp.Status)
}
resp = call("GET", "/api/notes/"+id, "")
if resp.StatusCode != http.StatusNotFound {
t.Fatalf("get pós-delete: %s", resp.Status)
}
}
func TestRenderMarkdownIsSafe(t *testing.T) {
srv := newTestServer(t)
resp := do(t, srv, "POST", "/api/render",
`{"content":"**negrito** <script>alert(1)</script>\nlinha1\nlinha2","format":"md"}`, testToken, "")
var out struct{ HTML string `json:"html"` }
decode(t, resp, &out)
if !strings.Contains(out.HTML, "<strong>negrito</strong>") {
t.Errorf("markdown não renderizado: %q", out.HTML)
}
if strings.Contains(out.HTML, "<script>") {
t.Errorf("HTML cru deveria ser escapado: %q", out.HTML)
}
if !strings.Contains(out.HTML, "<br") {
t.Errorf("quebra de linha simples deveria virar <br>: %q", out.HTML)
}
// html não é renderizado no servidor.
resp = do(t, srv, "POST", "/api/render", `{"content":"<b>x</b>","format":"html"}`, testToken, "")
if resp.StatusCode != http.StatusBadRequest {
t.Errorf("formato html deveria retornar 400, obtive %s", resp.Status)
}
resp.Body.Close()
}
func TestInvalidPayloads(t *testing.T) {
srv := newTestServer(t)
resp := do(t, srv, "POST", "/api/notes", `{"format":"rtf","content":"x"}`, testToken, "")
if resp.StatusCode != http.StatusBadRequest {
t.Fatalf("formato inválido: %s", resp.Status)
}
resp.Body.Close()
resp = do(t, srv, "POST", "/api/notes", `{"token":"extra"}`, testToken, "")
if resp.StatusCode != http.StatusBadRequest {
t.Fatalf("campo desconhecido deveria falhar (DisallowUnknownFields): %s", resp.Status)
}
resp.Body.Close()
resp = do(t, srv, "GET", "/api/notes/z0zzzzzzzzzz/revisions", "", testToken, "")
if resp.StatusCode != http.StatusNotFound {
t.Fatalf("nota inexistente: %s", resp.Status)
}
resp.Body.Close()
}