Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 3 additions & 13 deletions .github/workflows/coverage.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -15,21 +15,11 @@ jobs:

- uses: actions/setup-go@7b8cf10d4e4a01d4992d18a89f4d7dc5a3e6d6f4 # v4.3.0
with:
go-version: '1.22'
go-version-file: go.mod

- name: Run tests with coverage
run: |
# Test core packages (exclude LLM clients that require API keys and UI-heavy cmd packages)
# Focus on testable internal packages
go test \
./internal/config \
./internal/keys \
./internal/stats \
./internal/git \
./internal/llm \
./internal/ui/banner \
./internal/ui/notify \
-coverprofile=coverage.out
# Cover every package so the reported number matches `go test -cover ./...`.
run: go test -race -covermode=atomic -coverprofile=coverage.out ./...

- name: Upload coverage to Codecov
uses: codecov/codecov-action@671740ac38dd9b0130fbe1cec585b89eea48d3de # v5.5.2
Expand Down
134 changes: 134 additions & 0 deletions cmd/commit_test.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,16 @@
package cmd

import (
"context"
"errors"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"

"github.com/rshdhere/vibecheck/internal/llm"
"github.com/rshdhere/vibecheck/internal/stats"
)

func TestDetectMissingEnvVar(t *testing.T) {
Expand Down Expand Up @@ -105,3 +114,128 @@ type testError struct {
func (e *testError) Error() string {
return e.msg
}

// fakeProvider returns a canned message or error.
type fakeProvider struct {
msg string
err error
}

func (f fakeProvider) GenerateCommitMessage(context.Context, string, string) (string, error) {
return f.msg, f.err
}

func init() {
llm.Register("test-ok", fakeProvider{msg: "feat(cmd): add thing\n\n- detail"})
llm.Register("test-missing-key", fakeProvider{err: errors.New("FAKE_API_KEY environment variable not set")})
llm.Register("test-missing-model", fakeProvider{err: errors.New("model 'fake-model' not found")})
llm.Register("test-fail", fakeProvider{err: errors.New("boom")})
}

// setupRepo creates a git repo with one staged file and makes it the working directory.
func setupRepo(t *testing.T, stage bool) string {
t.Helper()
isolateHome(t)
dir := t.TempDir()
t.Chdir(dir)
t.Setenv("GIT_EDITOR", "true")
runGit(t, "init", "-q")
runGit(t, "config", "user.email", "test@example.com")
runGit(t, "config", "user.name", "Test User")
runGit(t, "config", "commit.gpgsign", "false")
if stage {
if err := os.WriteFile(filepath.Join(dir, "file.txt"), []byte("hello\n"), 0644); err != nil {
t.Fatal(err)
}
runGit(t, "add", "file.txt")
}
return dir
}

func runGit(t *testing.T, args ...string) string {
t.Helper()
out, err := exec.Command("git", args...).CombinedOutput()
if err != nil {
t.Fatalf("git %v: %v\n%s", args, err, out)
}
return string(out)
}

func headMessage(t *testing.T) string {
t.Helper()
out, err := exec.Command("git", "log", "-1", "--format=%B").CombinedOutput()
if err != nil {
return ""
}
return strings.TrimSpace(string(out))
}

func TestCommitCmdCommitsGeneratedMessage(t *testing.T) {
setupRepo(t, true)

if err := execute(t, "commit", "--provider", "test-ok", "--prompt", "ctx"); err != nil {
t.Fatalf("commit error = %v", err)
}

if got := headMessage(t); got != "feat(cmd): add thing\n\n- detail" {
t.Errorf("HEAD message = %q, want the generated message", got)
}
recent, err := stats.GetRecentCommits(1)
if err != nil || len(recent) != 1 {
t.Fatalf("recent commits = %v, %v; want one record", recent, err)
}
if recent[0].Model != "test-ok" || recent[0].CommitMsg != "feat(cmd): add thing" {
t.Errorf("recorded %+v, want model test-ok and the first message line", recent[0])
}
}

func TestCommitCmdHandledProviderErrors(t *testing.T) {
for _, provider := range []string{"test-missing-key", "test-missing-model"} {
t.Run(provider, func(t *testing.T) {
setupRepo(t, true)

if err := execute(t, "commit", "--provider", provider, "--prompt", ""); err != nil {
t.Fatalf("commit error = %v, want nil after showing a notice", err)
}
if got := headMessage(t); got != "" {
t.Errorf("HEAD message = %q, want no commit", got)
}
})
}
}

func TestCommitCmdNothingStaged(t *testing.T) {
setupRepo(t, false)

if err := execute(t, "commit", "--provider", "test-ok", "--prompt", ""); err != nil {
t.Fatalf("commit error = %v, want nil after the stage reminder", err)
}
if got := headMessage(t); got != "" {
t.Errorf("HEAD message = %q, want no commit", got)
}
}

func TestCommitCmdErrors(t *testing.T) {
tests := []struct {
name string
provider string
setup func(t *testing.T)
wantErr string
}{
{"not a git repo", "test-ok", func(t *testing.T) { isolateHome(t); t.Chdir(t.TempDir()) }, "staged changes"},
{"unknown provider", "no-such-provider", func(t *testing.T) { setupRepo(t, true) }, llm.ErrNoProvider.Error()},
{"provider failure", "test-fail", func(t *testing.T) { setupRepo(t, true) }, "generated commit message: boom"},
{"git commit aborted", "test-ok", func(t *testing.T) { setupRepo(t, true); t.Setenv("GIT_EDITOR", "false") }, "commit with message"},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
tt.setup(t)

err := execute(t, "commit", "--provider", tt.provider, "--prompt", "")
if err == nil || !strings.Contains(err.Error(), tt.wantErr) {
t.Fatalf("commit error = %v, want it to contain %q", err, tt.wantErr)
}
})
}
}
2 changes: 1 addition & 1 deletion cmd/dashboard.go
Original file line number Diff line number Diff line change
Expand Up @@ -282,7 +282,7 @@ var dashboardCmd = &cobra.Command{
height: 24,
}

p := tea.NewProgram(m, tea.WithAltScreen())
p := tea.NewProgram(m, append([]tea.ProgramOption{tea.WithAltScreen()}, teaOptions...)...)
if _, err := p.Run(); err != nil {
return fmt.Errorf("error running dashboard: %w", err)
}
Expand Down
114 changes: 114 additions & 0 deletions cmd/dashboard_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
package cmd

import (
"strings"
"testing"
"time"

tea "github.com/charmbracelet/bubbletea"
"github.com/rshdhere/vibecheck/internal/stats"
)

func TestDashboardModelUpdate(t *testing.T) {
var m tea.Model = dashboardModel{}

if m.(dashboardModel).Init() == nil {
t.Error("Init() should load stats and start the refresh tick")
}

m, _ = m.Update(tea.WindowSizeMsg{Width: 100, Height: 40})
if d := m.(dashboardModel); d.width != 100 || d.height != 40 {
t.Errorf("size = %dx%d, want 100x40", d.width, d.height)
}

loaded := statsLoadedMsg{totalCommits: 3, mostUsedModel: "groq", avgLatency: 1.5, lastUsed: time.Now()}
m, _ = m.Update(loaded)
if d := m.(dashboardModel); d.totalCommits != 3 || d.mostUsedModel != "groq" || d.avgLatency != 1.5 {
t.Errorf("stats not applied: %+v", d)
}

if _, cmd := m.Update(tickMsg{}); cmd == nil {
t.Error("tick should reload stats and schedule the next tick")
}
if _, cmd := m.Update(keyRunes("r")); cmd == nil {
t.Error("r should reload stats")
}
if _, cmd := m.Update(keyRunes("x")); cmd != nil {
t.Error("unbound keys should do nothing")
}

m, cmd := m.Update(keyRunes("q"))
if !m.(dashboardModel).quitting || cmd == nil {
t.Error("q should quit")
}
if m.View() != "" {
t.Error("view should be empty after quitting")
}
}

func TestDashboardModelView(t *testing.T) {
t.Run("empty", func(t *testing.T) {
view := dashboardModel{mostUsedModel: "N/A"}.View()
for _, want := range []string{"Vibecheck Dashboard", "Never", "None", "0.0s", "No commits yet"} {
if !strings.Contains(view, want) {
t.Errorf("view missing %q", want)
}
}
})

lastUsed := []struct {
ago time.Duration
want string
}{
{10 * time.Second, "Just now"},
{5 * time.Minute, "5m ago"},
{3 * time.Hour, "3h ago"},
{50 * time.Hour, "2d ago"},
}
for _, tt := range lastUsed {
t.Run(tt.want, func(t *testing.T) {
m := dashboardModel{
width: 120,
height: 40,
totalCommits: 2,
mostUsedModel: "openai",
avgLatency: 2.25,
lastUsed: time.Now().Add(-tt.ago),
recentCommits: []stats.CommitRecord{{Model: "openai", Latency: 2.25, CommitMsg: "feat: add dashboard"}},
}
view := m.View()
for _, want := range []string{tt.want, "openai", "2.2s", "feat: add dashboard"} {
if !strings.Contains(view, want) {
t.Errorf("view missing %q", want)
}
}
})
}
}

func TestLoadStats(t *testing.T) {
isolateHome(t)
if err := stats.RecordCommit("groq", 1.0, "feat: one"); err != nil {
t.Fatal(err)
}

msg, ok := loadStats()().(statsLoadedMsg)
if !ok {
t.Fatal("loadStats() did not return statsLoadedMsg")
}
if msg.totalCommits != 1 || msg.mostUsedModel != "groq" || len(msg.recentCommits) != 1 {
t.Errorf("loaded %+v, want the recorded commit", msg)
}
if tick() == nil {
t.Error("tick() returned nil")
}
}

func TestDashboardCmd(t *testing.T) {
isolateHome(t)
scriptTUI(t, "q")

if err := execute(t, "dashboard"); err != nil {
t.Fatalf("dashboard error = %v", err)
}
}
58 changes: 58 additions & 0 deletions cmd/helpers_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
package cmd

import (
"bytes"
"strings"
"testing"

tea "github.com/charmbracelet/bubbletea"
"github.com/rshdhere/vibecheck/internal/keys"
)

// isolateHome points HOME at a fresh directory and clears provider env vars so
// config, keys and stats never touch the developer's real files.
func isolateHome(t *testing.T) string {
t.Helper()
dir := t.TempDir()
t.Setenv("HOME", dir)
for _, envVar := range keys.ProviderToEnvVar {
t.Setenv(envVar, "")
}
return dir
}

// scriptTUI feeds input to the next interactive program and returns its output.
func scriptTUI(t *testing.T, input string) *bytes.Buffer {
t.Helper()
var out bytes.Buffer
old := teaOptions
teaOptions = []tea.ProgramOption{
tea.WithInput(strings.NewReader(input)),
tea.WithOutput(&out),
tea.WithoutSignalHandler(),
}
t.Cleanup(func() { teaOptions = old })
return &out
}

// execute runs the root command with args and returns its error.
func execute(t *testing.T, args ...string) error {
t.Helper()
var out bytes.Buffer
rootCmd.SetOut(&out)
rootCmd.SetErr(&out)
rootCmd.SetArgs(args)
t.Cleanup(func() {
rootCmd.SetOut(nil)
rootCmd.SetErr(nil)
rootCmd.SetArgs(nil)
})
return rootCmd.Execute()
}

func keyRunes(s string) tea.KeyMsg { return tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune(s)} }

var (
keyEnter = tea.KeyMsg{Type: tea.KeyEnter}
keyEsc = tea.KeyMsg{Type: tea.KeyEsc}
)
2 changes: 1 addition & 1 deletion cmd/keys.go
Original file line number Diff line number Diff line change
Expand Up @@ -458,7 +458,7 @@ var keysCmd = &cobra.Command{
state: "list",
}

p := tea.NewProgram(m)
p := tea.NewProgram(m, teaOptions...)
if _, err := p.Run(); err != nil {
return fmt.Errorf("error running program: %w", err)
}
Expand Down
Loading
Loading