testhelpers

package
v0.6.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 29, 2026 License: Apache-2.0 Imports: 22 Imported by: 0

Documentation

Overview

Package testhelpers provides reusable test utilities and helpers for testing the CipherSwarm agent.

Package testhelpers provides reusable test utilities and helpers for testing the CipherSwarm agent.

Package testhelpers provides reusable test utilities and helpers for testing the CipherSwarm agent.

Package testhelpers provides reusable test utilities and helpers for testing the CipherSwarm agent.

Package testhelpers provides reusable test utilities and helpers for testing the CipherSwarm agent.

Mock responders register multiple URL patterns and HTTP methods per endpoint for compatibility across API path variations (e.g. /client/agents vs /agents).

Package testhelpers provides reusable test utilities and helpers for testing the CipherSwarm agent.

Package testhelpers provides reusable test utilities and helpers for testing the CipherSwarm agent.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AssertAgentConfiguration

func AssertAgentConfiguration(t *testing.T, expected, actual TestAgentConfiguration)

AssertAgentConfiguration compares TestAgentConfiguration objects with detailed field-by-field comparison.

func AssertDeviceStatus

func AssertDeviceStatus(t *testing.T, expected, actual api.DeviceStatus)

AssertDeviceStatus compares two DeviceStatus objects field-by-field with clear error messages. This is useful when testing the convertDeviceStatuses function in lib/agentClient.go.

func AssertErrorType

func AssertErrorType(t *testing.T, err error, expectedType any)

AssertErrorType verifies that an error is of a specific API error type (e.g., *api.APIError or *api.SetTaskAbandonedError). This is critical for testing error handling paths in lib/errorUtils.go.

func AssertHashcatStatus

func AssertHashcatStatus(t *testing.T, expected, actual hashcat.Status)

AssertHashcatStatus compares hashcat Status objects including nested statusGuess and device arrays. Note: The Guess field uses hashcat's internal statusGuess type which is not exported, so Guess field comparisons are skipped. For full Guess field comparison, consider creating a helper in the hashcat package or using reflection.

func AssertTaskStatus

func AssertTaskStatus(t *testing.T, expected, actual api.HashcatStatusUpdate)

AssertTaskStatus compares two HashcatStatusUpdate objects, including nested HashcatGuess fields. This is useful when testing the convertToTaskStatus function in lib/task/status.go.

func CalculateTestChecksum

func CalculateTestChecksum(content []byte) string

CalculateTestChecksum calculates MD5 checksum of provided content and returns it as a hex string. This mirrors the checksum verification logic in lib/downloader/downloader.go (which uses cryptor.Md5File) and allows tests to generate valid checksums for test files.

func CreateHashListFile

func CreateHashListFile(t *testing.T, dir string, hashes []string) string

CreateHashListFile creates a hash list file with the provided hashes (one per line) in the specified directory. Returns the file path. This is specifically useful for testing hashcat session creation.

func CreateTempTestDir

func CreateTempTestDir(t *testing.T, _ string) string

CreateTempTestDir creates a temporary directory for test file operations and registers a cleanup function with t.Cleanup() to automatically remove it after the test completes. Returns the directory path.

func CreateTestFile

func CreateTestFile(t *testing.T, dir, filename string, content []byte) string

CreateTestFile creates a test file with the specified content in the given directory. Returns the full file path. Useful for testing file download verification and hashcat input files.

func CreateTestHashcatParams

func CreateTestHashcatParams() (hashcat.Params, func())

CreateTestHashcatParams returns minimal valid hashcat.Params for creating test sessions along with a cleanup function to delete the temporary hash file. AttackMode: hashcat.AttackModeMask HashFile: path to test hash file (created in temp directory) Mask: "?l" (simple lowercase mask) Other fields set to reasonable defaults.

func GetSubmitErrorCallCount

func GetSubmitErrorCallCount(agentID int64, baseURL string) int

GetSubmitErrorCallCount returns the number of times the submit_error endpoint was called for the given agent ID. This handles the different key formats that httpmock uses.

func MockAPIError

func MockAPIError(endpoint string, statusCode int, apiError api.APIError)

MockAPIError is a generic helper to mock API errors for any endpoint, useful for testing error handling across different API calls. The endpoint parameter should be a regex pattern string (will be compiled to *regexp.Regexp). Registers responders for multiple HTTP methods to handle different API call patterns.

func MockAuthenticationFailure

func MockAuthenticationFailure(statusCode int, errorMessage string)

MockAuthenticationFailure registers a mock responder for authentication that returns an error response with the specified status code and error message. Uses a regex pattern to match any HTTP scheme and host. Note: The API spec uses GET for authentication. POST is also registered for compatibility with test variations.

func MockAuthenticationSuccess

func MockAuthenticationSuccess(agentID int64)

MockAuthenticationSuccess registers a mock responder for the authentication endpoint that returns a successful authentication response with the provided agent ID. Uses a regex pattern to match any HTTP scheme and host. Note: The API spec uses GET for authentication. POST is also registered for compatibility with test variations.

func MockConfigurationError

func MockConfigurationError(statusCode int, errorMsg string)

MockConfigurationError registers a mock responder for configuration endpoint that returns an error response.

func MockConfigurationResponse

func MockConfigurationResponse(config TestAgentConfiguration)

MockConfigurationResponse registers a mock responder for the configuration endpoint that returns the provided configuration. Uses a regex pattern to match any HTTP scheme and host.

func MockDevicesList

func MockDevicesList() []string

MockDevicesList returns a mock list of device names for testing device discovery.

func MockDownloadServer

func MockDownloadServer(t *testing.T, baseDir string) *httptest.Server

MockDownloadServer creates a test HTTP server that serves files for download testing. Accepts a baseDir parameter to serve files from that directory. Returns the server instance which should be closed via t.Cleanup(). This will be used to test the downloader package without external dependencies.

func MockHeartbeatNoContent

func MockHeartbeatNoContent(agentID int64)

MockHeartbeatNoContent registers a mock responder for heartbeat endpoint that returns HTTP 204 No Content (indicating successful heartbeat with no state change). According to swagger.json, the endpoint is /api/v1/client/agents/{id}/heartbeat.

func MockHeartbeatResponse

func MockHeartbeatResponse(agentID int64, state api.State)

MockHeartbeatResponse registers a mock responder for heartbeat endpoint that returns the specified agent state. Accepts agentID and uses a regex pattern to match the path with the numeric agent ID. According to swagger.json, the endpoint is /api/v1/client/agents/{id}/heartbeat.

func MockHostInfo

func MockHostInfo() (*host.InfoStat, error)

MockHostInfo is a placeholder that always returns an error. Go's host.Info() cannot be easily mocked without interfaces or build tags. Tests requiring host info should use build tags or accept real host.Info() calls.

func MockSendCrackComplete

func MockSendCrackComplete(taskID int64)

MockSendCrackComplete registers a mock responder for send crack that returns HTTP 204 No Content (indicating hashlist completed). According to swagger.json, the endpoint is /api/v1/client/tasks/{id}/submit_crack.

func MockSendCrackSuccess

func MockSendCrackSuccess(taskID int64)

MockSendCrackSuccess registers a mock responder for POST /api/v1/client/tasks/{id}/submit_crack that returns HTTP 200 OK. According to swagger.json, the endpoint is /api/v1/client/tasks/{id}/submit_crack.

func MockSendStatusStale

func MockSendStatusStale(taskID int64)

MockSendStatusStale registers a mock responder for send status that returns HTTP 202 Accepted (indicating stale status). According to swagger.json, the endpoint is /api/v1/client/tasks/{id}/submit_status.

func MockSendStatusSuccess

func MockSendStatusSuccess(taskID int64)

MockSendStatusSuccess registers a mock responder for POST /api/v1/client/tasks/{id}/submit_status that returns HTTP 204 No Content. According to swagger.json, the endpoint is /api/v1/client/tasks/{id}/submit_status.

func MockSessionWithChannels

func MockSessionWithChannels(sessionName string) (*hashcat.Session, error)

MockSessionWithChannels is an alias for NewMockSession, retained for backward compatibility.

func MockSubmitErrorSuccess

func MockSubmitErrorSuccess(agentID int64)

MockSubmitErrorSuccess registers a mock responder for POST /api/v1/client/agents/{id}/submit_error that returns HTTP 204 No Content, matching the swagger.json contract for submit_error. Using 204 (no body) also avoids triggering error-handling logic that could cause infinite recursion.

func MockUpdateAgentSuccess

func MockUpdateAgentSuccess(agentID int64, agent api.Agent)

MockUpdateAgentSuccess registers mock responders for PUT /api/v1/client/agents/{id} (and POST/PATCH for compatibility) that returns a successful UpdateAgentResponse. According to swagger.json, the endpoint is /api/v1/client/agents/{id}.

func MockUpdateAgentWithCapture added in v0.6.2

func MockUpdateAgentWithCapture(agentID int64, capturedDevices *[]string)

MockUpdateAgentWithCapture registers mock responders for the update-agent endpoint that capture the Devices field from the request body into capturedDevices, then return a successful response. This allows tests to assert which device names were sent to the API.

func NewAPIError

func NewAPIError(statusCode int, message string) *api.APIError

NewAPIError creates a new APIError with the specified status code and message.

func NewMockSession

func NewMockSession(_ string) (*hashcat.Session, error)

NewMockSession creates a minimal hashcat.Session for testing without requiring the hashcat binary. It delegates to hashcat.NewTestSession to respect constructor invariants and avoid direct access to unexported fields. Cleanup is safe to call since no process or temporary files are created.

The sessionName parameter is unused; it exists so NewMockSession can be passed as a session factory callback matching the expected signature.

func NewSetTaskAbandonedError

func NewSetTaskAbandonedError(state string) *api.SetTaskAbandonedError

NewSetTaskAbandonedError creates a SetTaskAbandonedError for testing task abandonment scenarios.

func NewSetTaskAbandonedErrorWithErrorField

func NewSetTaskAbandonedErrorWithErrorField(errorMsg string) *api.SetTaskAbandonedError

NewSetTaskAbandonedErrorWithErrorField creates a SetTaskAbandonedError with empty Details but a populated Error_ field for testing fallback extraction.

func NewSetTaskAbandonedErrorWithNilError

func NewSetTaskAbandonedErrorWithNilError() *api.SetTaskAbandonedError

NewSetTaskAbandonedErrorWithNilError creates a SetTaskAbandonedError with empty Details and nil Error_ for testing edge case handling.

func NewTestAgent

func NewTestAgent(agentID int64, hostname string) api.Agent

NewTestAgent creates a test Agent object with the specified ID and hostname, including reasonable defaults for other fields (client_signature, operating_system, devices).

func NewTestAttack

func NewTestAttack(id int64, attackMode int) *api.Attack

NewTestAttack creates a test Attack object with the specified ID and attack mode, including mock resource files (word list, rule list, mask list) with download URLs.

func NewTestDeviceStatus

func NewTestDeviceStatus(deviceID int64, deviceType string) hashcat.StatusDevice

NewTestDeviceStatus creates a test StatusDevice with the specified ID and type.

func NewTestHashcatStatus

func NewTestHashcatStatus(sessionName string) hashcat.Status

NewTestHashcatStatus creates a sample hashcat.Status object with realistic values for all fields including devices, progress, and guess information. Note: The Guess field uses hashcat's internal statusGuess type which is not exported, so this function creates a Status with a zero-value Guess. For tests requiring Guess data, consider creating a helper in the hashcat package or using reflection.

func NewTestTask

func NewTestTask(id, attackID int64) *api.Task

NewTestTask creates a minimal valid Task object with the specified IDs and reasonable defaults for other fields. This will be used extensively across task-related tests.

func NewValidationAPIError

func NewValidationAPIError(message string) *api.APIError

NewValidationAPIError creates a new APIError with 422 Unprocessable Entity status, used as a test convenience for simulating validation errors.

func ResetTestState

func ResetTestState()

ResetTestState resets agentstate.State to zero values without cleanup. Useful for tests that need to reset state between subtests.

func SetupHTTPMock

func SetupHTTPMock() func()

SetupHTTPMock initializes httpmock, activates it, and returns a cleanup function. This ensures consistent setup/teardown across tests.

func SetupHTTPMockForClient

func SetupHTTPMockForClient(client *http.Client) func()

SetupHTTPMockForClient initializes httpmock for a custom http.Client and returns a cleanup function. This should be used when the API client uses a custom http.Client, or when ActivateNonDefault is needed instead of wrapping http.DefaultTransport.

func SetupMinimalTestState

func SetupMinimalTestState(agentID int64) func()

SetupMinimalTestState sets up minimal state (just AgentID and basic paths) for tests that don't need full initialization. It returns a cleanup function to remove the temporary directory and reset the updated state fields.

func SetupTestState

func SetupTestState(agentID int64, apiURL, apiToken string) func()

SetupTestState initializes agentstate.State with test values. It creates temporary directories for all path fields, sets up the API client, and returns a cleanup function that removes temporary directories and resets state.

func WithTestState

func WithTestState(agentID int64, apiURL, apiToken string, testFunc func())

WithTestState is a convenience wrapper that sets up state, runs the test function, and cleans up automatically.

Types

type TestAgentConfiguration

type TestAgentConfiguration struct {
	APIVersion                int                            `json:"api_version"`
	Config                    api.AdvancedAgentConfiguration `json:"config"`
	BenchmarksNeeded          bool                           `json:"benchmarks_needed"`
	RecommendedTimeouts       *TestRecommendedTimeouts       `json:"recommended_timeouts,omitempty"`
	RecommendedRetry          *TestRecommendedRetry          `json:"recommended_retry,omitempty"`
	RecommendedCircuitBreaker *TestRecommendedCircuitBreaker `json:"recommended_circuit_breaker,omitempty"`
}

TestAgentConfiguration represents the configuration response body for tests. It mirrors the structure returned by the GetConfiguration API endpoint.

func NewTestAgentConfiguration

func NewTestAgentConfiguration(useNativeHashcat bool) TestAgentConfiguration

NewTestAgentConfiguration creates a test agent configuration with specified settings.

type TestRecommendedCircuitBreaker added in v0.6.2

type TestRecommendedCircuitBreaker struct {
	FailureThreshold int `json:"failure_threshold"`
	Timeout          int `json:"timeout"`
}

TestRecommendedCircuitBreaker mirrors server-recommended circuit breaker settings for tests.

type TestRecommendedRetry added in v0.6.2

type TestRecommendedRetry struct {
	MaxAttempts  int `json:"max_attempts"`
	InitialDelay int `json:"initial_delay"`
	MaxDelay     int `json:"max_delay"`
}

TestRecommendedRetry mirrors server-recommended retry settings for tests.

type TestRecommendedTimeouts added in v0.6.2

type TestRecommendedTimeouts struct {
	ConnectTimeout int `json:"connect_timeout"`
	ReadTimeout    int `json:"read_timeout"`
	WriteTimeout   int `json:"write_timeout"`
	RequestTimeout int `json:"request_timeout"`
}

TestRecommendedTimeouts mirrors server-recommended timeout settings for tests.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL