Compare commits

...

3 Commits

Author SHA1 Message Date
fullstack-engineer 89904a531e test(handlers): add coverage for plugin listing endpoints and helpers
Adds plugins_listing_test.go — 9 new tests covering:
- ListRegistry: all plugins returned, empty dir, runtime filter, unspecified
  runtimes included for all, manifest fields parsed, no-manifest dir fallback
- ListAvailableForWorkspace: runtime filter via runtimeLookup, unspecified
  runtimes included
- HTTP status: both endpoints return 200

Issue: #1815 follow-up — plugins_listing.go was at 0% coverage.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-17 09:24:51 +00:00
fullstack-engineer 5564b394fe test: add coverage for PatchAbilities, BroadcastHandler, ListSources, and cssVar
Go (3 files, 23 tests):
  workspace_abilities_test.go (9): PatchAbilities — 400 (invalid UUID /
    empty body / invalid JSON), 404 (workspace not found / DB error),
    200 (update each ability independently and both together)

  workspace_broadcast_test.go (13): BroadcastHandler + broadcastTruncate —
    400 (invalid UUID / missing message), 404 (not found), 403 (disabled
    with hint), 500 (recipient query error), 200 (no recipients / one
    recipient / recipient insert fails / sender log fails)

  plugins_sources_test.go (1): ListSources — returns 200 with schemes
    array from the real plugin registry, stable across calls

Canvas (1 file, 4 tests):
  theme.test.ts: cssVar — all 23 ColorToken variants, purity,
    hyphenated tokens, style-prop usability

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-17 09:12:00 +00:00
fullstack-engineer 8b03185cb2 test(canvas): add explicit STATUS_CONFIG shape coverage
STATUS_CONFIG exports 7 status keys (online, offline, paused, degraded,
failed, provisioning, not_configured) with dot/glow/label/bar per entry.
The existing statusDotClass.test.ts covered .dot indirectly but left the
constant's full shape (label, glow, bar) untested. Add a dedicated
design-tokens.test.ts that asserts all keys exist, every entry has the
correct fields, and field values match the known tailwind tokens.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-17 09:12:00 +00:00
6 changed files with 1199 additions and 0 deletions
@@ -0,0 +1,102 @@
// @vitest-environment jsdom
/**
* Tests for design-tokens.ts constant exports.
*
* STATUS_CONFIG is tested here directly rather than inside
* statusDotClass.test.ts so the constant's full shape (dot, glow, label,
* bar per key) is explicitly asserted — not just indirectly via the
* statusDotClass helper that consumes its .dot field.
*/
import { describe, it, expect } from "vitest";
import { STATUS_CONFIG } from "../design-tokens";
const ALL_STATUS_KEYS = [
"online",
"offline",
"paused",
"degraded",
"failed",
"provisioning",
"not_configured",
] as const;
describe("STATUS_CONFIG", () => {
it("has exactly the expected status keys and no extras", () => {
const actual = Object.keys(STATUS_CONFIG).sort();
const expected = [...ALL_STATUS_KEYS].sort();
expect(actual).toEqual(expected);
});
it("every entry has dot, glow, label, and bar fields", () => {
for (const key of ALL_STATUS_KEYS) {
const entry = STATUS_CONFIG[key];
expect(entry, `entry for "${key}"`).toHaveProperty("dot");
expect(entry, `entry for "${key}"`).toHaveProperty("glow");
expect(entry, `entry for "${key}"`).toHaveProperty("label");
expect(entry, `entry for "${key}"`).toHaveProperty("bar");
}
});
it("dot, glow, label, bar are all non-empty strings", () => {
for (const key of ALL_STATUS_KEYS) {
const entry = STATUS_CONFIG[key];
for (const field of ["dot", "glow", "label", "bar"] as const) {
expect(typeof entry[field], `"${key}".${field}`).toBe("string");
// label must be non-empty; others may be empty (e.g. offline.glow = "").
if (field === "label") {
expect(entry[field].length, `"${key}".${field}`).toBeGreaterThan(0);
}
}
}
});
it('online: dot is emerald, glow is set, label is "Online"', () => {
expect(STATUS_CONFIG.online.dot).toBe("bg-emerald-400");
expect(STATUS_CONFIG.online.glow).toBe("shadow-emerald-400/50");
expect(STATUS_CONFIG.online.label).toBe("Online");
expect(STATUS_CONFIG.online.bar).toBe("from-emerald-500/20 to-transparent");
});
it('offline: dot is zinc, glow is empty, label is "Offline"', () => {
expect(STATUS_CONFIG.offline.dot).toBe("bg-zinc-500");
expect(STATUS_CONFIG.offline.glow).toBe("");
expect(STATUS_CONFIG.offline.label).toBe("Offline");
expect(STATUS_CONFIG.offline.bar).toBe("from-zinc-600/10 to-transparent");
});
it('paused: dot is indigo, label is "Paused"', () => {
expect(STATUS_CONFIG.paused.dot).toBe("bg-indigo-400");
expect(STATUS_CONFIG.paused.glow).toBe("");
expect(STATUS_CONFIG.paused.label).toBe("Paused");
});
it('degraded: dot is amber with glow, label is "Degraded"', () => {
expect(STATUS_CONFIG.degraded.dot).toBe("bg-amber-400");
expect(STATUS_CONFIG.degraded.glow).toBe("shadow-amber-400/50");
expect(STATUS_CONFIG.degraded.label).toBe("Degraded");
});
it('failed: dot is red with glow, label is "Failed"', () => {
expect(STATUS_CONFIG.failed.dot).toBe("bg-red-400");
expect(STATUS_CONFIG.failed.glow).toBe("shadow-red-400/50");
expect(STATUS_CONFIG.failed.label).toBe("Failed");
});
it('provisioning: dot is sky with pulse animation, label is "Starting"', () => {
expect(STATUS_CONFIG.provisioning.dot).toBe("bg-sky-400 motion-safe:animate-pulse");
expect(STATUS_CONFIG.provisioning.glow).toBe("shadow-sky-400/50");
expect(STATUS_CONFIG.provisioning.label).toBe("Starting");
});
it('not_configured: dot is amber-300 with glow, label is "Not configured"', () => {
expect(STATUS_CONFIG.not_configured.dot).toBe("bg-amber-300");
expect(STATUS_CONFIG.not_configured.glow).toBe("shadow-amber-300/50");
expect(STATUS_CONFIG.not_configured.label).toBe("Not configured");
});
it("is a frozen static map — same key always returns same object reference", () => {
for (const key of ALL_STATUS_KEYS) {
expect(STATUS_CONFIG[key]).toBe(STATUS_CONFIG[key]);
}
});
});
+60
View File
@@ -0,0 +1,60 @@
// @vitest-environment jsdom
/**
* Tests for theme.ts — cssVar() function and ColorToken type.
*/
import { describe, it, expect } from "vitest";
import { cssVar, type ColorToken } from "../theme";
describe("cssVar", () => {
it("wraps each known token in a var() reference", () => {
const tokens: ColorToken[] = [
"surface",
"surface-elevated",
"surface-sunken",
"surface-card",
"line",
"line-soft",
"ink",
"ink-mid",
"ink-soft",
"accent",
"accent-strong",
"warm",
"good",
"bad",
"bg",
"bg-elev",
"bg-card",
"line-strong",
"ink-mute",
"ink-dim",
"accent-dim",
"plasma",
"warn",
];
for (const token of tokens) {
expect(cssVar(token)).toBe(`var(--color-${token})`);
}
});
it("is a pure function — same token always returns same value", () => {
for (let i = 0; i < 5; i++) {
expect(cssVar("accent")).toBe("var(--color-accent)");
expect(cssVar("surface")).toBe("var(--color-surface)");
expect(cssVar("good")).toBe("var(--color-good)");
}
});
it("handles hyphenated tokens correctly", () => {
expect(cssVar("surface-elevated")).toBe("var(--color-surface-elevated)");
expect(cssVar("line-soft")).toBe("var(--color-line-soft)");
expect(cssVar("ink-mute")).toBe("var(--color-ink-mute)");
});
it("produces a value usable as an inline style prop value", () => {
const result = cssVar("accent");
expect(typeof result).toBe("string");
expect(result.startsWith("var(--color-")).toBe(true);
expect(result.endsWith(")")).toBe(true);
});
});
@@ -0,0 +1,287 @@
package handlers
import (
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"testing"
"github.com/gin-gonic/gin"
)
// setupTestPlugins creates a temporary plugins directory with named
// subdirectories, each optionally containing a plugin.yaml manifest.
func setupTestPlugins(t *testing.T, plugins map[string]string /* name → yamlContents */) string {
t.Helper()
dir := t.TempDir()
for name, yaml := range plugins {
plugDir := filepath.Join(dir, name)
if err := os.MkdirAll(plugDir, 0755); err != nil {
t.Fatalf("setupTestPlugins: mkdir %s: %v", plugDir, err)
}
if yaml != "" {
if err := os.WriteFile(filepath.Join(plugDir, "plugin.yaml"), []byte(yaml), 0644); err != nil {
t.Fatalf("setupTestPlugins: write plugin.yaml for %s: %v", name, err)
}
}
}
return dir
}
// makeTestHandler creates a PluginsHandler wired with a stub runtimeLookup
// that always returns "claude-code".
func makeTestHandler(t *testing.T, pluginsDir string) *PluginsHandler {
t.Helper()
h := NewPluginsHandler(pluginsDir, nil, nil)
h.WithRuntimeLookup(func(workspaceID string) (string, error) {
return "claude-code", nil
})
return h
}
// listRegistry fires ListRegistry and returns the parsed []pluginInfo.
func listRegistry(h *PluginsHandler, runtime string) []pluginInfo {
gin.SetMode(gin.TestMode)
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Request = httptest.NewRequest("GET", "/plugins", nil)
if runtime != "" {
c.Request.URL.RawQuery = "runtime=" + runtime
}
h.ListRegistry(c)
var out []pluginInfo
json.Unmarshal(w.Body.Bytes(), &out)
return out
}
// listAvailable fires ListAvailableForWorkspace and returns the parsed []pluginInfo.
func listAvailable(h *PluginsHandler, workspaceID string) []pluginInfo {
gin.SetMode(gin.TestMode)
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Request = httptest.NewRequest("GET", "/workspaces/"+workspaceID+"/plugins/available", nil)
c.Params = []gin.Param{{Key: "id", Value: workspaceID}}
h.ListAvailableForWorkspace(c)
var out []pluginInfo
json.Unmarshal(w.Body.Bytes(), &out)
return out
}
// --- ListRegistry ---
func TestListRegistry_ReturnsAllPlugins(t *testing.T) {
pluginsDir := setupTestPlugins(t, map[string]string{
"plugin-a": `name: plugin-a`,
"plugin-b": `name: plugin-b`,
})
h := makeTestHandler(t, pluginsDir)
plugins := listRegistry(h, "")
if len(plugins) != 2 {
t.Fatalf("expected 2 plugins, got %d", len(plugins))
}
names := make(map[string]bool)
for _, p := range plugins {
names[p.Name] = true
}
if !names["plugin-a"] || !names["plugin-b"] {
t.Errorf("unexpected plugin names: %v", names)
}
}
func TestListRegistry_EmptyDirectory(t *testing.T) {
dir := t.TempDir()
h := makeTestHandler(t, dir)
plugins := listRegistry(h, "")
if len(plugins) != 0 {
t.Fatalf("expected 0 plugins for empty dir, got %d", len(plugins))
}
}
func TestListRegistry_FiltersByRuntime(t *testing.T) {
// plugin-a supports claude-code; plugin-b supports langgraph only.
pluginsDir := setupTestPlugins(t, map[string]string{
"plugin-a": `
name: plugin-a
runtimes:
- claude_code
`,
"plugin-b": `
name: plugin-b
runtimes:
- langgraph
`,
})
h := makeTestHandler(t, pluginsDir)
// Filter by claude-code — only plugin-a matches.
plugins := listRegistry(h, "claude-code")
if len(plugins) != 1 || plugins[0].Name != "plugin-a" {
t.Errorf("expected [plugin-a], got %v", plugins)
}
// Filter by langgraph — only plugin-b matches.
plugins = listRegistry(h, "langgraph")
if len(plugins) != 1 || plugins[0].Name != "plugin-b" {
t.Errorf("expected [plugin-b], got %v", plugins)
}
// Filter by unknown runtime — plugins that declare specific runtimes
// are excluded; only unspecified (empty Runtimes) would appear.
plugins = listRegistry(h, "autogen")
if len(plugins) != 0 {
t.Errorf("expected 0 for unknown runtime, got %v", plugins)
}
}
func TestListRegistry_UnspecifiedRuntimesIncludedForAll(t *testing.T) {
// A plugin with no runtimes field is treated as "unspecified" — included
// for every runtime filter.
pluginsDir := setupTestPlugins(t, map[string]string{
"generic-plugin": `name: generic-plugin`,
"claude-plugin": `
name: claude-plugin
runtimes:
- claude_code
`,
})
h := makeTestHandler(t, pluginsDir)
plugins := listRegistry(h, "claude-code")
names := make(map[string]bool)
for _, p := range plugins {
names[p.Name] = true
}
// Both should appear: generic-plugin (unspecified) + claude-plugin.
if !names["generic-plugin"] || !names["claude-plugin"] {
t.Errorf("expected both plugins, got %v", names)
}
}
func TestListRegistry_ManifestFieldsParsed(t *testing.T) {
// Verify that ListRegistry returns the full pluginInfo shape from plugin.yaml.
pluginsDir := setupTestPlugins(t, map[string]string{
"my-plugin": `
name: my-plugin
version: 1.2.3
description: A test plugin
author: Test Author
tags:
- testing
- demo
skills:
- tdd-loop
- code-review
runtimes:
- claude_code
`,
})
h := makeTestHandler(t, pluginsDir)
plugins := listRegistry(h, "")
if len(plugins) != 1 {
t.Fatalf("expected 1 plugin, got %d", len(plugins))
}
p := plugins[0]
if p.Name != "my-plugin" {
t.Errorf("Name = %q; want my-plugin", p.Name)
}
if p.Version != "1.2.3" {
t.Errorf("Version = %q; want 1.2.3", p.Version)
}
if p.Description != "A test plugin" {
t.Errorf("Description = %q; want 'A test plugin'", p.Description)
}
if p.Author != "Test Author" {
t.Errorf("Author = %q; want 'Test Author'", p.Author)
}
if len(p.Tags) != 2 {
t.Errorf("Tags = %v; want 2 entries", p.Tags)
}
if len(p.Skills) != 2 {
t.Errorf("Skills = %v; want 2 entries", p.Skills)
}
if len(p.Runtimes) != 1 {
t.Errorf("Runtimes = %v; want 1 entry", p.Runtimes)
}
}
func TestListRegistry_NoManifestFile(t *testing.T) {
// A plugin directory without plugin.yaml should still appear with its
// directory name as the Name.
pluginsDir := setupTestPlugins(t, map[string]string{
"no-manifest-plugin": ``, // directory with no plugin.yaml
})
h := makeTestHandler(t, pluginsDir)
plugins := listRegistry(h, "")
if len(plugins) != 1 {
t.Fatalf("expected 1 plugin, got %d", len(plugins))
}
if plugins[0].Name != "no-manifest-plugin" {
t.Errorf("expected Name to be directory name, got %q", plugins[0].Name)
}
}
// --- ListAvailableForWorkspace ---
func TestListAvailableForWorkspace_WithRuntimeLookup(t *testing.T) {
// When runtimeLookup is wired, ListAvailableForWorkspace filters by the
// workspace's runtime (claude-code), which is set by makeTestHandler.
pluginsDir := setupTestPlugins(t, map[string]string{
"runtime-plugin": `
name: runtime-plugin
runtimes:
- claude_code
`,
"langgraph-plugin": `
name: langgraph-plugin
runtimes:
- langgraph
`,
})
h := makeTestHandler(t, pluginsDir)
plugins := listAvailable(h, "ws-123")
if len(plugins) != 1 || plugins[0].Name != "runtime-plugin" {
t.Errorf("expected [runtime-plugin], got %v", plugins)
}
}
func TestListAvailableForWorkspace_UnspecifiedRuntime(t *testing.T) {
// A plugin without runtimes is included for all workspaces.
pluginsDir := setupTestPlugins(t, map[string]string{
"generic": `name: generic`,
})
h := makeTestHandler(t, pluginsDir)
plugins := listAvailable(h, "ws-456")
if len(plugins) != 1 || plugins[0].Name != "generic" {
t.Errorf("expected [generic], got %v", plugins)
}
}
// --- HTTP response codes ---
func TestListRegistry_HTTPStatusOK(t *testing.T) {
pluginsDir := setupTestPlugins(t, map[string]string{"foo": "name: foo"})
h := NewPluginsHandler(pluginsDir, nil, nil)
gin.SetMode(gin.TestMode)
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Request = httptest.NewRequest("GET", "/plugins", nil)
h.ListRegistry(c)
if w.Code != http.StatusOK {
t.Errorf("expected 200, got %d", w.Code)
}
}
func TestListAvailableForWorkspace_HTTPStatusOK(t *testing.T) {
pluginsDir := setupTestPlugins(t, map[string]string{"bar": "name: bar"})
h := makeTestHandler(t, pluginsDir)
gin.SetMode(gin.TestMode)
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Request = httptest.NewRequest("GET", "/workspaces/ws-789/plugins/available", nil)
c.Params = []gin.Param{{Key: "id", Value: "ws-789"}}
h.ListAvailableForWorkspace(c)
if w.Code != http.StatusOK {
t.Errorf("expected 200, got %d", w.Code)
}
}
@@ -0,0 +1,55 @@
package handlers
import (
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"github.com/gin-gonic/gin"
)
// ListSources is the only exported function in plugins_sources.go.
// It calls h.sources.Schemes() and returns the result verbatim,
// so the test verifies the handler correctly serialises whatever
// the real registry provides.
func TestListSources_ReturnsSchemes(t *testing.T) {
// Use a real handler — the registry is deterministic (local + github).
h := NewPluginsHandler(t.TempDir(), nil, nil)
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Request = httptest.NewRequest("GET", "/plugins/sources", nil)
h.ListSources(c)
if w.Code != http.StatusOK {
t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())
}
var body struct {
Schemes []string `json:"schemes"`
}
if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil {
t.Fatalf("failed to unmarshal response: %v", err)
}
// The default registry registers local + github resolvers.
if len(body.Schemes) < 1 {
t.Fatalf("expected at least 1 scheme, got %d: %v", len(body.Schemes), body.Schemes)
}
// Verify stability — same call always returns same result.
w2 := httptest.NewRecorder()
c2, _ := gin.CreateTestContext(w2)
c2.Request = httptest.NewRequest("GET", "/plugins/sources", nil)
h.ListSources(c2)
var body2 struct {
Schemes []string `json:"schemes"`
}
json.Unmarshal(w2.Body.Bytes(), &body2)
if len(body.Schemes) != len(body2.Schemes) {
t.Errorf("Schemes() is not stable: first=%v, second=%v", body.Schemes, body2.Schemes)
}
}
@@ -0,0 +1,297 @@
package handlers
import (
"bytes"
"context"
"database/sql"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"testing"
"github.com/DATA-DOG/go-sqlmock"
"github.com/Molecule-AI/molecule-monorepo/platform/internal/db"
"github.com/gin-gonic/gin"
)
func setupAbilitiesTest(t *testing.T) (sqlmock.Sqlmock, func()) {
t.Helper()
mockDB, mock, err := sqlmock.New()
if err != nil {
t.Fatalf("failed to create sqlmock: %v", err)
}
prev := db.DB
db.DB = mockDB
return mock, func() {
db.DB = prev
mockDB.Close()
}
}
func TestPatchAbilities_InvalidWorkspaceID_Returns400(t *testing.T) {
_, cleanup := setupAbilitiesTest(t)
defer cleanup()
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Params = gin.Params{{Key: "id", Value: "not-a-valid-uuid"}}
c.Request = httptest.NewRequest("PATCH",
"/workspaces/not-a-valid-uuid/abilities",
bytes.NewBufferString(`{"broadcast_enabled":true}`))
c.Request.Header.Set("Content-Type", "application/json")
c.Request = c.Request.WithContext(context.Background())
PatchAbilities(c)
if w.Code != http.StatusBadRequest {
t.Errorf("expected 400, got %d: %s", w.Code, w.Body.String())
}
var body map[string]string
json.Unmarshal(w.Body.Bytes(), &body)
if body["error"] != "invalid workspace ID" {
t.Errorf("expected 'invalid workspace ID', got %q", body["error"])
}
}
func TestPatchAbilities_EmptyBody_Returns400(t *testing.T) {
_, cleanup := setupAbilitiesTest(t)
defer cleanup()
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Params = gin.Params{{Key: "id", Value: "550e8400-e29b-41d4-a716-446655440000"}}
c.Request = httptest.NewRequest("PATCH",
"/workspaces/550e8400-e29b-41d4-a716-446655440000/abilities",
bytes.NewBufferString(`{}`))
c.Request.Header.Set("Content-Type", "application/json")
c.Request = c.Request.WithContext(context.Background())
PatchAbilities(c)
if w.Code != http.StatusBadRequest {
t.Errorf("expected 400, got %d: %s", w.Code, w.Body.String())
}
var body map[string]string
json.Unmarshal(w.Body.Bytes(), &body)
if body["error"] != "at least one ability field required" {
t.Errorf("expected 'at least one ability field required', got %q", body["error"])
}
}
func TestPatchAbilities_InvalidJSON_Returns400(t *testing.T) {
_, cleanup := setupAbilitiesTest(t)
defer cleanup()
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Params = gin.Params{{Key: "id", Value: "550e8400-e29b-41d4-a716-446655440000"}}
c.Request = httptest.NewRequest("PATCH",
"/workspaces/550e8400-e29b-41d4-a716-446655440000/abilities",
bytes.NewBufferString(`{invalid json}`))
c.Request.Header.Set("Content-Type", "application/json")
c.Request = c.Request.WithContext(context.Background())
PatchAbilities(c)
if w.Code != http.StatusBadRequest {
t.Errorf("expected 400, got %d: %s", w.Code, w.Body.String())
}
var body map[string]string
json.Unmarshal(w.Body.Bytes(), &body)
if body["error"] != "invalid request body" {
t.Errorf("expected 'invalid request body', got %q", body["error"])
}
}
func TestPatchAbilities_WorkspaceNotFound_Returns404(t *testing.T) {
mock, cleanup := setupAbilitiesTest(t)
defer cleanup()
mock.ExpectQuery("SELECT EXISTS").
WithArgs("550e8400-e29b-41d4-a716-446655440000").
WillReturnError(sql.ErrNoRows)
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Params = gin.Params{{Key: "id", Value: "550e8400-e29b-41d4-a716-446655440000"}}
c.Request = httptest.NewRequest("PATCH",
"/workspaces/550e8400-e29b-41d4-a716-446655440000/abilities",
bytes.NewBufferString(`{"broadcast_enabled":true}`))
c.Request.Header.Set("Content-Type", "application/json")
c.Request = c.Request.WithContext(context.Background())
PatchAbilities(c)
if w.Code != http.StatusNotFound {
t.Errorf("expected 404, got %d: %s", w.Code, w.Body.String())
}
if err := mock.ExpectationsWereMet(); err != nil {
t.Errorf("unmet expectations: %v", err)
}
}
func TestPatchAbilities_WorkspaceDBError_Returns404(t *testing.T) {
mock, cleanup := setupAbilitiesTest(t)
defer cleanup()
mock.ExpectQuery("SELECT EXISTS").
WithArgs("550e8400-e29b-41d4-a716-446655440000").
WillReturnError(errors.New("connection refused"))
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Params = gin.Params{{Key: "id", Value: "550e8400-e29b-41d4-a716-446655440000"}}
c.Request = httptest.NewRequest("PATCH",
"/workspaces/550e8400-e29b-41d4-a716-446655440000/abilities",
bytes.NewBufferString(`{"broadcast_enabled":true}`))
c.Request.Header.Set("Content-Type", "application/json")
c.Request = c.Request.WithContext(context.Background())
PatchAbilities(c)
if w.Code != http.StatusNotFound {
t.Errorf("expected 404, got %d: %s", w.Code, w.Body.String())
}
if err := mock.ExpectationsWereMet(); err != nil {
t.Errorf("unmet expectations: %v", err)
}
}
func TestPatchAbilities_UpdateBroadcastEnabled_Returns200(t *testing.T) {
mock, cleanup := setupAbilitiesTest(t)
defer cleanup()
mock.ExpectQuery("SELECT EXISTS").
WithArgs("550e8400-e29b-41d4-a716-446655440000").
WillReturnRows(sqlmock.NewRows([]string{"exists"}).AddRow(true))
mock.ExpectExec("UPDATE workspaces SET broadcast_enabled").
WithArgs("550e8400-e29b-41d4-a716-446655440000", true).
WillReturnResult(sqlmock.NewResult(0, 1))
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Params = gin.Params{{Key: "id", Value: "550e8400-e29b-41d4-a716-446655440000"}}
c.Request = httptest.NewRequest("PATCH",
"/workspaces/550e8400-e29b-41d4-a716-446655440000/abilities",
bytes.NewBufferString(`{"broadcast_enabled":true}`))
c.Request.Header.Set("Content-Type", "application/json")
c.Request = c.Request.WithContext(context.Background())
PatchAbilities(c)
if w.Code != http.StatusOK {
t.Errorf("expected 200, got %d: %s", w.Code, w.Body.String())
}
var body map[string]string
json.Unmarshal(w.Body.Bytes(), &body)
if body["status"] != "updated" {
t.Errorf("expected status=updated, got %v", body)
}
if err := mock.ExpectationsWereMet(); err != nil {
t.Errorf("unmet expectations: %v", err)
}
}
func TestPatchAbilities_UpdateTalkToUserEnabled_Returns200(t *testing.T) {
mock, cleanup := setupAbilitiesTest(t)
defer cleanup()
mock.ExpectQuery("SELECT EXISTS").
WithArgs("550e8400-e29b-41d4-a716-446655440000").
WillReturnRows(sqlmock.NewRows([]string{"exists"}).AddRow(true))
mock.ExpectExec("UPDATE workspaces SET talk_to_user_enabled").
WithArgs("550e8400-e29b-41d4-a716-446655440000", true).
WillReturnResult(sqlmock.NewResult(0, 1))
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Params = gin.Params{{Key: "id", Value: "550e8400-e29b-41d4-a716-446655440000"}}
c.Request = httptest.NewRequest("PATCH",
"/workspaces/550e8400-e29b-41d4-a716-446655440000/abilities",
bytes.NewBufferString(`{"talk_to_user_enabled":true}`))
c.Request.Header.Set("Content-Type", "application/json")
c.Request = c.Request.WithContext(context.Background())
PatchAbilities(c)
if w.Code != http.StatusOK {
t.Errorf("expected 200, got %d: %s", w.Code, w.Body.String())
}
var body map[string]string
json.Unmarshal(w.Body.Bytes(), &body)
if body["status"] != "updated" {
t.Errorf("expected status=updated, got %v", body)
}
if err := mock.ExpectationsWereMet(); err != nil {
t.Errorf("unmet expectations: %v", err)
}
}
func TestPatchAbilities_UpdateBothAbilities_Returns200(t *testing.T) {
mock, cleanup := setupAbilitiesTest(t)
defer cleanup()
mock.ExpectQuery("SELECT EXISTS").
WithArgs("550e8400-e29b-41d4-a716-446655440000").
WillReturnRows(sqlmock.NewRows([]string{"exists"}).AddRow(true))
mock.ExpectExec("UPDATE workspaces SET broadcast_enabled").
WithArgs("550e8400-e29b-41d4-a716-446655440000", true).
WillReturnResult(sqlmock.NewResult(0, 1))
mock.ExpectExec("UPDATE workspaces SET talk_to_user_enabled").
WithArgs("550e8400-e29b-41d4-a716-446655440000", false).
WillReturnResult(sqlmock.NewResult(0, 1))
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Params = gin.Params{{Key: "id", Value: "550e8400-e29b-41d4-a716-446655440000"}}
c.Request = httptest.NewRequest("PATCH",
"/workspaces/550e8400-e29b-41d4-a716-446655440000/abilities",
bytes.NewBufferString(`{"broadcast_enabled":true,"talk_to_user_enabled":false}`))
c.Request.Header.Set("Content-Type", "application/json")
c.Request = c.Request.WithContext(context.Background())
PatchAbilities(c)
if w.Code != http.StatusOK {
t.Errorf("expected 200, got %d: %s", w.Code, w.Body.String())
}
var body map[string]string
json.Unmarshal(w.Body.Bytes(), &body)
if body["status"] != "updated" {
t.Errorf("expected status=updated, got %v", body)
}
if err := mock.ExpectationsWereMet(); err != nil {
t.Errorf("unmet expectations: %v", err)
}
}
func TestPatchAbilities_UpdateBroadcastDisabled_Returns200(t *testing.T) {
mock, cleanup := setupAbilitiesTest(t)
defer cleanup()
mock.ExpectQuery("SELECT EXISTS").
WithArgs("550e8400-e29b-41d4-a716-446655440000").
WillReturnRows(sqlmock.NewRows([]string{"exists"}).AddRow(true))
mock.ExpectExec("UPDATE workspaces SET broadcast_enabled").
WithArgs("550e8400-e29b-41d4-a716-446655440000", false).
WillReturnResult(sqlmock.NewResult(0, 1))
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Params = gin.Params{{Key: "id", Value: "550e8400-e29b-41d4-a716-446655440000"}}
c.Request = httptest.NewRequest("PATCH",
"/workspaces/550e8400-e29b-41d4-a716-446655440000/abilities",
bytes.NewBufferString(`{"broadcast_enabled":false}`))
c.Request.Header.Set("Content-Type", "application/json")
c.Request = c.Request.WithContext(context.Background())
PatchAbilities(c)
if w.Code != http.StatusOK {
t.Errorf("expected 200, got %d: %s", w.Code, w.Body.String())
}
if err := mock.ExpectationsWereMet(); err != nil {
t.Errorf("unmet expectations: %v", err)
}
}
@@ -0,0 +1,398 @@
package handlers
import (
"bytes"
"context"
"database/sql"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"testing"
"github.com/DATA-DOG/go-sqlmock"
"github.com/Molecule-AI/molecule-monorepo/platform/internal/db"
"github.com/gin-gonic/gin"
)
// -------------------------------------------------------------------------- //
// broadcastTruncate
// -------------------------------------------------------------------------- //
func TestBroadcastTruncate_ShortString_ReturnsUnmodified(t *testing.T) {
result := broadcastTruncate("hello", 10)
if result != "hello" {
t.Errorf("expected 'hello', got %q", result)
}
}
func TestBroadcastTruncate_ExactlyMaxLength_ReturnsUnmodified(t *testing.T) {
result := broadcastTruncate("hello", 5)
if result != "hello" {
t.Errorf("expected 'hello', got %q", result)
}
}
func TestBroadcastTruncate_ExceedsMaxLength_TruncatesWithEllipsis(t *testing.T) {
result := broadcastTruncate("hello world", 5)
if result != "hello…" {
t.Errorf("expected 'hello…', got %q", result)
}
}
func TestBroadcastTruncate_Unicode_TruncatesAtRuneBoundary(t *testing.T) {
result := broadcastTruncate("日本語テスト", 2)
if result != "日本…" {
t.Errorf("expected '日本…', got %q", result)
}
}
// -------------------------------------------------------------------------- //
// BroadcastHandler
// -------------------------------------------------------------------------- //
func setupBroadcastTest(t *testing.T) (sqlmock.Sqlmock, func()) {
t.Helper()
mockDB, mock, err := sqlmock.New()
if err != nil {
t.Fatalf("failed to create sqlmock: %v", err)
}
prev := db.DB
db.DB = mockDB
return mock, func() {
db.DB = prev
mockDB.Close()
}
}
func TestBroadcast_InvalidWorkspaceID_Returns400(t *testing.T) {
_, cleanup := setupBroadcastTest(t)
defer cleanup()
h := NewBroadcastHandler(newTestBroadcaster())
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Params = gin.Params{{Key: "id", Value: "not-a-uuid"}}
c.Request = httptest.NewRequest("POST", "/workspaces/not-a-uuid/broadcast",
bytes.NewBufferString(`{"message":"hello"}`))
c.Request.Header.Set("Content-Type", "application/json")
c.Request = c.Request.WithContext(context.Background())
h.Broadcast(c)
if w.Code != http.StatusBadRequest {
t.Errorf("expected 400, got %d: %s", w.Code, w.Body.String())
}
var body map[string]string
json.Unmarshal(w.Body.Bytes(), &body)
if body["error"] != "invalid workspace ID" {
t.Errorf("expected 'invalid workspace ID', got %q", body["error"])
}
}
func TestBroadcast_MissingMessage_Returns400(t *testing.T) {
_, cleanup := setupBroadcastTest(t)
defer cleanup()
h := NewBroadcastHandler(newTestBroadcaster())
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Params = gin.Params{{Key: "id", Value: "550e8400-e29b-41d4-a716-446655440000"}}
c.Request = httptest.NewRequest("POST",
"/workspaces/550e8400-e29b-41d4-a716-446655440000/broadcast",
bytes.NewBufferString(`{}`))
c.Request.Header.Set("Content-Type", "application/json")
c.Request = c.Request.WithContext(context.Background())
h.Broadcast(c)
if w.Code != http.StatusBadRequest {
t.Errorf("expected 400, got %d: %s", w.Code, w.Body.String())
}
var body map[string]string
json.Unmarshal(w.Body.Bytes(), &body)
if body["error"] != "message is required" {
t.Errorf("expected 'message is required', got %q", body["error"])
}
}
func TestBroadcast_WorkspaceNotFound_Returns404(t *testing.T) {
mock, cleanup := setupBroadcastTest(t)
defer cleanup()
mock.ExpectQuery("SELECT name, broadcast_enabled FROM workspaces").
WithArgs("550e8400-e29b-41d4-a716-446655440000").
WillReturnError(sql.ErrNoRows)
h := NewBroadcastHandler(newTestBroadcaster())
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Params = gin.Params{{Key: "id", Value: "550e8400-e29b-41d4-a716-446655440000"}}
c.Request = httptest.NewRequest("POST",
"/workspaces/550e8400-e29b-41d4-a716-446655440000/broadcast",
bytes.NewBufferString(`{"message":"hello"}`))
c.Request.Header.Set("Content-Type", "application/json")
c.Request = c.Request.WithContext(context.Background())
h.Broadcast(c)
if w.Code != http.StatusNotFound {
t.Errorf("expected 404, got %d: %s", w.Code, w.Body.String())
}
if err := mock.ExpectationsWereMet(); err != nil {
t.Errorf("unmet expectations: %v", err)
}
}
func TestBroadcast_BroadcastDisabled_Returns403(t *testing.T) {
mock, cleanup := setupBroadcastTest(t)
defer cleanup()
mock.ExpectQuery("SELECT name, broadcast_enabled FROM workspaces").
WithArgs("550e8400-e29b-41d4-a716-446655440000").
WillReturnRows(sqlmock.NewRows([]string{"name", "broadcast_enabled"}).
AddRow("test-agent", false))
h := NewBroadcastHandler(newTestBroadcaster())
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Params = gin.Params{{Key: "id", Value: "550e8400-e29b-41d4-a716-446655440000"}}
c.Request = httptest.NewRequest("POST",
"/workspaces/550e8400-e29b-41d4-a716-446655440000/broadcast",
bytes.NewBufferString(`{"message":"hello"}`))
c.Request.Header.Set("Content-Type", "application/json")
c.Request = c.Request.WithContext(context.Background())
h.Broadcast(c)
if w.Code != http.StatusForbidden {
t.Errorf("expected 403, got %d: %s", w.Code, w.Body.String())
}
var body map[string]string
json.Unmarshal(w.Body.Bytes(), &body)
if body["error"] != "broadcast_disabled" {
t.Errorf("expected error='broadcast_disabled', got %v", body)
}
if _, ok := body["hint"]; !ok {
t.Errorf("expected hint field in 403 body, got %v", body)
}
if err := mock.ExpectationsWereMet(); err != nil {
t.Errorf("unmet expectations: %v", err)
}
}
func TestBroadcast_RecipientQueryFails_Returns500(t *testing.T) {
mock, cleanup := setupBroadcastTest(t)
defer cleanup()
mock.ExpectQuery("SELECT name, broadcast_enabled FROM workspaces").
WithArgs("550e8400-e29b-41d4-a716-446655440000").
WillReturnRows(sqlmock.NewRows([]string{"name", "broadcast_enabled"}).
AddRow("test-agent", true))
mock.ExpectQuery("SELECT id FROM workspaces WHERE status != 'removed' AND id != ").
WithArgs("550e8400-e29b-41d4-a716-446655440000").
WillReturnError(errors.New("connection refused"))
h := NewBroadcastHandler(newTestBroadcaster())
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Params = gin.Params{{Key: "id", Value: "550e8400-e29b-41d4-a716-446655440000"}}
c.Request = httptest.NewRequest("POST",
"/workspaces/550e8400-e29b-41d4-a716-446655440000/broadcast",
bytes.NewBufferString(`{"message":"hello"}`))
c.Request.Header.Set("Content-Type", "application/json")
c.Request = c.Request.WithContext(context.Background())
h.Broadcast(c)
if w.Code != http.StatusInternalServerError {
t.Errorf("expected 500, got %d: %s", w.Code, w.Body.String())
}
if err := mock.ExpectationsWereMet(); err != nil {
t.Errorf("unmet expectations: %v", err)
}
}
func TestBroadcast_NoRecipients_Returns200(t *testing.T) {
mock, cleanup := setupBroadcastTest(t)
defer cleanup()
mock.ExpectQuery("SELECT name, broadcast_enabled FROM workspaces").
WithArgs("550e8400-e29b-41d4-a716-446655440000").
WillReturnRows(sqlmock.NewRows([]string{"name", "broadcast_enabled"}).
AddRow("test-agent", true))
mock.ExpectQuery("SELECT id FROM workspaces WHERE status != 'removed' AND id != ").
WithArgs("550e8400-e29b-41d4-a716-446655440000").
WillReturnRows(sqlmock.NewRows([]string{"id"}))
mock.ExpectExec("INSERT INTO activity_logs").
WithArgs("550e8400-e29b-41d4-a716-446655440000", "Broadcast sent to 0 workspace(s)").
WillReturnResult(sqlmock.NewResult(0, 1))
h := NewBroadcastHandler(newTestBroadcaster())
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Params = gin.Params{{Key: "id", Value: "550e8400-e29b-41d4-a716-446655440000"}}
c.Request = httptest.NewRequest("POST",
"/workspaces/550e8400-e29b-41d4-a716-446655440000/broadcast",
bytes.NewBufferString(`{"message":"hello"}`))
c.Request.Header.Set("Content-Type", "application/json")
c.Request = c.Request.WithContext(context.Background())
h.Broadcast(c)
if w.Code != http.StatusOK {
t.Errorf("expected 200, got %d: %s", w.Code, w.Body.String())
}
var body map[string]interface{}
json.Unmarshal(w.Body.Bytes(), &body)
if body["status"] != "sent" {
t.Errorf("expected status=sent, got %v", body)
}
if int(body["delivered"].(float64)) != 0 {
t.Errorf("expected delivered=0, got %v", body["delivered"])
}
if err := mock.ExpectationsWereMet(); err != nil {
t.Errorf("unmet expectations: %v", err)
}
}
func TestBroadcast_DeliversToOneRecipient_Returns200(t *testing.T) {
mock, cleanup := setupBroadcastTest(t)
defer cleanup()
senderID := "550e8400-e29b-41d4-a716-446655440000"
recipientID := "660e8400-e29b-41d4-a716-446655440001"
senderName := "test-agent"
mock.ExpectQuery("SELECT name, broadcast_enabled FROM workspaces").
WithArgs(senderID).
WillReturnRows(sqlmock.NewRows([]string{"name", "broadcast_enabled"}).
AddRow(senderName, true))
mock.ExpectQuery("SELECT id FROM workspaces WHERE status != 'removed' AND id != ").
WithArgs(senderID).
WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(recipientID))
mock.ExpectExec("INSERT INTO activity_logs").
WithArgs(recipientID, senderID, "Broadcast from "+senderName+": hello").
WillReturnResult(sqlmock.NewResult(0, 1))
mock.ExpectExec("INSERT INTO activity_logs").
WithArgs(senderID, "Broadcast sent to 1 workspace(s)").
WillReturnResult(sqlmock.NewResult(0, 1))
h := NewBroadcastHandler(newTestBroadcaster())
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Params = gin.Params{{Key: "id", Value: senderID}}
c.Request = httptest.NewRequest("POST",
"/workspaces/"+senderID+"/broadcast",
bytes.NewBufferString(`{"message":"hello"}`))
c.Request.Header.Set("Content-Type", "application/json")
c.Request = c.Request.WithContext(context.Background())
h.Broadcast(c)
if w.Code != http.StatusOK {
t.Errorf("expected 200, got %d: %s", w.Code, w.Body.String())
}
var body map[string]interface{}
json.Unmarshal(w.Body.Bytes(), &body)
if int(body["delivered"].(float64)) != 1 {
t.Errorf("expected delivered=1, got %v", body["delivered"])
}
if err := mock.ExpectationsWereMet(); err != nil {
t.Errorf("unmet expectations: %v", err)
}
}
func TestBroadcast_RecipientInsertFails_Continues_Returns200(t *testing.T) {
mock, cleanup := setupBroadcastTest(t)
defer cleanup()
senderID := "550e8400-e29b-41d4-a716-446655440000"
recipientID := "660e8400-e29b-41d4-a716-446655440001"
senderName := "test-agent"
mock.ExpectQuery("SELECT name, broadcast_enabled FROM workspaces").
WithArgs(senderID).
WillReturnRows(sqlmock.NewRows([]string{"name", "broadcast_enabled"}).
AddRow(senderName, true))
mock.ExpectQuery("SELECT id FROM workspaces WHERE status != 'removed' AND id != ").
WithArgs(senderID).
WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(recipientID))
mock.ExpectExec("INSERT INTO activity_logs").
WithArgs(recipientID, senderID, "Broadcast from "+senderName+": hello").
WillReturnError(errors.New("connection refused"))
mock.ExpectExec("INSERT INTO activity_logs").
WithArgs(senderID, "Broadcast sent to 0 workspace(s)").
WillReturnResult(sqlmock.NewResult(0, 1))
h := NewBroadcastHandler(newTestBroadcaster())
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Params = gin.Params{{Key: "id", Value: senderID}}
c.Request = httptest.NewRequest("POST",
"/workspaces/"+senderID+"/broadcast",
bytes.NewBufferString(`{"message":"hello"}`))
c.Request.Header.Set("Content-Type", "application/json")
c.Request = c.Request.WithContext(context.Background())
h.Broadcast(c)
if w.Code != http.StatusOK {
t.Errorf("expected 200, got %d: %s", w.Code, w.Body.String())
}
var body map[string]interface{}
json.Unmarshal(w.Body.Bytes(), &body)
if int(body["delivered"].(float64)) != 0 {
t.Errorf("expected delivered=0 (failed inserts don't count), got %v", body["delivered"])
}
if err := mock.ExpectationsWereMet(); err != nil {
t.Errorf("unmet expectations: %v", err)
}
}
func TestBroadcast_SenderLogFails_StillReturns200(t *testing.T) {
mock, cleanup := setupBroadcastTest(t)
defer cleanup()
senderID := "550e8400-e29b-41d4-a716-446655440000"
recipientID := "660e8400-e29b-41d4-a716-446655440001"
senderName := "test-agent"
mock.ExpectQuery("SELECT name, broadcast_enabled FROM workspaces").
WithArgs(senderID).
WillReturnRows(sqlmock.NewRows([]string{"name", "broadcast_enabled"}).
AddRow(senderName, true))
mock.ExpectQuery("SELECT id FROM workspaces WHERE status != 'removed' AND id != ").
WithArgs(senderID).
WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(recipientID))
mock.ExpectExec("INSERT INTO activity_logs").
WithArgs(recipientID, senderID, "Broadcast from "+senderName+": hello").
WillReturnResult(sqlmock.NewResult(0, 1))
mock.ExpectExec("INSERT INTO activity_logs").
WithArgs(senderID, "Broadcast sent to 1 workspace(s)").
WillReturnError(errors.New("connection refused"))
h := NewBroadcastHandler(newTestBroadcaster())
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Params = gin.Params{{Key: "id", Value: senderID}}
c.Request = httptest.NewRequest("POST",
"/workspaces/"+senderID+"/broadcast",
bytes.NewBufferString(`{"message":"hello"}`))
c.Request.Header.Set("Content-Type", "application/json")
c.Request = c.Request.WithContext(context.Background())
h.Broadcast(c)
if w.Code != http.StatusOK {
t.Errorf("expected 200, got %d: %s", w.Code, w.Body.String())
}
var body map[string]interface{}
json.Unmarshal(w.Body.Bytes(), &body)
if int(body["delivered"].(float64)) != 1 {
t.Errorf("expected delivered=1, got %v", body["delivered"])
}
if err := mock.ExpectationsWereMet(); err != nil {
t.Errorf("unmet expectations: %v", err)
}
}