helpers

package
v3.4.9 Latest Latest
Warning

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

Go to latest
Published: Feb 19, 2026 License: Apache-2.0 Imports: 21 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AuthHeaders

func AuthHeaders(requestID string) map[string]string

AuthHeaders returns default headers including Authorization and X-Request-Id. If TEST_AUTH_HEADER is set, its value is used for Authorization.

func AuthenticateFromEnv

func AuthenticateFromEnv() error

AuthenticateFromEnv obtains a Bearer token using env vars and exports TEST_AUTH_HEADER. Inputs via env:

TEST_AUTH_URL: OAuth token endpoint (e.g., https://auth.../v1/login/oauth/access_token)
TEST_AUTH_USERNAME: username
TEST_AUTH_PASSWORD: password

If TEST_AUTH_URL is empty, no-op. On success sets TEST_AUTH_HEADER to "Bearer <token>".

func ComposeDownBackend

func ComposeDownBackend() error

ComposeDownBackend stops services started with ComposeUpBackend.

func ComposeUpBackend

func ComposeUpBackend() error

ComposeUpBackend brings infra + onboarding + transaction online using root Makefile.

func CreateUSDAsset

func CreateUSDAsset(ctx context.Context, client *HTTPClient, orgID, ledgerID string, headers map[string]string) error

CreateUSDAsset posts a minimal USD asset to the onboarding API; ignores if already exists.

func DockerAction

func DockerAction(action, container string, extraArgs ...string) error

DockerAction performs a docker container action like stop/start/restart/pause/unpause.

func DockerExec

func DockerExec(container string, args ...string) (string, error)

DockerExec runs a command inside a running container and returns its combined output.

func DockerLogsSince

func DockerLogsSince(container, since string, tail int) (string, error)

DockerLogsSince returns docker logs for a container since the provided RFC3339 timestamp. If tail > 0, limits the number of lines returned.

func DockerNetwork

func DockerNetwork(action, network, container string) error

DockerNetwork connects or disconnects a container to/from a Docker network. action should be "connect" or "disconnect".

func EnableDefaultBalance

func EnableDefaultBalance(ctx context.Context, trans *HTTPClient, orgID, ledgerID, alias string, headers map[string]string) error

EnableDefaultBalance sets AllowSending/AllowReceiving to true on the default balance for an account alias.

func EnsureDefaultBalanceRecord

func EnsureDefaultBalanceRecord(ctx context.Context, trans *HTTPClient, orgID, ledgerID, accountID string, headers map[string]string) error

EnsureDefaultBalanceRecord waits until the default balance exists for the given account ID. It no longer attempts to create the default, as the system creates it asynchronously upon account creation.

func GetAvailableSumByAlias

func GetAvailableSumByAlias(ctx context.Context, trans *HTTPClient, orgID, ledgerID, alias, asset string, headers map[string]string) (decimal.Decimal, error)

GetAvailableSumByAlias returns the sum of Available across all balances for the given alias and asset code.

func OrgPayload

func OrgPayload(name, legalDocument string) map[string]any

OrgPayload returns a minimal valid organization payload including a valid country code.

func RandHex

func RandHex(n int) string

func RandString

func RandString(n int) string

func RestartWithWait

func RestartWithWait(container string, wait time.Duration) error

RestartWithWait restarts a container and waits a bit for it to come back.

func RunTestsWithAuth

func RunTestsWithAuth(m *testing.M)

RunTestsWithAuth authenticates using env (if configured) and runs tests, failing fast on auth errors. Usage in each package's TestMain:

func TestMain(m *testing.M) { helpers.RunTestsWithAuth(m) }

func SetupAccount

func SetupAccount(ctx context.Context, onboard *HTTPClient, headers map[string]string, orgID, ledgerID, alias, assetCode string) (string, error)

CreateAccount creates an account with alias and asset code (type=deposit) and returns its ID.

func SetupInflowTransaction

func SetupInflowTransaction(ctx context.Context, trans *HTTPClient, orgID, ledgerID, alias, assetCode, amount string, headers map[string]string) (int, []byte, error)

SetupInflow posts a simple inflow transaction to credit an alias with amount for a given asset code. Returns status code and body for assertion when needed.

func SetupLedger

func SetupLedger(ctx context.Context, onboard *HTTPClient, headers map[string]string, orgID, name string) (string, error)

CreateLedger creates a ledger under the given organization and returns its ID.

func SetupOrganization

func SetupOrganization(ctx context.Context, onboard *HTTPClient, headers map[string]string, name string) (string, error)

CreateOrganization creates an organization and returns its ID.

func StartLogCapture

func StartLogCapture(containers []string, testName string) func()

StartLogCapture marks a start timestamp and returns a function that writes docker logs for the given containers since that timestamp to ./reports/logs/<container>_<testName>.log. Intended for use within tests; paths are relative to the package CWD (e.g., tests/chaos).

func URLHostPort

func URLHostPort(raw string) (string, error)

URLHostPort extracts host:port from a base URL string. If no port is specified, it defaults based on scheme (https=443, http=80).

func WaitForAvailableSumByAlias

func WaitForAvailableSumByAlias(ctx context.Context, trans *HTTPClient, orgID, ledgerID, alias, asset string, headers map[string]string, expected decimal.Decimal, timeout time.Duration) (decimal.Decimal, error)

WaitForAvailableSumByAlias polls until the available sum for alias equals expected, or timeout.

func WaitForBalanceChange

func WaitForBalanceChange(ctx context.Context, client *HTTPClient, orgID, ledgerID, accountAlias, assetCode string, headers map[string]string, snapshot *BalanceSnapshot, expectedDelta decimal.Decimal, timeout time.Duration) (decimal.Decimal, error)

WaitForBalanceChange waits for the balance to change by the expected delta from a snapshot

func WaitForHTTP200

func WaitForHTTP200(fullURL string, timeout time.Duration) error

WaitForHTTP200 polls a URL until it returns HTTP 200 or timeout elapses.

func WaitForTCP

func WaitForTCP(hostPort string, timeout time.Duration) error

WaitForTCP waits until the given host:port is accepting connections or timeout elapses.

func WriteTextFile

func WriteTextFile(path string, content string) error

WriteTextFile ensures the directory exists and writes content to path, overwriting any existing file.

Types

type BalanceSnapshot

type BalanceSnapshot struct {
	Available decimal.Decimal
	Block     decimal.Decimal
	On_hold   decimal.Decimal
	Timestamp time.Time
}

BalanceSnapshot captures the state of an account balance at a point in time

func GetBalanceSnapshot

func GetBalanceSnapshot(ctx context.Context, client *HTTPClient, orgID, ledgerID, accountAlias, assetCode string, headers map[string]string) (*BalanceSnapshot, error)

GetBalanceSnapshot captures the current balance state for an account

type Environment

type Environment struct {
	OnboardingURL  string
	TransactionURL string
	ManageStack    bool // if true, tests may start/stop stack via Makefile
	HTTPTimeout    time.Duration
}

Environment holds base URLs for Midaz services and behavior flags.

func LoadEnvironment

func LoadEnvironment() Environment

LoadEnvironment loads environment configuration with sensible defaults matching the local docker-compose setup.

type HTTPClient

type HTTPClient struct {
	// contains filtered or unexported fields
}

HTTPClient wraps a standard http.Client with base URL handling.

func NewHTTPClient

func NewHTTPClient(base string, timeout time.Duration) *HTTPClient

NewHTTPClient constructs a client with given base URL and timeout.

func (*HTTPClient) PostDSL

func (c *HTTPClient) PostDSL(ctx context.Context, path string, headers map[string]string, dsl string) (int, []byte, http.Header, error)

PostDSL is a convenience for uploading a DSL file required by the DSL endpoint.

func (*HTTPClient) Request

func (c *HTTPClient) Request(ctx context.Context, method, path string, headers map[string]string, body any) (int, []byte, error)

Request executes an HTTP request with optional JSON body and returns status code and response body.

func (*HTTPClient) RequestFull

func (c *HTTPClient) RequestFull(ctx context.Context, method, path string, headers map[string]string, body any) (int, []byte, http.Header, error)

RequestFull executes an HTTP request and returns status, body, and headers.

func (*HTTPClient) RequestFullWithRetry

func (c *HTTPClient) RequestFullWithRetry(ctx context.Context, method, path string, headers map[string]string, body any, attempts int, baseBackoff time.Duration) (int, []byte, http.Header, error)

RequestFullWithRetry performs RequestFull with simple retry/backoff for transient statuses. Retries on 429, 502, 503, 504 or network errors up to attempts with exponential backoff.

func (*HTTPClient) RequestMultipart

func (c *HTTPClient) RequestMultipart(ctx context.Context, method, path string, headers map[string]string, fields map[string]string, files map[string]struct {
	Field, Filename string
	Content         []byte
}) (int, []byte, http.Header, error)

RequestMultipart sends a multipart/form-data request with optional text fields and file parts.

func (*HTTPClient) RequestRaw

func (c *HTTPClient) RequestRaw(ctx context.Context, method, path string, headers map[string]string, contentType string, raw []byte) (int, []byte, http.Header, error)

RequestRaw sends a request with an arbitrary raw body and explicit Content-Type.

func (*HTTPClient) RequestWithHeaderValues

func (c *HTTPClient) RequestWithHeaderValues(ctx context.Context, method, path string, headers map[string][]string, body any) (int, []byte, http.Header, error)

RequestWithHeaderValues executes an HTTP request with explicit header values including duplicates. The map value is a slice; each value is added using Header.Add in order. Content-Type is NOT auto-set.

type OperationTracker

type OperationTracker struct {
	OrgID           string
	LedgerID        string
	AccountAlias    string
	AssetCode       string
	Headers         map[string]string
	Client          *HTTPClient
	InitialSnapshot *BalanceSnapshot
}

TrackOperationBalance tracks balance changes during an operation

func NewOperationTracker

func NewOperationTracker(ctx context.Context, client *HTTPClient, orgID, ledgerID, accountAlias, assetCode string, headers map[string]string) (*OperationTracker, error)

NewOperationTracker creates a new operation tracker for an account

func (*OperationTracker) GetCurrentDelta

func (ot *OperationTracker) GetCurrentDelta(ctx context.Context) (decimal.Decimal, error)

GetCurrentDelta returns the current balance delta from the initial snapshot

func (*OperationTracker) VerifyDelta

func (ot *OperationTracker) VerifyDelta(ctx context.Context, expectedDelta decimal.Decimal, timeout time.Duration) (decimal.Decimal, error)

VerifyDelta verifies that the balance changed by the expected amount

type TestIsolation

type TestIsolation struct {
	// contains filtered or unexported fields
}

TestIsolation provides methods to ensure test data isolation

func NewTestIsolation

func NewTestIsolation() *TestIsolation

NewTestIsolation creates a new test isolation helper

func (*TestIsolation) MakeTestHeaders

func (ti *TestIsolation) MakeTestHeaders() map[string]string

MakeTestHeaders creates headers with a unique request ID for this test run

func (*TestIsolation) TestRunID

func (ti *TestIsolation) TestRunID() string

TestRunID returns the unique identifier for this test run

func (*TestIsolation) UniqueAccountAlias

func (ti *TestIsolation) UniqueAccountAlias(prefix string) string

UniqueAccountAlias generates a unique account alias for this test run

func (*TestIsolation) UniqueAssetCode

func (ti *TestIsolation) UniqueAssetCode(prefix string) string

UniqueAssetCode generates a unique asset code for this test run Asset codes are typically shorter, so we use a different pattern

func (*TestIsolation) UniqueLedgerName

func (ti *TestIsolation) UniqueLedgerName(prefix string) string

UniqueLedgerName generates a unique ledger name for this test run

func (*TestIsolation) UniqueOrgName

func (ti *TestIsolation) UniqueOrgName(prefix string) string

UniqueOrgName generates a unique organization name for this test run

func (*TestIsolation) UniqueTransactionCode

func (ti *TestIsolation) UniqueTransactionCode(prefix string) string

UniqueTransactionCode generates a unique transaction code

Jump to

Keyboard shortcuts

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