Trebejo.Mox (Trebejo v2.0.0)

Copy Markdown View Source

Test-only mocking layer for Trebejo command execution.

Lets you stub Trebejo.Util.run_cmd/3 (and downstream wrappers) without spinning up real binaries. Unlike Mox, this is explicit: you stub a specific (cmd_name, args) pair, not a behaviour. The tradeoff is simplicity — no expect/3 count tracking, no verify_on_exit!.

Usage

In a test:

use ExUnit.Case, async: false
import Trebejo.Mox

setup do
  stub_cmd("echo", ["hello"], {:ok, "hello\n", 0})
  stub_cmd("git", ["status"], {:ok, "", 0})
  :ok
end

test "wraps echo in docker" do
  {:ok, out, 0} = Trebejo.Util.run_cmd("echo", ["hello"])
  assert out =~ "hello"
end

stub_cmd/3 is order-specific by default (the args list must match exactly). For git-style wrappers that build args dynamically, use stub_cmd_pattern/2 with a regex on the joined command line.

Cleanup

Stubs live in a process named Trebejo.Mox.Server. The agent is started automatically on first stub and reset by reset_stubs/0. Tests using stub_cmd/3 should call reset_stubs/0 in setup if they run with async: true.

Summary

Functions

Look up a stub for the given call. Returns the result tuple or :miss.

Wipe all stubs. Call in setup to keep tests isolated.

Stub a specific (cmd_name, args) → result triple.

Stub any call whose joined command line matches regex. Useful for commands whose args are built dynamically and vary by call site.

Functions

lookup(cmd_name, args)

@spec lookup(binary(), [binary()]) ::
  {:ok, binary(), non_neg_integer()}
  | {:error, term()}
  | {:pattern, Regex.t(), {:ok, binary(), non_neg_integer()} | {:error, term()}}
  | :miss

Look up a stub for the given call. Returns the result tuple or :miss.

Internal — used by Trebejo.Mox.Runner.

reset_stubs()

@spec reset_stubs() :: :ok

Wipe all stubs. Call in setup to keep tests isolated.

stub_cmd(cmd_name, args, result)

@spec stub_cmd(
  binary(),
  [binary()],
  {:ok, binary(), non_neg_integer()} | {:error, term()}
) :: :ok

Stub a specific (cmd_name, args) → result triple.

result must be a {:ok, stdout, exit_code} or {:error, term()} tuple. Anything else is ignored by the runner.

stub_cmd_pattern(regex, result)

@spec stub_cmd_pattern(
  Regex.t(),
  {:ok, binary(), non_neg_integer()} | {:error, term()}
) :: :ok

Stub any call whose joined command line matches regex. Useful for commands whose args are built dynamically and vary by call site.

stub_cmd_pattern(~r/^docker compose ps/, {:ok, "myapp\n", 0})