Back to Repositories

Testing Inline Command Substitution for Environment Variables in Kamal

This test suite validates the inline command substitution functionality in Kamal’s secrets management system, focusing on how environment variables are processed with embedded commands. It ensures proper handling of both Kamal-specific secret commands and general shell commands.

Test Coverage Overview

The test suite covers two primary scenarios for command substitution in environment variables:

  • Kamal secrets command interpolation using the ‘secrets fetch’ command
  • General shell command execution and substitution
  • Verification of correct output string formatting

Implementation Analysis

The implementation uses Minitest’s mocking capabilities to verify command execution behavior. It employs expects/stubs patterns to isolate the command substitution logic and validates the string manipulation for environment variable assignments.

The tests specifically focus on the InlineCommandSubstitution class’s call method, ensuring proper command execution and result formatting.

Technical Details

  • Testing Framework: Minitest
  • Mocking Library: Built-in Minitest mocking
  • Test Class: SecretsInlineCommandSubstitution
  • Key Methods Tested: Kamal::Secrets::Dotenv::InlineCommandSubstitution.call
  • Command Types: Kamal secrets commands, Shell commands

Best Practices Demonstrated

The test suite demonstrates several testing best practices including isolation of external command execution, clear test case separation, and explicit assertion of expected outcomes. It effectively uses mocking to prevent actual command execution while verifying the correct interaction patterns.

  • Isolated test cases for different command types
  • Proper mocking of system commands
  • Clear input/output validation

basecamp/kamal

test/secrets/dotenv_inline_command_substitution_test.rb

            
require "test_helper"

class SecretsInlineCommandSubstitution < SecretAdapterTestCase
  test "inlines kamal secrets commands" do
    Kamal::Cli::Main.expects(:start).with { |command| command == [ "secrets", "fetch", "...", "--inline" ] }.returns("results")
    substituted = Kamal::Secrets::Dotenv::InlineCommandSubstitution.call("FOO=$(kamal secrets fetch ...)", nil, overwrite: false)
    assert_equal "FOO=results", substituted
  end

  test "executes other commands" do
    Kamal::Secrets::Dotenv::InlineCommandSubstitution.stubs(:`).with("blah").returns("results")
    substituted = Kamal::Secrets::Dotenv::InlineCommandSubstitution.call("FOO=$(blah)", nil, overwrite: false)
    assert_equal "FOO=results", substituted
  end
end