### Environment Setup with CDK8s and Helm Charts Source: https://smartcontractkit.github.io/chainlink-testing-framework/print.html Example of setting up a testing environment by adding a CDK8s deployment part and Helm charts for Ethereum and Chainlink. Ensure necessary imports are present. ```go package main import ( "github.com/smartcontractkit/chainlink-testing-framework/k8s/environment" "github.com/smartcontractkit/chainlink-testing-framework/k8s/examples/deployment_part_cdk8s" "github.com/smartcontractkit/chainlink-testing-framework/k8s/pkg/helm/chainlink" "github.com/smartcontractkit/chainlink-testing-framework/k8s/pkg/helm/ethereum" ) func main() { env := &environment.Config{ NamespacePrefix: "adding-new-deployment-part", TTL: 3 * time.Hour, KeepConnection: true, RemoveOnInterrupt: true, } addHardcodedLabelsToEnv(env) e := environment.New(env). AddChart(deployment_part_cdk8s.New(&deployment_part_cdk8s.Props{})). AddHelm(ethereum.New(nil)). AddHelm(chainlink.New(0, map[string]any{ "replicas": 2, })) if err := e.Run(); err != nil { panic(err) } e.Shutdown() } ``` -------------------------------- ### Run Simple Kubernetes Environment (Re-run) Source: https://smartcontractkit.github.io/chainlink-testing-framework/lib.html Re-runs the simple Chainlink environment setup in Kubernetes. This command is identical to a previous example. ```bash go run k8s/examples/simple/env.go ``` -------------------------------- ### Start Ethereum Network (Proof-of-Work/Authority) Source: https://smartcontractkit.github.io/chainlink-testing-framework/print.html Initiates a basic Ethereum network using the default configuration for a Proof-of-Work or Proof-of-Authority setup. If no version is specified, it defaults to Ethereum 1.0 (pre-Merge). ```go builder := NewEthereumNetworkBuilder() cfg, err := builder. WithExecutionLayer(types.ExecutionLayer_Nethermind). Build() if err != nil { panic(err) } net, rpcs, err := cfg.Start() if err != nil { panic(err) } ``` -------------------------------- ### WSVirtualUser Setup Implementation Source: https://smartcontractkit.github.io/chainlink-testing-framework/libs/wasp/stateful_test.html Implements the Setup method for the WSVirtualUser struct. This method establishes a connection to the WebSocket server and handles potential connection errors. ```go func (m *WSVirtualUser) Setup(l *wasp.Generator) error { var err error m.conn, _, err = websocket.Dial(context.Background(), m.target, &websocket.DialOptions{}) if err != nil { l.Log.Error().Err(err).Msg("failed to connect from vu") _ = m.conn.Close(websocket.StatusInternalError, "") return err } return nil } ``` -------------------------------- ### Start Nix Shell Source: https://smartcontractkit.github.io/chainlink-testing-framework/lib.html Starts a reliable development environment using Nix. This ensures consistent behavior locally and in CI. Requires Nix to be installed. ```bash make nix_shell ``` -------------------------------- ### Install Taskfile Source: https://smartcontractkit.github.io/chainlink-testing-framework/framework/components/mocking.html Install Taskfile, a utility for managing development tasks, using Homebrew. ```bash brew install go-task ``` -------------------------------- ### Initialize and Create a Chaos Experiment with Havoc Source: https://smartcontractkit.github.io/chainlink-testing-framework/print.html This example demonstrates the basic workflow for creating a chaos experiment using the 'havoc' package. It involves defining chaos object options, initializing the experiment with NewChaos, and then calling Create to start it. ```go package main import ( "context" . "github.com/smartcontractkit/chainlink-testing-framework/pkg/chaos" . "github.com/smartcontractkit/chainlink-testing-framework/pkg/logger" ) func main() { ctx := context.Background() // Initialize logger log := New() // zerolog.Logger // Define chaos experiment options chaosOpts := []ChaosOption{ WithChaosMesh(), // Use Chaos Mesh provider WithExperimentName("my-chaos-experiment"), WithExperimentNamespace("default"), } // Initialize a new chaos experiment experiment, err := NewChaos(ctx, log, chaosOpts...) if err != nil { log.Fatal().Err(err).Msg("Failed to initialize chaos experiment") } // Create and start the chaos experiment err = experiment.Create(ctx) if err != nil { log.Fatal().Err(err).Msg("Failed to create chaos experiment") } log.Info().Msg("Chaos experiment created successfully") // ... (further actions with the experiment, e.g., wait for completion, delete) // Example: Clean up the experiment (optional, depending on your test) // defer experiment.Delete(ctx) } ``` -------------------------------- ### Start Observability Stack Source: https://smartcontractkit.github.io/chainlink-testing-framework/framework/observability-victoria/observability_stack_victoria.html Starts the observability stack including Grafana, OTEL Collector, VictoriaMetrics, and VictoriaLogs. Use this for initial setup or when experimenting with metrics and logs. ```bash ctf obs up -vm ``` -------------------------------- ### Setup and Test EVM Storage API Source: https://smartcontractkit.github.io/chainlink-testing-framework/framework/fork_storage.html Navigates to the evm_storage directory, sets up the environment, runs tests for the Layout API, and tears down the environment. ```bash cd framework/evm_storage ./setup.sh go test -v -run TestLayoutAPI ./teardown.sh ``` -------------------------------- ### WASP TestVirtualUser Example Source: https://smartcontractkit.github.io/chainlink-testing-framework/libs/wasp/stateful_test.html An example test function demonstrating how to use WASP to test a WebSocket server. It includes starting a mock server, creating a generator with specific configurations, and running the generator. ```go func TestVirtualUser(t *testing.T) { // start mock WebSocket server s := httptest.NewServer(wasp.MockWSServer{ Sleep: 50 * time.Millisecond, }) defer s.Close() time.Sleep(1 * time.Second) // some parts omitted for brevity // create generator gen, err := wasp.NewGenerator(&wasp.Config{ LoadType: wasp.VU, // plain line profile - 5 VUs for 60s Schedule: wasp.Plain(5, 60*time.Second), VU: NewExampleVirtualUser(url), Labels: labels, LokiConfig: wasp.NewEnvLokiConfig(), }) if err != nil { panic(err) } // run the generator and wait until it finishes gen.Run(true) } ``` -------------------------------- ### Aptos Smoke Test Example Source: https://smartcontractkit.github.io/chainlink-testing-framework/framework/components/blockchains/aptos.html A Go test case demonstrating Aptos smoke testing. It loads configuration, initializes the blockchain network, and performs a basic HTTP GET request to check for transactions. ```go package examples import ( "github.com/go-resty/resty/v2" "github.com/smartcontractkit/chainlink-testing-framework/framework" "github.com/smartcontractkit/chainlink-testing-framework/framework/components/blockchain" "github.com/stretchr/testify/require" "testing" ) type CfgAptos struct { BlockchainA *blockchain.Input `toml:"blockchain_a" validate:"required"` } func TestAptosSmoke(t *testing.T) { in, err := framework.Load[CfgAptos](t) require.NoError(t, err) bc, err := blockchain.NewBlockchainNetwork(in.BlockchainA) require.NoError(t, err) // execute any additional commands, to deploy contracts or set up // network is already funded, here are the keys _ = blockchain.DefaultAptosAccount _ = blockchain.DefaultAptosPrivateKey _, err = framework.ExecContainer(bc.ContainerName, []string{"ls", "-lah"}) require.NoError(t, err) t.Run("test something", func(t *testing.T) { // use internal URL to connect Chainlink nodes _ = bc.Nodes[0].InternalHTTPUrl // use host URL to interact _ = bc.Nodes[0].ExternalHTTPUrl r := resty.New().SetBaseURL(bc.Nodes[0].ExternalHTTPUrl).EnableTrace() _, err := r.R().Get("/v1/transactions") require.NoError(t, err) }) } ``` -------------------------------- ### NewDeploymentPart Implementation Example Source: https://smartcontractkit.github.io/chainlink-testing-framework/print.html Provides an example of how to implement a new deployment part by creating a Chart struct that embeds HelmProps and Props. It includes a constructor function `New` and a `GetLabels` method to assign a specific label for the component. ```go func New(props *Props) environment.ConnectedChart { if props == nil { props = defaultProps() } return Chart{ HelmProps: &HelmProps{ Name: "sol", Path: "chainlink-qa/solana-validator", // ./local_path/chartdir will work too Values: &props.Values, }, Props: props, } } func (m NewDeploymentPart) GetLabels() map[string]string { return map[string]string{ "chain.link/component": "new-deployment-part", } } ``` -------------------------------- ### Start an Ethereum 2.0 (PoS) Network Source: https://smartcontractkit.github.io/chainlink-testing-framework/lib/docker/blockchain_nodes.html Configures and starts an Ethereum 2.0 Proof-of-Stake network. This process involves additional containers and may take longer than starting a 1.0 network. ```go builder := NewEthereumNetworkBuilder() cfg, err := builder. WithEthereumVersion(config_types.EthereumVersion_Eth2). WithExecutionLayer(config_types.ExecutionLayer_Geth). Build() if err != nil { panic(err) } net, rpcs, err := cfg.Start() if err != nil { panic(err) } ``` -------------------------------- ### Start Postgres Database Container Source: https://smartcontractkit.github.io/chainlink-testing-framework/print.html Initializes and starts a PostgreSQL database container using the testing framework. Specifies network, database name, and image version. The container must be started before interaction. ```go pg, err := test_env.NewPostgresDb( []string{network.Name}, test_env.WithPostgresDbName("jd-db"), test_env.WithPostgresImageVersion("14.1")) if err != nil { panic(err) } err = pg.StartContainer() if err != nil { panic(err) } ``` -------------------------------- ### Start a new Postgres DB instance Source: https://smartcontractkit.github.io/chainlink-testing-framework/lib/docker/chainlink_ecosystem.html Use this snippet to initialize and start a new Postgres database container for JD. It allows specifying network, database name, and image version. ```go pg, err := test_env.NewPostgresDb( []string{network.Name}, test_env.WithPostgresDbName("jd-db"), test_env.WithPostgresImageVersion("14.1")) if err != nil { panic(err) } er r = pg.StartContainer() if err != nil { panic(err) } ``` -------------------------------- ### TOML Configuration Example Source: https://smartcontractkit.github.io/chainlink-testing-framework/framework/test_configuration_overrides.html Example of a TOML configuration file for custom settings. Use comments to describe the purpose of fields and `validate` tags in your Go struct for validation. ```toml # My custom config does X [MyCustomConfig] # Can be a number a = 1 # Can be Y or Z b = "Z" ``` -------------------------------- ### Start VictoriaMetrics + OTEL Stack Source: https://smartcontractkit.github.io/chainlink-testing-framework/libs/wasp/how-to/start_local_observability_stack.html Starts the VictoriaMetrics + OTEL observability stack using the 'just' command. This stack includes Grafana, VictoriaMetrics, VictoriaLogs, and OTEL. After starting, you can run tests and then stop the stack. ```bash just victoria-up # from "wasp" directory cd examples/profiles && WASP_LOG_SEND_METHOD=otel go test -v -run TestNodeMixed && cd - just victoria-down ``` -------------------------------- ### Start a new Job Distributor instance Source: https://smartcontractkit.github.io/chainlink-testing-framework/lib/docker/chainlink_ecosystem.html This snippet shows how to instantiate and start a Job Distributor (JD) container. It requires the database URL from the running Postgres instance and allows specifying the JD image and version. ```go jd := New([]string{network.Name}, //replace with actual image WithImage("localhost:5001/jd"), WithVersion("latest"), WithDBURL(pg.InternalURL.String()), ) er r = jd.StartContainer() if err != nil { panic(err) } ``` -------------------------------- ### Start Full Observability Stack Source: https://smartcontractkit.github.io/chainlink-testing-framework/framework/observability/observability_stack.html Use this command to start the full local observability stack, which includes additional services like Cadvisor, Tempo, Pyroscope, and PostgreSQL exporters. ```bash ctf obs up -f ``` -------------------------------- ### Starting Local Test Networks Source: https://smartcontractkit.github.io/chainlink-testing-framework/print.html Commands to start local Ethereum test networks using Anvil or Geth. These are prerequisites for running various test suites. ```bash make AnvilSync make GethSync ``` -------------------------------- ### Install Pre-commit Hooks Source: https://smartcontractkit.github.io/chainlink-testing-framework/monorepo-tools.html Installs the necessary pre-commit hooks for the project using the Just build system. This should be run before committing code. ```bash just install ``` -------------------------------- ### Start Kubernetes Chaos Playground Source: https://smartcontractkit.github.io/chainlink-testing-framework/framework/chaos/chaos.html Initiates the Kubernetes chaos playground using Docker. This is the recommended first step for running Kubernetes tests. ```bash cd infra/chaosmesh-playground devbox run up k9s ``` -------------------------------- ### Deploying and Managing Test Environments Source: https://smartcontractkit.github.io/chainlink-testing-framework/print.html This Go code demonstrates how to initialize a test environment, add various Chainlink-related Helm charts and CDK8s charts, deploy them, copy files into a pod, and then deploy additional services. It also includes error handling and environment shutdown. ```go package main import ( "fmt" "github.com/smartcontractkit/chainlink-testing-framework/k8s/environment" "github.com/smartcontractkit/chainlink-testing-framework/k8s/pkg/cdk8s/blockscout" "github.com/smartcontractkit/chainlink-testing-framework/k8s/pkg/helm/chainlink" "github.com/smartcontractkit/chainlink-testing-framework/k8s/pkg/helm/ethereum" "github.com/smartcontractkit/chainlink-testing-framework/k8s/pkg/helm/mockserver" mockservercfg "github.com/smartcontractkit/chainlink-testing-framework/k8s/pkg/helm/mockserver-cfg" ) func main() { envConfig := &environment.Config{ Labels: []string{"chain.link/product=myProduct", "chain.link/team=my-team", "chain.link/cost-center=test-tooling-load-test"}, WorkloadLabels: map[string]string{"chain.link/product": "myProduct", "chain.link/team": "my-team", "chain.link/cost-center": "test-tooling-load-test"}, PodLabels: map[string]string{"chain.link/product": "myProduct", "chain.link/team": "my-team", "chain.link/cost-center": "test-tooling-load-test"} } e := environment.New(envConfig) err := e. AddChart(blockscout.New(&blockscout.Props{})). // you can also add cdk8s charts if you like Go code AddHelm(ethereum.New(nil)). AddHelm(chainlink.New(0, nil)). Run() if err != nil { panic(err) } // do some other stuff with deployed charts pl, err := e.Client.ListPods(e.Cfg.Namespace, "app=chainlink-0") if err != nil { panic(err) } dstPath := fmt.Sprintf("%s/%s:/", e.Cfg.Namespace, pl.Items[0].Name) if _, _, _, err = e.Client.CopyToPod(e.Cfg.Namespace, "./examples/multistage/someData.txt", dstPath, "node"); err != nil { panic(err) } // deploy another part err = e. AddHelm(mockservercfg.New(nil)). AddHelm(mockserver.New(nil)). Run() defer func() { errr := e.Shutdown() panic(errr) }() if err != nil { panic(err) } } ``` -------------------------------- ### Initialize and Test TRON Network in Go Source: https://smartcontractkit.github.io/chainlink-testing-framework/print.html This Go example demonstrates how to load TRON network configuration, initialize a TRON blockchain network using the framework, and access node URLs. It also shows how to access funded private keys. ```Go __ package examples import ( "github.com/smartcontractkit/chainlink-testing-framework/framework" "github.com/smartcontractkit/chainlink-testing-framework/framework/components/blockchain" "github.com/stretchr/testify/require" "testing" ) type CfgTron struct { BlockchainA *blockchain.Input `toml:"blockchain_a" validate:"required"` } func TestTRONSmoke(t *testing.T) { in, err := framework.Load[CfgTron](t) require.NoError(t, err) bc, err := blockchain.NewBlockchainNetwork(in.BlockchainA) require.NoError(t, err) // all private keys are funded _ = blockchain.TRONAccounts.PrivateKeys[0] t.Run("test something", func(t *testing.T) { // use internal URL to connect Chainlink nodes _ = bc.Nodes[0].InternalHTTPUrl // use host URL to interact _ = bc.Nodes[0].ExternalHTTPUrl // use bc.Nodes[0].ExternalHTTPUrl + "/wallet" to access full node // use bc.Nodes[0].ExternalHTTPUrl + "/walletsolidity" to access Solidity node }) } ``` -------------------------------- ### VirtualUser Request Example Source: https://smartcontractkit.github.io/chainlink-testing-framework/libs/wasp/profile_test.html Defines a method for a VirtualUser to make an HTTP GET request and report success or failure. It uses a predefined constant for response grouping. ```go // represents user login func (m *VirtualUser) requestOne(l *wasp.Generator) { var result map[string]interface{} r, err := m.client.R(). SetResult(&result). Get(m.target) if err != nil { l.Responses.Err(r, GroupAuth, err) return } l.Responses.OK(r, GroupAuth) } ``` -------------------------------- ### Initializing and Querying Loki Client Source: https://smartcontractkit.github.io/chainlink-testing-framework/lib.html Demonstrates how to initialize a Loki client with basic authentication and query parameters, then retrieve log entries. Ensure environment variables for authentication are set. ```go auth := LokiBasicAuth{ Username: os.Getenv("LOKI_LOGIN"), Password: os.Getenv("LOKI_PASSWORD"), } queryParams := LokiQueryParams{ Query: `{namespace="test"} |= "test"`, StartTime: time.Now().AddDate(0, 0, -1), EndTime: time.Now(), Limit: 100, } lokiClient := NewLokiClient("https://loki.api.url", "my-tenant", auth, queryParams) logEntries, err := lokiClient.QueryLogs(context.Background()) ``` -------------------------------- ### VirtualUser Request Example Source: https://smartcontractkit.github.io/chainlink-testing-framework/print.html Represents a user login request within a VirtualUser. It sends an HTTP GET request to a target URL and handles success or error responses. ```go func (m *VirtualUser) requestOne(l *wasp.Generator) { var result map[string]interface{} r, err := m.client.R(). SetResult(&result). Get(m.target) if err != nil { l.Responses.Err(r, GroupAuth, err) return } l.Responses.OK(r, GroupAuth) } ``` -------------------------------- ### Integrate goc and Dummy Service in Environment Source: https://smartcontractkit.github.io/chainlink-testing-framework/print.html This Go code demonstrates how to set up a testing environment that includes goc for coverage and a dummy HTTP service. It initializes the environment, adds the necessary charts, runs the services, saves coverage, and then clears it. ```go package main import ( "time" "github.com/smartcontractkit/chainlink-testing-framework/k8s/environment" goc "github.com/smartcontractkit/chainlink-testing-framework/k8s/pkg/cdk8s/goc" dummy "github.com/smartcontractkit/chainlink-testing-framework/k8s/pkg/cdk8s/http_dummy" ) func main() { envConfig := &environment.Config{} addHardcodedLabelsToEnv(envConfig) e := environment.New(envConfig). AddChart(goc.New()). AddChart(dummy.New()) if err := e.Run(); err != nil { panic(err) } // run your test logic here time.Sleep(1 * time.Minute) if err := e.SaveCoverage(); err != nil { panic(err) } // clear the coverage, rerun the tests again if needed if err := e.ClearCoverage(); err != nil { panic(err) } } ``` -------------------------------- ### Get TRON Account Information Source: https://smartcontractkit.github.io/chainlink-testing-framework/framework/components/blockchains/tron.html Example cURL command to retrieve account information from a TRON Solidity node using its API. Requires the account's address. ```curl curl -X POST http://127.0.0.1:9090/walletsolidity/getaccount -d '{"address": "41E552F6487585C2B58BC2C9BB4492BC1F17132CD0"}' ``` -------------------------------- ### Initialize MockServer Client Source: https://smartcontractkit.github.io/chainlink-testing-framework/lib/client/mockserver.html Demonstrates three ways to initialize the MockServer client: by providing an environment, a URL, or a custom configuration. Initialization with an environment is most common. ```go var myk8sEnv *environment.Environment // ... create k8s environment k8sMockserver := ConnectMockServer(myk8sEnv) mockServerUrl := "http://my.mockserver.instance.io" myMockServer := ConnectMockServerURL(mockServerUrl) customConfig := &MockserverConfig{ LocalURL: mockServerUrl, ClusterURL: mockServerUrl, Headers: map[string]string{"x-secret-auth-header": "such-a-necessary-auth-header"}, } myCustomMockServerClient := NewMockserverClient(customConfig) ``` -------------------------------- ### Create and Run a Simple Kubernetes Environment Source: https://smartcontractkit.github.io/chainlink-testing-framework/print.html Initializes and runs a new Kubernetes environment using Helm charts for Ethereum and Chainlink. Ensure to set appropriate labels for internal reporting. ```go package main import ( "fmt" "github.com/smartcontractkit/chainlink-testing-framework/k8s/environment" "github.com/smartcontractkit/chainlink-testing-framework/k8s/pkg" "github.com/smartcontractkit/chainlink-testing-framework/k8s/pkg/helm/chainlink" "github.com/smartcontractkit/chainlink-testing-framework/k8s/pkg/helm/ethereum" "github.com/smartcontractkit/chainlink-testing-framework/k8s/pkg/helm/mockserver" ) func addHardcodedLabelsToEnv(env *environment.Config) { env.Labels = []string{"chain.link/product=myProduct", "chain.link/team=my-team", "chain.link/cost-center=test-tooling-load-test"} env.WorkloadLabels = map[string]string{"chain.link/product": "myProduct", "chain.link/team": "my-team", "chain.link/cost-center": "test-tooling-load-test"} env.PodLabels = map[string]string{"chain.link/product": "myProduct", "chain.link/team": "my-team", "chain.link/cost-center": "test-tooling-load-test"} } func main() { env := &environment.Config{ NamespacePrefix: "new-environment", KeepConnection: false, RemoveOnInterrupt: false, } addHardcodedLabelsToEnv(env) err := environment.New(env). AddHelm(ethereum.New(nil)). AddHelm(chainlink.New(0, nil)). Run() if err != nil { panic(err) } } ``` -------------------------------- ### Run and Dump Logs for a Kubernetes Environment Source: https://smartcontractkit.github.io/chainlink-testing-framework/print.html This snippet demonstrates how to initialize a Kubernetes environment, add Ethereum and Chainlink Helm charts, run the environment, and dump the logs to a specified directory. Use this when you need to capture detailed logs from your test environment. ```go package main import ( "github.com/smartcontractkit/chainlink-testing-framework/k8s/environment" "github.com/smartcontractkit/chainlink-testing-framework/k8s/pkg/helm/chainlink" "github.com/smartcontractkit/chainlink-testing-framework/k8s/pkg/helm/ethereum" ) func main() { env := &environment.Config{} addHardcodedLabelsToEnv(env) e := environment.New(env). AddHelm(ethereum.New(nil)). AddHelm(chainlink.New(0, nil)) if err := e.Run(); err != nil { panic(err) } if err := e.DumpLogs("logs/mytest"); err != nil { panic(err) } } ``` -------------------------------- ### Getting Network Stats for a Defined Network Source: https://smartcontractkit.github.io/chainlink-testing-framework/print.html Retrieve network statistics for a predefined network using the `stats` command. Use `-s` for the start block and `-e` for the end block, or a negative number for the last N blocks. ```bash seth -n MyCustomNetwork stats -s -10 ``` ```bash seth -n MyCustomNetwork stats -s A -e B ``` -------------------------------- ### Initialize and Run Environment with Helm Charts Source: https://smartcontractkit.github.io/chainlink-testing-framework/print.html This snippet demonstrates initializing a new Kubernetes environment with default Ethereum and Chainlink Helm charts. It configures environment settings like namespace prefix and cleanup behavior. The environment is then run, and any errors are panicked. ```go package main import ( "github.com/smartcontractkit/chainlink-testing-framework/k8s/environment" "github.com/smartcontractkit/chainlink-testing-framework/k8s/pkg/helm/chainlink" "github.com/smartcontractkit/chainlink-testing-framework/k8s/pkg/helm/ethereum" ) func main() { env := &environment.Config{ NamespacePrefix: "new-environment", KeepConnection: true, RemoveOnInterrupt: true, } addHardcodedLabelsToEnv(env) err := environment.New(env). AddHelm(ethereum.New(nil)). AddHelm(chainlink.New(0, nil)). Run() if err != nil { panic(err) } } ``` -------------------------------- ### Get TRON Account Information via HTTP API Source: https://smartcontractkit.github.io/chainlink-testing-framework/print.html This example demonstrates how to retrieve TRON account information using the TRON Solidity node's HTTP API. The default port for the Solidity node is 9090. ```Shell __ curl -X POST http://127.0.0.1:9090/walletsolidity/getaccount -d '{"address": "41E552F6487585C2B58BC2C9BB4492BC1F17132CD0"}' ``` -------------------------------- ### Set MockServer Expectations for a 200 OK Response Source: https://smartcontractkit.github.io/chainlink-testing-framework/lib/client/mockserver.html Use `PutExpectations` to define mocked responses. The body must be a JSON string conforming to MockServer's format, including a request matcher and response action. This example sets up a simple GET request to '/status' that returns a 200 OK with a JSON body. ```go var myk8sEnv *environment.Environment returnOk := `{ "httpRequest": { "method": "GET", "path": "/status" }, "httpResponse": { "statusCode": 200, "body": { "message": "Service is running" } } }` ms := ConnectMockServer(myk8sEnv) err := ms.PutExpectations(returnOk) if err != nil { panic(err) } ``` -------------------------------- ### Create and Use GitHub Client Source: https://smartcontractkit.github.io/chainlink-testing-framework/print.html Demonstrates how to create instances of the GitHub client for both public and private repositories. Use `WITHOUT_TOKEN` for public repositories and a personal access token for private ones. ```go publicRepoClient := NewGithubClient(WITHOUT_TOKEN) // "smartcontractkit", "chainlink" latestCLReleases, err := publicRepoClient.ListLatestCLCoreReleases(10) if err != nil { panic(err) } // "smartcontractkit", "chainlink" latestCLTags, err := publicRepoClient.ListLatestCLCoreTags(10) if err != nil { panic(err) } privateRepoClient := NewGithubClient("my-secret-PAT") myLatestReleases, err := privateRepoClient.ListLatestReleases("my-org", "my-private-repo", 5) if err != nil { panic(err) } ``` -------------------------------- ### Running Go Test Suite Source: https://smartcontractkit.github.io/chainlink-testing-framework/print.html Instructions for running the framework's end-to-end tests locally. Assumes Geth is running in a separate terminal and the test suite is located in the 'examples' directory. ```bash make GethSync cd examples go test -v ``` -------------------------------- ### Install ghsecrets Tool Source: https://smartcontractkit.github.io/chainlink-testing-framework/lib/config/config.html Install the `ghsecrets` tool using `go install`. This tool helps manage GitHub Secrets more efficiently. ```bash go install github.com/smartcontractkit/chainlink-testing-framework/tools/ghsecrets@latest ``` -------------------------------- ### Start LGTM Stack Source: https://smartcontractkit.github.io/chainlink-testing-framework/libs/wasp/how-to/start_local_observability_stack.html Starts the LGTM observability stack using the 'just' command. After starting, you can run tests and then stop the stack. ```bash just lgtm-up # from "wasp" directory cd examples/profiles && WASP_LOG_SEND_METHOD=loki go test -v -run TestNodeMixed && cd - just lgtm-down ``` -------------------------------- ### Environment Configuration Setup Source: https://smartcontractkit.github.io/chainlink-testing-framework/print.html Sets up the base environment configuration, including Time-To-Live (TTL) for the namespace, a namespace prefix for uniqueness, and prevents pod eviction. Configures labels for namespaces, workloads, and pods. ```go baseEnvironmentConfig := &environment.Config{ TTL: time.Hour * 2, NamespacePrefix: "my-namespace-prefix", Test: t, PreventPodEviction: true, Labels: nsLabels, WorkloadLabels: workloadPodLabels, PodLabels: workloadPodLabels, } ``` -------------------------------- ### Instantiate Loki Client with Basic Auth Source: https://smartcontractkit.github.io/chainlink-testing-framework/lib/client/loki.html Create a new Loki client instance providing the Loki URL, tenant ID, basic authentication credentials, and query parameters including the LogQL query, start and end times, and a limit. ```go // scheme is required lokiUrl := "http://loki-host.io" // can be empty tenantId := "promtail" basicAuth := LokiBasicAuth{ Login: "admin", Password: "oh-so-secret", } queryParams := LokiQueryParams{ Query: "quantile_over_time(0.5, {name='my awesome app'} | json| unwrap duration [10s]) by name", StartTime: time.Now().Add(1 * time.Hour), EndTime: time.Now(), Limit: 1000, } lokiClient := client.NewLokiClient(lokiUrl, tenantId, basicAuth, queryParams) ``` -------------------------------- ### Setup Local Test Environment Source: https://smartcontractkit.github.io/chainlink-testing-framework/libs/seth.html Commands to set up and synchronize a local Ethereum test network using Geth or Anvil. Ensure your environment is ready for testing. ```bash make GethSync cd examples go test -v ``` ```bash make AnvilSync ``` ```bash make GethSync ``` -------------------------------- ### Initialize GitHub Clients Source: https://smartcontractkit.github.io/chainlink-testing-framework/lib/client/github.html Demonstrates how to initialize GitHub clients for public and private repositories. A token is required for private repositories. ```go publicRepoClient := NewGithubClient(WITHOUT_TOKEN) // "smartcontractkit", "chainlink" latestCLReleases, err := publicRepoClient.ListLatestCLCoreReleases(10) if err != nil { panic(err) } // "smartcontractkit", "chainlink" latestCLTags, err := publicRepoClient.ListLatestCLCoreTags(10) if err != nil { panic(err) } privateRepoClient := NewGithubClient("my-secret-PAT") myLatestReleases, err := privateRepoClient.ListLatestReleases("my-org", "my-private-repo", 5) if err != nil { panic(err) } ``` -------------------------------- ### Start Job Distributor Container Source: https://smartcontractkit.github.io/chainlink-testing-framework/print.html Initializes and starts a Job Distributor (JD) container. Requires the network name, image, version, and the internal URL of a running Postgres database. The container must be started before interaction. ```go jd := New([]string{network.Name}, //replace with actual image WithImage("localhost:5001/jd"), WithVersion("latest"), WithDBURL(pg.InternalURL.String()), ) err = jd.StartContainer() if err != nil { panic(err) } ``` -------------------------------- ### Install Dependencies Source: https://smartcontractkit.github.io/chainlink-testing-framework/lib.html Installs necessary dependencies for the project. Requires Node 14.x.x, helm, and yarn. ```bash make install_deps ``` -------------------------------- ### Start ChaosMesh Playground Source: https://smartcontractkit.github.io/chainlink-testing-framework/framework/chaos/debug-k8s.html Starts the ChaosMesh playground environment using DevBox. Ensure you are in the 'infra/chaosmesh-playground' directory. ```bash cd infra/chaosmesh-playground devbox run up ``` -------------------------------- ### Example Local .testsecrets File Source: https://smartcontractkit.github.io/chainlink-testing-framework/lib/config/config.html This is an example of a local `.testsecrets` file. Secrets should be set only as required for specific tests. ```dotenv E2E_TEST_CHAINLINK_IMAGE=qa_ecr_image_url E2E_TEST_CHAINLINK_UPGRADE_IMAGE=qa_ecr_image_url E2E_TEST_ARBITRUM_SEPOLIA_WALLET_KEY=wallet_key ``` -------------------------------- ### Sample TOML Configuration Source: https://smartcontractkit.github.io/chainlink-testing-framework/lib/config/config.html An example TOML file demonstrating how to configure network settings, including selected networks, EVM network details, fork configurations, RPC endpoints, and wallet keys. This serves as a template for defining test environments. ```toml __ selected_networks = ["arbitrum_goerli", "optimism_goerli", "new_network"] [EVMNetworks.new_network] evv_name = "new_test_network" evv_chain_id = 100009 evv_simulated = true evv_chainlink_transaction_limit = 5000 evv_minimum_confirmations = 1 evv_gas_estimation_buffer = 10000 client_implementation = "Ethereum" evv_supports_eip1559 = true evv_default_gas_limit = 6000000 [ForkConfigs.new_network] url = "ws://localhost:8546" block_number = 100 [RpcHttpUrls] arbitrum_goerli = ["https://devnet-2.mt/ABC/rpc/"] new_network = ["http://localhost:8545"] [RpcWsUrls] arbitrum_goerli = ["wss://devnet-2.mt/ABC/ws/"] new_network = ["ws://localhost:8546"] [WalletKeys] arbitrum_goerli = ["1810868fc221b9f50b5b3e0186d8a5f343f892e51ce12a9e818f936ec0b651ed"] optimism_goerli = ["1810868fc221b9f50b5b3e0186d8a5f343f892e51ce12a9e818f936ec0b651ed"] new_network = ["ac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80"] ``` -------------------------------- ### Start Simulated Backend with Funded Addresses Source: https://smartcontractkit.github.io/chainlink-testing-framework/libs/seth.html Initializes an in-memory simulated Ethereum backend with pre-funded accounts. A background goroutine commits blocks periodically. Ensure to call the cancel function to shut down the backend. ```go var startBackend := func(fundedAddresses []common.Address) (*simulated.Backend, context.CancelFunc) { toFund := make(map[common.Address]types.Account) for _, address := range fundedAddresses { toFund[address] = types.Account{ Balance: big.NewInt(1000000000000000000), // 1 Ether } } backend := simulated.NewBackend(toFund) ctx, cancelFn := context.WithCancel(context.Background()) // 100ms block time ticker := time.NewTicker(100 * time.Millisecond) go func() { for { select { case <-ticker.C: backend.Commit() case <-ctx.Done(): backend.Close() return } } }() return backend, cancelFn } // 0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266 is the default dev account backend, cancelFn := startBackend( []common.Address{common.HexToAddress("0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266")}, ) defer func() { cancelFn() }() client, err := builder. WithNetworkName("simulated"). WithEthClient(backend.Client()). WithPrivateKeys([]string{"ac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80"}). Build() require.NoError(t, err, "failed to build client") _ = client ``` -------------------------------- ### Creating a New Seth Client with Configuration Source: https://smartcontractkit.github.io/chainlink-testing-framework/libs/seth.html Initializes a new Seth client instance using a provided configuration object. Handles potential errors during client creation. ```Go seth, err := seth.NewClientWithConfig(cfg) if err != nil { log.Fatal(err) } ``` -------------------------------- ### Example Loki Error Message Source: https://smartcontractkit.github.io/chainlink-testing-framework/libs/wasp/how-to/debug_loki_errors.html This is an example of a malformed promtail log message error that may be encountered. It indicates issues with the format of logs being sent to Loki. ```text ERR Malformed promtail log message, skipping Line=["level",{},"component","client","host","...","msg","batch add err","tenant","","error",{}] ``` -------------------------------- ### Configure Environment with Labels Source: https://smartcontractkit.github.io/chainlink-testing-framework/print.html Sets up the environment configuration, including namespace and workload/pod labels, for a new Kubernetes deployment. ```go envConfig := &environment.Config{ Labels: nsLabels, WorkloadLabels: workloadPodLabels, PodLabels: workloadPodLabels, NamespacePrefix: "new-environment", } ``` -------------------------------- ### Start a Basic Ethereum Network Source: https://smartcontractkit.github.io/chainlink-testing-framework/lib/docker/blockchain_nodes.html Initiates a default Ethereum 1.0 network using the specified execution layer client. If no version is specified, it defaults to pre-Merge Ethereum. ```go builder := NewEthereumNetworkBuilder() cfg, err := builder. WithExecutionLayer(types.ExecutionLayer_Nethermind). Build() if err != nil { panic(err) } net, rpcs, err := cfg.Start() if err != nil { panic(err) } ``` -------------------------------- ### Start a Private Test Network Source: https://smartcontractkit.github.io/chainlink-testing-framework/lib.html Use this command to start a simulated private Ethereum network. It defaults to a single node running Geth and Prysm with chain ID 1337. ```bash go run docker/test_env/cmd/main.go start-test-env private-chain ``` -------------------------------- ### Display Help for Environment Generation Source: https://smartcontractkit.github.io/chainlink-testing-framework/framework/developer_environment/overview.html Use this command to see all available options for generating a new Chainlink environment. ```bash ctf gen -h ``` -------------------------------- ### Test Runner TOML Configuration Example Source: https://smartcontractkit.github.io/chainlink-testing-framework/k8s-test-runner/k8s-test-runner.html Example TOML configuration for the `k8s-test-runner`. Specifies namespace, image details, test execution parameters, resource requests/limits, and environment variables. ```toml namespace = "e2e-tests" rbac_role_name = "" # RBAC role name for the chart rbac_service_account_name = "" # RBAC service account name for the chart image_registry_url = "" # URL to the ECR containing the test binary image, e.g., staging ECR URL image_name = "k8s-test-runner" image_tag = "" # The image tag to use, like "mercury-load-tests" (see readme above) job_count = "1" test_name = "TestMercuryLoad/all_endpoints" test_timeout = "24h" test_config_base64_env_name = "LOAD_TEST_BASE64_TOML_CONTENT" test_config_file_path = "/Users/lukasz/Documents/test-configs/load-staging-testnet.toml" resources_requests_cpu = "1000m" resources_requests_memory = "512Mi" resources_limits_cpu = "2000m" resources_limits_memory = "1024Mi" [envs] WASP_LOG_LEVEL = "info" TEST_LOG_LEVEL = "info" MERCURY_TEST_LOG_LEVEL = "info" [metadata.labels] "chain.link/component" = "test-runner" "chain.link/product" = "" "chain.link/team" = "" "chain.link/cost-center" = "test-tooling--test" ``` -------------------------------- ### Network Statistics Output Example Source: https://smartcontractkit.github.io/chainlink-testing-framework/libs/seth.html Example output of network statistics, including TPS, block duration, gas usage, and base fees. Also shows recommended parameters for performance/chaos testing. ```json # Stats perc_95_tps = 8.0 perc_95_block_duration = '3s' perc_95_block_gas_used = 1305450 perc_95_block_gas_limit = 15000000 perc_95_block_base_fee = 25000000000 avg_tps = 2.433333333333333 avg_block_duration = '2s' avg_block_gas_used = 493233 avg_block_gas_limit = 15000000 avg_block_base_fee = 25000000000 # Recommended performance/chaos test parameters duration = '2m0s' block_gas_base_fee_initial_value = 25000000000 block_gas_base_fee_bump_percentage = '100.00% (no bump required)' block_gas_usage_percentage = '3.28822000% gas used (no congestion)' avg_tps = 3.0 max_tps = 8.0 ``` -------------------------------- ### Initialize and Run Test Environment Source: https://smartcontractkit.github.io/chainlink-testing-framework/lib/k8s_new/environments.html Initializes a new test environment and adds necessary Helm charts for blockchain nodes and Chainlink nodes. The environment is then run, and any errors are reported. ```go testEnv := environment.New(baseEnvironmentConfig). AddHelm(ethereum.New(ethProps)). // Blockchain node AddHelm(cd) // Chainlink nodes err = testEnv.Run() if err != nil { t.Fatal("Error running environment", err) } ``` -------------------------------- ### Create Docker Image for Test Binary Source: https://smartcontractkit.github.io/chainlink-testing-framework/k8s-test-runner/k8s-test-runner.html Compiles the test binary, creates a Docker image, and pushes it to the image registry. Provide the path to the test folder you wish to package. ```bash go run ./cmd/main.go create-test-image --image-registry-url --image-name "" --image-tag "" "" ``` -------------------------------- ### Install WASP Package Source: https://smartcontractkit.github.io/chainlink-testing-framework/print.html Add the WASP package to your Go project. Ensure you have a go.mod file in your project directory. ```go go get github.com/smartcontractkit/chainlink-testing-framework/wasp ```