AI agent skill that researches any topic across Reddit, X, YouTube, HN, Polymarket, and the web - then synthesizes a grounded summary
Python ai-promptsai-skillblueskyclaudeclaude-codeclawhubdeep-researchhackernewsinstagramopenclawpolymarketrecencyredditresearchsocial-mediatiktoktrendstwitterweb-searchyoutube
package engine
import (
"context"
"errors"
"os"
"path/filepath"
"runtime"
"strconv"
"strings"
"testing"
"time"
)
// makeStubPython writes a shell script that simulates python3 and returns
// its absolute path. The script honors a small env-driven protocol so each
// test can shape its output:
//
// STUB_STDOUT - text printed to stdout
// STUB_STDERR - text printed to stderr
// STUB_EXIT_CODE - integer exit code (default 0)
// STUB_SLEEP_SECS - sleep before exiting (for timeout tests)
// STUB_ECHO_ENV - name of an env var; the stub prints "<NAME>=<VALUE>"
// STUB_ECHO_ARG - integer index; the stub prints "ARG<i>=<args[i]>"
// STUB_ECHO_ARGS - when set (any value), the stub prints its full argv
// after the script path, one argument per line, so tests
// can assert the exact argv the engine receives
//
// The stub ignores its first argument (the script path), matching how a
// real python3 invocation treats `python3 last30days.py ...`.
func makeStubPython(t *testing.T) string {
t.Helper()
if runtime.GOOS == "windows" {
t.Skip("stub-python tests rely on POSIX shell")
}
dir := t.TempDir()
path := filepath.Join(dir, "python3-stub.sh")
script := `#!/usr/bin/env bash
if [ -n "${STUB_SLEEP_SECS:-}" ]; then sleep "$STUB_SLEEP_SECS"; fi
if [ -n "${STUB_STDOUT:-}" ]; then printf "%s" "$STUB_STDOUT"; fi
if [ -n "${STUB_STDERR:-}" ]; then printf "%s" "$STUB_STDERR" >&2; fi
if [ -n "${STUB_ECHO_ENV:-}" ]; then echo "${STUB_ECHO_ENV}=${!STUB_ECHO_ENV:-<unset>}"; fi
if [ -n "${STUB_ECHO_ARG:-}" ]; then echo "ARG${STUB_ECHO_ARG}=${!STUB_ECHO_ARG:-<unset>}"; fi
if [ -n "${STUB_ECHO_ARGS:-}" ]; then shift; printf "%s\n" "$@"; fi
exit "${STUB_EXIT_CODE:-0}"
`
if err := os.WriteFile(path, []byte(script), 0o755); err != nil {
t.Fatalf("write stub: %v", err)
}
return path
}
// stageCache materializes a fake CacheDir with a no-op last30days.py so
// the existence check in Run passes. The stub python3 ignores the script
// contents, so the file just has to exist.
func stageCache(t *testing.T) string {
t.Helper()
dir := t.TempDir()
if err := os.WriteFile(filepath.Join(dir, "last30days.py"), []byte("# stub\n"), 0o644); err != nil {
t.Fatalf("stage cache: %v", err)
}
return dir
}
func TestRunHappyPath(t *testing.T) {
stub := makeStubPython(t)
cache := stageCache(t)
t.Setenv("STUB_STDOUT", "synthesis output\n")
res, err := Run(context.Background(), RunOptions{
PythonPath: stub,
CacheDir: cache,
Args: []string{"my topic", "--emit=compact"},
})
if err != nil {
t.Fatalf("Run: %v", err)
}
if string(res.Stdout) != "synthesis output\n" {
t.Fatalf("stdout = %q, want %q", res.Stdout, "synthesis output\n")
}
if res.ExitCode != 0 {
t.Fatalf("ExitCode = %d, want 0", res.ExitCode)
}
if res.TimedOut {
t.Fatal("TimedOut = true, want false")
}
}
// TestRunForwardsExactArgv pins the full argv the engine subprocess
// receives: options first, explicit empty --save-dir on decline, `--`
// separator, then the positional topic. The default-deny
// --no-browser-cookies flag rides along in this shape too.
func TestRunForwardsExactArgv(t *testing.T) {
stub := makeStubPython(t)
cache := stageCache(t)
t.Setenv("STUB_ECHO_ARGS", "1")
want := []string{"--emit=compact", "--no-browser-cookies", "--save-dir", "", "--", "--mock"}
res, err := Run(context.Background(), RunOptions{
PythonPath: stub,
CacheDir: cache,
Args: want,
})
if err != nil {
t.Fatalf("Run: %v", err)
}
got := strings.Split(strings.TrimSuffix(string(res.Stdout), "\n"), "\n")
if strings.Join(got, "\x00") != strings.Join(want, "\x00") {
t.Fatalf("engine argv = %#v, want %#v", got, want)
}
}
func TestRunForwardsEnv(t *testing.T) {
stub := makeStubPython(t)
cache := stageCache(t)
t.Setenv("OPENAI_API_KEY", "sk-test-value")
t.Setenv("STUB_ECHO_ENV", "OPENAI_API_KEY")
res, err := Run(context.Background(), RunOptions{
PythonPath: stub,
CacheDir: cache,
})
if err != nil {
t.Fatalf("Run: %v", err)
}
if got := strings.TrimSpace(string(res.Stdout)); got != "OPENAI_API_KEY=sk-test-value" {
t.Fatalf("stdout = %q, want OPENAI_API_KEY=sk-test-value", got)
}
}
func TestRunSetsPythonPath(t *testing.T) {
stub := makeStubPython(t)
cache := stageCache(t)
t.Setenv("STUB_ECHO_ENV", "PYTHONPATH")
res, err := Run(context.Background(), RunOptions{
PythonPath: stub,
CacheDir: cache,
})
if err != nil {
t.Fatalf("Run: %v", err)
}
want := "PYTHONPATH=" + cache
if got := strings.TrimSpace(string(res.Stdout)); got != want {
t.Fatalf("stdout = %q, want %q", got, want)
}
}
// TestRunDropsPreExistingPythonPath guards the buildEnv dedup: when the
// parent already sets PYTHONPATH (common on dev machines and CI runners
// that touch Python), the child must NOT see two PYTHONPATH= entries.
// POSIX getenv returns the first match, so a duplicate from os.Environ
// would shadow our cache-dir entry and break `from lib import ...`.
func TestRunDropsPreExistingPythonPath(t *testing.T) {
stub := makeStubPython(t)
cache := stageCache(t)
t.Setenv("PYTHONPATH", "/users-stale-pythonpath")
t.Setenv("STUB_ECHO_ENV", "PYTHONPATH")
res, err := Run(context.Background(), RunOptions{
PythonPath: stub,
CacheDir: cache,
})
if err != nil {
t.Fatalf("Run: %v", err)
}
got := strings.TrimSpace(string(res.Stdout))
want := "PYTHONPATH=" + cache
if got != want {
t.Fatalf("stdout = %q, want %q (stale parent value leaked through)", got, want)
}
}
func TestBuildEnvDropsAllPreExistingPythonPath(t *testing.T) {
// Direct unit test on buildEnv to catch the case where the parent has
// PYTHONPATH set: the returned slice must contain exactly one
// PYTHONPATH= entry, and it must be ours.
t.Setenv("PYTHONPATH", "/parent/one")
cache := "/cache/dir"
out := buildEnv(cache, []string{"EXTRA=1"})
var pythonPaths []string
for _, kv := range out {
if strings.HasPrefix(kv, "PYTHONPATH=") {
pythonPaths = append(pythonPaths, kv)
}
}
if len(pythonPaths) != 1 {
t.Fatalf("got %d PYTHONPATH entries, want 1: %v", len(pythonPaths), pythonPaths)
}
if pythonPaths[0] != "PYTHONPATH="+cache {
t.Fatalf("PYTHONPATH = %q, want %q", pythonPaths[0], "PYTHONPATH="+cache)
}
// Confirm ExtraEnv still rides along.
found := false
for _, kv := range out {
if kv == "EXTRA=1" {
found = true
break
}
}
if !found {
t.Fatal("EXTRA=1 missing from buildEnv output")
}
}
func TestRunSurfacesExitCode(t *testing.T) {
stub := makeStubPython(t)
cache := stageCache(t)
t.Setenv("STUB_STDERR", "engine boom\n")
t.Setenv("STUB_EXIT_CODE", "2")
res, err := Run(context.Background(), RunOptions{
PythonPath: stub,
CacheDir: cache,
})
if err == nil {
t.Fatal("expected error for non-zero exit")
}
if res == nil {
t.Fatal("res is nil; want populated result alongside error")
}
if res.ExitCode != 2 {
t.Fatalf("ExitCode = %d, want 2", res.ExitCode)
}
if !strings.Contains(string(res.Stderr), "engine boom") {
t.Fatalf("stderr did not surface engine output: %q", res.Stderr)
}
}
func TestRunTimesOut(t *testing.T) {
stub := makeStubPython(t)
cache := stageCache(t)
t.Setenv("STUB_SLEEP_SECS", "3")
res, err := Run(context.Background(), RunOptions{
PythonPath: stub,
CacheDir: cache,
Timeout: 200 * time.Millisecond,
})
if err == nil {
t.Fatal("expected timeout error")
}
if !res.TimedOut {
t.Fatal("TimedOut = false, want true")
}
if !strings.Contains(err.Error(), "timeout") {
t.Fatalf("error %q lacks 'timeout' marker", err)
}
if !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("Run error = %v, want context.DeadlineExceeded", err)
}
}
func TestRunCanceledBeforeStart(t *testing.T) {
for _, wantErr := range []error{context.Canceled, context.DeadlineExceeded} {
t.Run(wantErr.Error(), func(t *testing.T) {
expired := wantErr == context.DeadlineExceeded
ctx, cancel := context.WithCancel(context.Background())
if expired {
cancel()
ctx, cancel = context.WithDeadline(context.Background(), time.Now().Add(-time.Second))
}
cancel()
cache := stageCache(t)
// A missing executable exposes an attempted start even when a
// valid child would be killed before it could write output.
res, err := Run(ctx, RunOptions{
PythonPath: filepath.Join(cache, "must-not-start"),
CacheDir: cache,
})
if !errors.Is(err, wantErr) {
t.Errorf("Run error = %v, want %v", err, wantErr)
}
if res == nil {
t.Fatal("Run result is nil; want a canceled result")
}
if res.TimedOut != expired || res.ExitCode != -1 || len(res.Stdout) != 0 {
t.Errorf("Run result = %+v, want no started subprocess and TimedOut=%v", res, expired)
}
})
}
}
func TestResolvePythonHonorsEnvOverride(t *testing.T) {
executable := fakePython(t, t.TempDir(), "selected-python", "3.12")
t.Setenv(PythonEnvOverride, executable)
t.Setenv("PATH", "")
got, err := resolvePython("")
if err != nil {
t.Fatalf("resolvePython: %v", err)
}
gotInfo, err := os.Stat(got)
if err != nil {
t.Fatalf("stat resolved path %q: %v", got, err)
}
wantInfo, err := os.Stat(executable)
if err != nil {
t.Fatalf("stat override path %q: %v", executable, err)
}
if !os.SameFile(gotInfo, wantInfo) {
t.Fatalf("resolvePython = %q, want executable %q", got, executable)
}
}
func TestResolvePythonRejectsInvalidEnvOverride(t *testing.T) {
t.Run("missing path", func(t *testing.T) {
missing := filepath.Join(t.TempDir(), "missing-python")
t.Setenv(PythonEnvOverride, missing)
_, err := resolvePython("")
if err == nil {
t.Fatal("expected invalid override error")
}
if !strings.Contains(err.Error(), PythonEnvOverride) || !strings.Contains(err.Error(), strconv.Quote(missing)) {
t.Fatalf("error %q does not identify invalid %s path %q", err, PythonEnvOverride, missing)
}
})
t.Run("empty value", func(t *testing.T) {
t.Setenv(PythonEnvOverride, "")
_, err := resolvePython("")
if err == nil {
t.Fatal("expected empty override error")
}
if !strings.Contains(err.Error(), PythonEnvOverride) || !strings.Contains(err.Error(), "set but empty") {
t.Fatalf("error %q does not clearly identify the empty override", err)
}
})
}
func TestResolvePythonDefaultsToPython3Lookup(t *testing.T) {
dir := t.TempDir()
candidate := fakePython(t, dir, DefaultPythonBinary, "3.12")
t.Setenv(PythonEnvOverride, "temporarily-set-for-cleanup")
if err := os.Unsetenv(PythonEnvOverride); err != nil {
t.Fatalf("unset %s: %v", PythonEnvOverride, err)
}
t.Setenv("PATH", dir)
got, err := resolvePython("")
if err != nil {
t.Fatalf("resolvePython: %v", err)
}
gotInfo, err := os.Stat(got)
if err != nil {
t.Fatalf("stat resolved path %q: %v", got, err)
}
wantInfo, err := os.Stat(candidate)
if err != nil {
t.Fatalf("stat default stub %q: %v", candidate, err)
}
if !os.SameFile(gotInfo, wantInfo) {
t.Fatalf("resolvePython = %q, want python3 lookup result %q", got, candidate)
}
}
func TestRunMissingPython(t *testing.T) {
unsetPythonOverride(t)
cache := stageCache(t)
// Empty PATH guarantees the lookup fails. PythonPath stays unset so Run
// falls through to exec.LookPath.
t.Setenv(PythonEnvOverride, "temporarily-set-for-cleanup")
if err := os.Unsetenv(PythonEnvOverride); err != nil {
t.Fatalf("unset %s: %v", PythonEnvOverride, err)
}
t.Setenv("PATH", "")
_, err := Run(context.Background(), RunOptions{CacheDir: cache})
if err == nil {
t.Fatal("expected lookup failure with empty PATH")
}
if !strings.Contains(err.Error(), DefaultPythonBinary) {
t.Fatalf("error %q does not mention %s", err, DefaultPythonBinary)
}
if !strings.Contains(err.Error(), PythonInstallURL) {
t.Fatalf("error %q does not include install URL", err)
}
}
func TestResolvePythonRejectsRelativePATH(t *testing.T) {
unsetPythonOverride(t)
if runtime.GOOS == "windows" {
t.Skip("POSIX executable fixture")
}
t.Chdir(t.TempDir())
if err := os.WriteFile(DefaultPythonBinary, []byte("#!/bin/sh\nexit 0\n"), 0o755); err != nil {
t.Fatal(err)
}
t.Setenv("PATH", ".")
// Exercise our own guard even when Go's ErrDot protection is disabled.
t.Setenv("GODEBUG", "execerrdot=0")
if path, err := resolvePython(""); err == nil || path != "" {
t.Fatalf("resolvePython accepted relative executable: path=%q err=%v", path, err)
}
}
func TestResolvePythonAcceptsAbsolutePATH(t *testing.T) {
unsetPythonOverride(t)
if runtime.GOOS == "windows" {
t.Skip("POSIX executable fixture")
}
dir := t.TempDir()
want := filepath.Join(dir, DefaultPythonBinary)
if err := os.WriteFile(want, []byte("#!/bin/sh\nprintf '3.12\\n'\n"), 0o755); err != nil {
t.Fatal(err)
}
t.Setenv("PATH", dir)
if path, err := resolvePython(""); err != nil || path != want {
t.Fatalf("resolvePython = %q, %v; want %q", path, err, want)
}
}
func TestResolvePythonPreservesExplicitOverride(t *testing.T) {
t.Setenv("PATH", "")
want := filepath.Join("explicit", "python")
if path, err := resolvePython(want); err != nil || path != want {
t.Fatalf("resolvePython = %q, %v; want trusted override %q", path, err, want)
}
}
func TestRunMissingScript(t *testing.T) {
stub := makeStubPython(t)
// CacheDir exists but contains no last30days.py.
cache := t.TempDir()
_, err := Run(context.Background(), RunOptions{
PythonPath: stub,
CacheDir: cache,
})
if err == nil {
t.Fatal("expected error when last30days.py missing")
}
if !strings.Contains(err.Error(), "last30days.py") {
t.Fatalf("error %q does not name missing script", err)
}
}
func TestRunRejectsEmptyCacheDir(t *testing.T) {
stub := makeStubPython(t)
_, err := Run(context.Background(), RunOptions{PythonPath: stub})
if err == nil {
t.Fatal("expected error for empty CacheDir")
}
if !errors.Is(err, err) || !strings.Contains(err.Error(), "CacheDir") {
t.Fatalf("error %q does not name CacheDir", err)
}
}
func TestResolveTimeoutHonorsEnv(t *testing.T) {
t.Setenv(TimeoutEnvOverride, "750ms")
if got := resolveTimeout(0); got != 750*time.Millisecond {
t.Fatalf("resolveTimeout = %v, want 750ms", got)
}
t.Setenv(TimeoutEnvOverride, "garbage")
if got := resolveTimeout(0); got != DefaultTimeout {
t.Fatalf("garbage value: got %v, want default %v", got, DefaultTimeout)
}
if got := resolveTimeout(time.Minute); got != time.Minute {
t.Fatalf("explicit value not honored: got %v", got)
}
}
func TestResolveTimeoutBareIntegerSeconds(t *testing.T) {
t.Setenv(TimeoutEnvOverride, "300")
if got := resolveTimeout(0); got != 300*time.Second {
t.Fatalf("bare integer 300: got %v, want 5m0s", got)
}
t.Setenv(TimeoutEnvOverride, "1")
if got := resolveTimeout(0); got != 1*time.Second {
t.Fatalf("bare integer 1: got %v, want 1s", got)
}
t.Setenv(TimeoutEnvOverride, "0")
if got := resolveTimeout(0); got != DefaultTimeout {
t.Fatalf("bare integer 0: got %v, want default %v", got, DefaultTimeout)
}
t.Setenv(TimeoutEnvOverride, "-1")
if got := resolveTimeout(0); got != DefaultTimeout {
t.Fatalf("bare integer -1: got %v, want default %v", got, DefaultTimeout)
}
}