cli/pkg/build/builders/wails_test.go

406 lines
11 KiB
Go
Raw Normal View History

package builders
import (
"context"
"os"
"os/exec"
"path/filepath"
"runtime"
"testing"
"github.com/host-uk/core/pkg/build"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// setupWailsTestProject creates a minimal Wails project structure for testing.
func setupWailsTestProject(t *testing.T) string {
t.Helper()
dir := t.TempDir()
// Create wails.json
wailsJSON := `{
"name": "testapp",
"outputfilename": "testapp"
}`
err := os.WriteFile(filepath.Join(dir, "wails.json"), []byte(wailsJSON), 0644)
require.NoError(t, err)
// Create a minimal go.mod
goMod := `module testapp
go 1.21
require github.com/wailsapp/wails/v3 v3.0.0
`
err = os.WriteFile(filepath.Join(dir, "go.mod"), []byte(goMod), 0644)
require.NoError(t, err)
// Create a minimal main.go
mainGo := `package main
func main() {
println("hello wails")
}
`
err = os.WriteFile(filepath.Join(dir, "main.go"), []byte(mainGo), 0644)
require.NoError(t, err)
// Create a minimal Taskfile.yml
taskfile := `version: '3'
tasks:
build:
cmds:
- mkdir -p {{.OUTPUT_DIR}}/{{.GOOS}}_{{.GOARCH}}
- touch {{.OUTPUT_DIR}}/{{.GOOS}}_{{.GOARCH}}/testapp
`
err = os.WriteFile(filepath.Join(dir, "Taskfile.yml"), []byte(taskfile), 0644)
require.NoError(t, err)
return dir
}
// setupWailsV2TestProject creates a Wails v2 project structure.
func setupWailsV2TestProject(t *testing.T) string {
t.Helper()
dir := t.TempDir()
// wails.json
err := os.WriteFile(filepath.Join(dir, "wails.json"), []byte("{}"), 0644)
require.NoError(t, err)
// go.mod with v2
goMod := `module testapp
go 1.21
require github.com/wailsapp/wails/v2 v2.8.0
`
err = os.WriteFile(filepath.Join(dir, "go.mod"), []byte(goMod), 0644)
require.NoError(t, err)
return dir
}
func TestWailsBuilder_Build_Taskfile_Good(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
// Check if task is available
if _, err := exec.LookPath("task"); err != nil {
t.Skip("task not installed, skipping test")
}
t.Run("delegates to Taskfile if present", func(t *testing.T) {
projectDir := setupWailsTestProject(t)
outputDir := t.TempDir()
// Create a Taskfile that just touches a file
taskfile := `version: '3'
tasks:
build:
cmds:
- mkdir -p {{.OUTPUT_DIR}}/{{.GOOS}}_{{.GOARCH}}
- touch {{.OUTPUT_DIR}}/{{.GOOS}}_{{.GOARCH}}/testapp
`
err := os.WriteFile(filepath.Join(projectDir, "Taskfile.yml"), []byte(taskfile), 0644)
require.NoError(t, err)
builder := NewWailsBuilder()
cfg := &build.Config{
ProjectDir: projectDir,
OutputDir: outputDir,
Name: "testapp",
}
targets := []build.Target{
{OS: runtime.GOOS, Arch: runtime.GOARCH},
}
artifacts, err := builder.Build(context.Background(), cfg, targets)
require.NoError(t, err)
assert.NotEmpty(t, artifacts)
})
}
func TestWailsBuilder_Name_Good(t *testing.T) {
builder := NewWailsBuilder()
assert.Equal(t, "wails", builder.Name())
}
func TestWailsBuilder_Build_V2_Good(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
if _, err := exec.LookPath("wails"); err != nil {
t.Skip("wails not installed, skipping integration test")
}
t.Run("builds v2 project", func(t *testing.T) {
projectDir := setupWailsV2TestProject(t)
outputDir := t.TempDir()
builder := NewWailsBuilder()
cfg := &build.Config{
ProjectDir: projectDir,
OutputDir: outputDir,
Name: "testapp",
}
targets := []build.Target{
{OS: runtime.GOOS, Arch: runtime.GOARCH},
}
feat: git command, build improvements, and go fmt git-aware (#74) * feat(go): make go fmt git-aware by default - By default, only check changed Go files (modified, staged, untracked) - Add --all flag to check all files (previous behaviour) - Reduces noise when running fmt on large codebases Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * feat(build): minimal output by default, add missing i18n - Default output now shows single line: "Success Built N artifacts (dir)" - Add --verbose/-v flag to show full detailed output - Add all missing i18n translations for build commands - Errors still show failure reason in minimal mode Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * feat: add root-level `core git` command - Create pkg/gitcmd with git workflow commands as root menu - Export command builders from pkg/dev (AddCommitCommand, etc.) - Commands available under both `core git` and `core dev` for compatibility - Git commands: health, commit, push, pull, work, sync, apply - GitHub orchestration stays in dev: issues, reviews, ci, impact Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * feat(qa): add docblock coverage checking Implement docblock/docstring coverage analysis for Go code: - New `core qa docblock` command to check coverage - Shows compact file:line list when under threshold - Integrate with `core go qa` as a default check - Add --docblock-threshold flag (default 80%) The checker uses Go AST parsing to find exported symbols (functions, types, consts, vars) without documentation. Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * fix: address CodeRabbit review feedback - Fix doc comment: "status" → "health" in gitcmd package - Implement --check flag for `core go fmt` (exits non-zero if files need formatting) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * docs: add docstrings for 100% coverage Add documentation comments to all exported symbols: - pkg/build: ProjectType constants - pkg/cli: LogLevel, RenderStyle, TableStyle - pkg/framework: ServiceFor, MustServiceFor, Core.Core - pkg/git: GitError.Error, GitError.Unwrap - pkg/i18n: Handler Match/Handle methods - pkg/log: Level constants - pkg/mcp: Tool input/output types - pkg/php: Service constants, QA types, service methods - pkg/process: ServiceError.Error - pkg/repos: RepoType constants - pkg/setup: ChangeType, ChangeCategory constants - pkg/workspace: AddWorkspaceCommands Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * chore: standardize line endings to LF Add .gitattributes to enforce LF line endings for all text files. Normalize all existing files to use Unix-style line endings. Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * fix: address CodeRabbit review feedback - cmd_format.go: validate --check/--fix mutual exclusivity, capture stderr - cmd_docblock.go: return error instead of os.Exit(1) for proper error handling Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * fix: address CodeRabbit review feedback (round 2) - linuxkit.go: propagate state update errors, handle cmd.Wait() errors in waitForExit - mcp.go: guard against empty old_string in editDiff to prevent runaway edits - cmd_docblock.go: log parse errors instead of silently skipping Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-01 10:48:44 +00:00
// This will likely fail in a real run because we can't easily mock the full wails v2 build process
// (which needs a valid project with main.go etc).
// But it validates we are trying to run the command.
feat: git command, build improvements, and go fmt git-aware (#74) * feat(go): make go fmt git-aware by default - By default, only check changed Go files (modified, staged, untracked) - Add --all flag to check all files (previous behaviour) - Reduces noise when running fmt on large codebases Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * feat(build): minimal output by default, add missing i18n - Default output now shows single line: "Success Built N artifacts (dir)" - Add --verbose/-v flag to show full detailed output - Add all missing i18n translations for build commands - Errors still show failure reason in minimal mode Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * feat: add root-level `core git` command - Create pkg/gitcmd with git workflow commands as root menu - Export command builders from pkg/dev (AddCommitCommand, etc.) - Commands available under both `core git` and `core dev` for compatibility - Git commands: health, commit, push, pull, work, sync, apply - GitHub orchestration stays in dev: issues, reviews, ci, impact Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * feat(qa): add docblock coverage checking Implement docblock/docstring coverage analysis for Go code: - New `core qa docblock` command to check coverage - Shows compact file:line list when under threshold - Integrate with `core go qa` as a default check - Add --docblock-threshold flag (default 80%) The checker uses Go AST parsing to find exported symbols (functions, types, consts, vars) without documentation. Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * fix: address CodeRabbit review feedback - Fix doc comment: "status" → "health" in gitcmd package - Implement --check flag for `core go fmt` (exits non-zero if files need formatting) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * docs: add docstrings for 100% coverage Add documentation comments to all exported symbols: - pkg/build: ProjectType constants - pkg/cli: LogLevel, RenderStyle, TableStyle - pkg/framework: ServiceFor, MustServiceFor, Core.Core - pkg/git: GitError.Error, GitError.Unwrap - pkg/i18n: Handler Match/Handle methods - pkg/log: Level constants - pkg/mcp: Tool input/output types - pkg/php: Service constants, QA types, service methods - pkg/process: ServiceError.Error - pkg/repos: RepoType constants - pkg/setup: ChangeType, ChangeCategory constants - pkg/workspace: AddWorkspaceCommands Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * chore: standardize line endings to LF Add .gitattributes to enforce LF line endings for all text files. Normalize all existing files to use Unix-style line endings. Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * fix: address CodeRabbit review feedback - cmd_format.go: validate --check/--fix mutual exclusivity, capture stderr - cmd_docblock.go: return error instead of os.Exit(1) for proper error handling Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * fix: address CodeRabbit review feedback (round 2) - linuxkit.go: propagate state update errors, handle cmd.Wait() errors in waitForExit - mcp.go: guard against empty old_string in editDiff to prevent runaway edits - cmd_docblock.go: log parse errors instead of silently skipping Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-01 10:48:44 +00:00
// For now, we just verify it attempts the build - error is expected
_, _ = builder.Build(context.Background(), cfg, targets)
})
}
func TestWailsBuilder_Detect_Good(t *testing.T) {
t.Run("detects Wails project with wails.json", func(t *testing.T) {
dir := t.TempDir()
err := os.WriteFile(filepath.Join(dir, "wails.json"), []byte("{}"), 0644)
require.NoError(t, err)
builder := NewWailsBuilder()
detected, err := builder.Detect(dir)
assert.NoError(t, err)
assert.True(t, detected)
})
t.Run("returns false for Go-only project", func(t *testing.T) {
dir := t.TempDir()
err := os.WriteFile(filepath.Join(dir, "go.mod"), []byte("module test"), 0644)
require.NoError(t, err)
builder := NewWailsBuilder()
detected, err := builder.Detect(dir)
assert.NoError(t, err)
assert.False(t, detected)
})
t.Run("returns false for Node.js project", func(t *testing.T) {
dir := t.TempDir()
err := os.WriteFile(filepath.Join(dir, "package.json"), []byte("{}"), 0644)
require.NoError(t, err)
builder := NewWailsBuilder()
detected, err := builder.Detect(dir)
assert.NoError(t, err)
assert.False(t, detected)
})
t.Run("returns false for empty directory", func(t *testing.T) {
dir := t.TempDir()
builder := NewWailsBuilder()
detected, err := builder.Detect(dir)
assert.NoError(t, err)
assert.False(t, detected)
})
}
func TestDetectPackageManager_Good(t *testing.T) {
t.Run("detects bun from bun.lockb", func(t *testing.T) {
dir := t.TempDir()
err := os.WriteFile(filepath.Join(dir, "bun.lockb"), []byte(""), 0644)
require.NoError(t, err)
result := detectPackageManager(dir)
assert.Equal(t, "bun", result)
})
t.Run("detects pnpm from pnpm-lock.yaml", func(t *testing.T) {
dir := t.TempDir()
err := os.WriteFile(filepath.Join(dir, "pnpm-lock.yaml"), []byte(""), 0644)
require.NoError(t, err)
result := detectPackageManager(dir)
assert.Equal(t, "pnpm", result)
})
t.Run("detects yarn from yarn.lock", func(t *testing.T) {
dir := t.TempDir()
err := os.WriteFile(filepath.Join(dir, "yarn.lock"), []byte(""), 0644)
require.NoError(t, err)
result := detectPackageManager(dir)
assert.Equal(t, "yarn", result)
})
t.Run("detects npm from package-lock.json", func(t *testing.T) {
dir := t.TempDir()
err := os.WriteFile(filepath.Join(dir, "package-lock.json"), []byte(""), 0644)
require.NoError(t, err)
result := detectPackageManager(dir)
assert.Equal(t, "npm", result)
})
t.Run("defaults to npm when no lock file", func(t *testing.T) {
dir := t.TempDir()
result := detectPackageManager(dir)
assert.Equal(t, "npm", result)
})
t.Run("prefers bun over other lock files", func(t *testing.T) {
dir := t.TempDir()
// Create multiple lock files
require.NoError(t, os.WriteFile(filepath.Join(dir, "bun.lockb"), []byte(""), 0644))
require.NoError(t, os.WriteFile(filepath.Join(dir, "yarn.lock"), []byte(""), 0644))
require.NoError(t, os.WriteFile(filepath.Join(dir, "package-lock.json"), []byte(""), 0644))
result := detectPackageManager(dir)
assert.Equal(t, "bun", result)
})
t.Run("prefers pnpm over yarn and npm", func(t *testing.T) {
dir := t.TempDir()
// Create multiple lock files (no bun)
require.NoError(t, os.WriteFile(filepath.Join(dir, "pnpm-lock.yaml"), []byte(""), 0644))
require.NoError(t, os.WriteFile(filepath.Join(dir, "yarn.lock"), []byte(""), 0644))
require.NoError(t, os.WriteFile(filepath.Join(dir, "package-lock.json"), []byte(""), 0644))
result := detectPackageManager(dir)
assert.Equal(t, "pnpm", result)
})
t.Run("prefers yarn over npm", func(t *testing.T) {
dir := t.TempDir()
// Create multiple lock files (no bun or pnpm)
require.NoError(t, os.WriteFile(filepath.Join(dir, "yarn.lock"), []byte(""), 0644))
require.NoError(t, os.WriteFile(filepath.Join(dir, "package-lock.json"), []byte(""), 0644))
result := detectPackageManager(dir)
assert.Equal(t, "yarn", result)
})
}
func TestWailsBuilder_Build_Bad(t *testing.T) {
t.Run("returns error for nil config", func(t *testing.T) {
builder := NewWailsBuilder()
artifacts, err := builder.Build(context.Background(), nil, []build.Target{{OS: "linux", Arch: "amd64"}})
assert.Error(t, err)
assert.Nil(t, artifacts)
assert.Contains(t, err.Error(), "config is nil")
})
t.Run("returns error for empty targets", func(t *testing.T) {
projectDir := setupWailsTestProject(t)
builder := NewWailsBuilder()
cfg := &build.Config{
ProjectDir: projectDir,
OutputDir: t.TempDir(),
Name: "test",
}
artifacts, err := builder.Build(context.Background(), cfg, []build.Target{})
assert.Error(t, err)
assert.Nil(t, artifacts)
assert.Contains(t, err.Error(), "no targets specified")
})
}
func TestWailsBuilder_Build_Good(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
// Check if wails3 is available in PATH
if _, err := exec.LookPath("wails3"); err != nil {
t.Skip("wails3 not installed, skipping integration test")
}
t.Run("builds for current platform", func(t *testing.T) {
projectDir := setupWailsTestProject(t)
outputDir := t.TempDir()
builder := NewWailsBuilder()
cfg := &build.Config{
ProjectDir: projectDir,
OutputDir: outputDir,
Name: "testapp",
}
targets := []build.Target{
{OS: runtime.GOOS, Arch: runtime.GOARCH},
}
artifacts, err := builder.Build(context.Background(), cfg, targets)
require.NoError(t, err)
require.Len(t, artifacts, 1)
// Verify artifact properties
artifact := artifacts[0]
assert.Equal(t, runtime.GOOS, artifact.OS)
assert.Equal(t, runtime.GOARCH, artifact.Arch)
})
}
func TestWailsBuilder_Interface_Good(t *testing.T) {
// Verify WailsBuilder implements Builder interface
var _ build.Builder = (*WailsBuilder)(nil)
var _ build.Builder = NewWailsBuilder()
}
func TestWailsBuilder_Ugly(t *testing.T) {
t.Run("handles nonexistent frontend directory gracefully", func(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
// Create a Wails project without a frontend directory
dir := t.TempDir()
err := os.WriteFile(filepath.Join(dir, "wails.json"), []byte("{}"), 0644)
require.NoError(t, err)
builder := NewWailsBuilder()
cfg := &build.Config{
ProjectDir: dir,
OutputDir: t.TempDir(),
Name: "test",
}
targets := []build.Target{
{OS: runtime.GOOS, Arch: runtime.GOARCH},
}
// This will fail because wails3 isn't set up, but it shouldn't panic
// due to missing frontend directory
_, err = builder.Build(context.Background(), cfg, targets)
// We expect an error (wails3 build will fail), but not a panic
// The error should be about wails3 build, not about frontend
if err != nil {
assert.NotContains(t, err.Error(), "frontend dependencies")
}
})
t.Run("handles context cancellation", func(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
projectDir := setupWailsTestProject(t)
builder := NewWailsBuilder()
cfg := &build.Config{
ProjectDir: projectDir,
OutputDir: t.TempDir(),
Name: "canceltest",
}
targets := []build.Target{
{OS: runtime.GOOS, Arch: runtime.GOARCH},
}
// Create an already cancelled context
ctx, cancel := context.WithCancel(context.Background())
cancel()
artifacts, err := builder.Build(ctx, cfg, targets)
assert.Error(t, err)
assert.Empty(t, artifacts)
})
}