### Create and Start Mock Servers Source: https://github.com/lamoda/gonkey/blob/master/README.md Initializes and starts mock servers for specified services. Ensure to defer the Shutdown call to release resources. ```go m := mocks.NewNop( "cart", "loyalty", "catalog", "madmin", "okz", "discounts", ) // spin up mocks err := m.Start() if err != nil { t.Fatal(err) } defer m.Shutdown() ``` -------------------------------- ### Create and Start Mock Servers Source: https://github.com/lamoda/gonkey/wiki/Mocks Initializes and starts multiple mock servers for different services. Ensure to defer the shutdown of mocks. ```go m := mocks.NewNop( "cart", "loyalty", "catalog", "madmin", "okz", "discounts", ) // spin up mocks err := m.Start() if err != nil { t.Fatal(err) } deferr m.Shutdown() ``` -------------------------------- ### Start ServiceMock Server Source: https://github.com/lamoda/gonkey/blob/master/_autodocs/mocks-api.md Starts the mock service on a random available loopback port. Use ServerAddr() to get the assigned address and log.Fatal to handle startup errors. ```go mock := mocks.NewServiceMock("api", definition) if err := mock.StartServer(); err != nil { log.Fatal(err) } addr := mock.ServerAddr() // e.g., "127.0.0.1:54321" ``` -------------------------------- ### Dockerfile for Running Gonkey Tests Source: https://github.com/lamoda/gonkey/blob/master/_autodocs/cli-configuration.md An example Dockerfile to set up an environment for running Gonkey tests. It installs Go, Gonkey, and prepares the working directory. ```dockerfile FROM golang:1.19-alpine RUN apk add --no-cache git WORKDIR /app COPY . . RUN go install github.com/lamoda/gonkey@latest ENTRYPOINT ["gonkey"] ``` -------------------------------- ### Start All Managed Mock Services Source: https://github.com/lamoda/gonkey/blob/master/_autodocs/mocks-api.md Starts all the mock services that have been added to the Mocks manager. If any service fails to start, an error is returned, and all successfully started services are shut down. ```go mocks := mocks.NewNop("service1", "service2") if err := mocks.Start(); err != nil { log.Fatal(err) } ``` -------------------------------- ### Basic CLI Runner Configuration Source: https://github.com/lamoda/gonkey/blob/master/_autodocs/runner-api.md Example of setting up and running the runner via CLI with a basic configuration and a file loader. ```go cfg := &runner.Config{ Host: "http://localhost:8080", } r := runner.New( cfg, yaml_file.NewLoader("./tests"), handler.HandleTest, ) runner.AddOutput(console_colored.NewOutput(true)) if err := runner.Run(); err != nil { log.Fatal(err) } ``` -------------------------------- ### Complete User Creation Test Example Source: https://github.com/lamoda/gonkey/blob/master/_autodocs/test-definition-schema.md A comprehensive example demonstrating a POST request to create a user, including fixtures, scripts, request/response definitions, database queries, and allure reporting. It also shows how to define test cases with different request arguments and expected response headers. ```yaml - name: Create user with orders description: "POST /users creates a user and validates database state" status: "" fixtures: - default_organizations beforeScript: path: "./scripts/setup_auth.sh" timeout: 3 method: POST path: /api/v1/users headers: Authorization: "Bearer {{ $auth_token }}" Content-Type: "application/json" request: | { "name": "{{ $name }}", "email": "{{ $email }}", "organization_id": {{ $org_id }} } response: 201: | { "id": "$matchRegexp([0-9]+)", "name": "{{ $name }}", "email": "{{ $email }}", "created_at": "$matchRegexp(\d{4}-\d{2}-\d{2})" } 400: | { "error": "Invalid input" } responseHeaders: 201: Content-Type: "application/json" Location: "{{ $location }}" variables_to_set: 201: user_id: "id" created_at: "created_at" dbQuery: > SELECT id, name, email FROM users WHERE id = {{ $user_id }} dbResponse: - '{"id":"{{ $user_id }}","name":"{{ $name }}","email":"{{ $email }}"}' comparisonParams: ignoreValues: false ignoreArraysOrdering: false disallowExtraFields: false allure: links: - name: "USER-123" url: "https://testit.example.com/projects/TEST/tests/123" type: "tms" labels: - name: "severity" value: "critical" - name: "feature" value: "user-creation" cases: - requestArgs: name: "John Doe" email: "john@example.com" org_id: "1" responseArgs: 201: location: "/api/v1/users/{{ $user_id }}" - requestArgs: name: "Jane Smith" email: "jane@example.com" org_id: "2" responseArgs: 201: location: "/api/v1/users/{{ $user_id }}" ``` -------------------------------- ### StartServer Source: https://github.com/lamoda/gonkey/blob/master/_autodocs/mocks-api.md Starts the mock service on a random loopback port. ```APIDOC ## StartServer ### Description Starts the mock service on a random loopback port. ### Signature ```go func (m *ServiceMock) StartServer() error ``` ### Returns - `error` - error if server fails to start ### Example ```go mock := mocks.NewServiceMock("api", definition) if err := mock.StartServer(); err != nil { log.Fatal(err) } addr := mock.ServerAddr() // e.g., "127.0.0.1:54321" ``` ``` -------------------------------- ### Start Source: https://github.com/lamoda/gonkey/blob/master/_autodocs/mocks-api.md Starts all managed mock services. If any service fails to start, all successfully started services are shut down. ```APIDOC ## Start ### Description Starts all managed mock services. ### Signature ```go func (m *Mocks) Start() error ``` ### Parameters None ### Returns - **`error`** - error if any service fails to start; all started services are shut down on failure ### Example ```go mocks := mocks.NewNop("service1", "service2") if err := mocks.Start(); err != nil { log.Fatal(err) } ``` ``` -------------------------------- ### Example Usage of RunWithTesting Source: https://github.com/lamoda/gonkey/blob/master/_autodocs/runner-api.md An example demonstrating how to use `RunWithTesting` within a Go test function. It sets up an HTTP test server, specifies the directory for test files, and includes mock services. ```go import ( "testing" "github.com/lamoda/gonkey/runner" ) func TestAPI(t *testing.T) { runner.RunWithTesting(t, &runner.RunWithTestingParams{ Server: httptest.NewServer(handler), TestsDir: "./tests", Mocks: mocks, }) } ``` -------------------------------- ### Example Usage of FixturesMultiDb Source: https://github.com/lamoda/gonkey/blob/master/_autodocs/types.md Illustrates how to initialize and populate a FixturesMultiDb collection, specifying fixture files for different databases. ```go f := models.FixturesMultiDb{ {DbName: "primary", Files: []string{"users"}}, {DbName: "replica", Files: []string{"users_read"}}, } ``` -------------------------------- ### Script with Templated Path Example Source: https://github.com/lamoda/gonkey/blob/master/_autodocs/test-definition-schema.md Shows a script path that uses templating to dynamically include environment variables. Useful for environment-specific setup. ```yaml beforeScript: path: "./scripts/setup_{{ .environment }}.sh" cases: - beforeScriptArgs: environment: "staging" ``` -------------------------------- ### End-to-End Test Example (Gonkey CLI) Source: https://github.com/lamoda/gonkey/blob/master/_autodocs/README.md Illustrates how to run end-to-end tests using the Gonkey command-line interface with specified parameters. ```bash gonkey -host production.example.com -tests ./e2e -v ``` -------------------------------- ### Examples of -tests Flag Usage Source: https://github.com/lamoda/gonkey/blob/master/_autodocs/cli-configuration.md Illustrates how to specify the path to test files or directories. ```bash -tests ./tests/api_tests.yaml -tests ./tests -tests /absolute/path/to/tests ``` ```bash # Single file gonkey -tests ./cases/users.yaml # Directory (all YAML files) gonkey -tests ./test_cases ``` -------------------------------- ### Mock Service Configuration Example Source: https://github.com/lamoda/gonkey/wiki/Mocks An example of configuring a single mock service with request constraints and a strategy. Parameters for the strategy are defined at the same nesting level. ```yaml ... mocks: service1: requestConstraints: - ... - ... strategy: strategyName strategyParam1: ... strategyParam2: ... ``` -------------------------------- ### StartServerWithAddr Source: https://github.com/lamoda/gonkey/blob/master/_autodocs/mocks-api.md Starts the mock service on a specific address. ```APIDOC ## StartServerWithAddr ### Description Starts the mock service on a specific address. ### Signature ```go func (m *ServiceMock) StartServerWithAddr(addr string) error ``` ### Parameters #### Path Parameters - **addr** (string) - Required - Address to bind to (e.g., "localhost:8090") ### Returns - `error` - error if server fails to start ### Example ```go if err := mock.StartServerWithAddr("127.0.0.1:8090"); err != nil { log.Fatal(err) } ``` ``` -------------------------------- ### Example: Load Fixture Data Source: https://github.com/lamoda/gonkey/blob/master/_autodocs/fixtures-api.md Demonstrates how to call the Load method to load multiple fixture files, such as 'users' and 'orders'. ```go loader.Load([]string{"users", "orders"}) // Loads: Location/users.yml and Location/orders.yml ``` -------------------------------- ### Runner Configuration with Mocks and Multiple Outputs Source: https://github.com/lamoda/gonkey/blob/master/_autodocs/runner-api.md Example showing how to configure the runner with mock services, custom variables, multiple output formats, and checkers. ```go mocks := mocks.NewNop("external-service", "analytics") if err := mocks.Start(); err != nil { log.Fatal(err) } defers mocks.Shutdown() cfg := &runner.Config{ Host: "http://localhost:8080", Mocks: mocks, Variables: variables.New(), } r := runner.New(cfg, yaml_file.NewLoader("./tests"), handler.HandleTest) r.AddOutput(console_colored.NewOutput(false)) r.AddOutput(allure_report.NewAllure2Output("./allure-results")) r.AddCheckers(response_body.NewChecker()) if err := r.Run(); err != nil { log.Fatal(err) } ``` -------------------------------- ### Examples of -host Flag Usage Source: https://github.com/lamoda/gonkey/blob/master/_autodocs/cli-configuration.md Demonstrates various valid formats for specifying the service hostname and port. ```bash -host localhost:8080 -host 192.168.1.1:3000 -host api.example.com -host https://api.example.com ``` ```bash # All equivalent: gonkey -host localhost:8080 gonkey -host http://localhost:8080 gonkey -host http://localhost:8080/ # Real service: gonkey -host https://api.example.com ``` -------------------------------- ### AllureLink Example Configuration Source: https://github.com/lamoda/gonkey/blob/master/_autodocs/types.md Provides an example of how to configure Allure links in a YAML file. This demonstrates setting TMS and issue links with their respective names, URLs, and types. ```yaml allure: links: - name: "PROJECT-456" url: "https://testit.example.com/projects/PROJECT/tests/456" type: "tms" - name: "JIRA-789" url: "https://jira.example.com/browse/JIRA-789" type: "issue" ``` -------------------------------- ### Redis Example Fixture File Source: https://github.com/lamoda/gonkey/blob/master/_autodocs/fixtures-api.md Example YAML structure for Redis fixtures, demonstrating templates, keys, sets, and hashes across multiple databases. ```yaml # fixtures/redis_data.yml templates: user_tmpl: - $name: basic_user values: email: "user@example.com" databases: 0: keys: values: user:1:name: "John" user:2:name: "Jane" sets: values: active_users: values: - "user:1" - "user:2" hashes: values: user:1:data: values: - key: "email" value: "john@example.com" ``` -------------------------------- ### Unit Test Example (Go) Source: https://github.com/lamoda/gonkey/blob/master/_autodocs/README.md Demonstrates a basic unit test structure in Go using the standard testing package. ```go func TestMyFunction(t *testing.T) { // Standard Go testing } ``` -------------------------------- ### Basic Gonkey Test Function Setup Source: https://github.com/lamoda/gonkey/blob/master/README.md Set up a basic test function in Go using Gonkey. This includes initializing mocks, the database, and the server. Configure Allure reporting via environment variables if needed. ```go package test import ( "testing" "github.com/lamoda/gonkey/fixtures" "github.com/lamoda/gonkey/mocks" "github.com/lamoda/gonkey/runner" ) func TestFuncCases(t *testing.T) { // init the mocks if needed (details below) // m := mocks.NewNop(...) // init the DB to load the fixtures if needed (details below) // db := ... // init Aerospike to load the fixtures if needed (details below) // aerospikeClient := ... // create a server instance of your app srv := server.NewServer() defer srv.Close() // Optional: configure Allure via environment variables // os.Setenv("GONKEY_ALLURE_DIR", "./allure-results") // directory for reports // os.Setenv("GONKEY_ALLURE_FORMAT", "v2") // format: v2 (JSON, default) or v1 (XML) // run test cases from your dir with Allure report generation runner.RunWithTesting(t, &runner.RunWithTestingParams{ Server: srv, TestsDir: "cases", Mocks: m, DB: db, Aerospike: runner.Aerospike{ Client: aerospikeClient, Namespace: "test", }, // Type of database, can be fixtures.Postgres, fixtures.Mysql, fixtures.CustomLoader // if DB parameter present, by default uses fixtures.Postgres database type DbType: fixtures.Postgres, FixturesDir: "fixtures", // Optional: TestIT integration - set default package and testClass labels for all tests // These can be overridden by individual test YAML definitions AllurePackage: "api", // e.g., "api", "cron", "consumer" AllureTestClass: "UserHandler", // e.g., handler or method name }) } ``` -------------------------------- ### Aerospike Example Fixture File Source: https://github.com/lamoda/gonkey/blob/master/_autodocs/fixtures-api.md Example YAML structure for Aerospike fixtures, defining data for 'users' and 'sessions' sets. ```yaml # fixtures/aerospike_data.yml sets: users: user:1: name: "John Doe" age: 30 active: true user:2: name: "Jane Doe" age: 25 active: true sessions: session:abc123: user_id: 1 created_at: 1609459200 ``` -------------------------------- ### API Integration Test Example (Gonkey) Source: https://github.com/lamoda/gonkey/blob/master/_autodocs/README.md Shows how to initiate an API integration test using Gonkey's RunWithTesting function. ```go func TestAPI(t *testing.T) { runner.RunWithTesting(t, &runner.RunWithTestingParams{...}) } ``` -------------------------------- ### Fixture Loading Example Source: https://github.com/lamoda/gonkey/blob/master/_autodocs/test-definition-schema.md Demonstrates how to load fixtures for a single database. Fixtures are pre-defined data sets used to set up test environments. ```yaml fixtures: - users - orders - products ``` -------------------------------- ### Redis Fixture File Example Source: https://github.com/lamoda/gonkey/blob/master/README.md Example of a YAML fixture file for Redis, demonstrating inheritance and definitions for various data structures like keys, sets, hashes, lists, and zsets. ```yaml inherits: - template1 - template2 - other_fixture templates: keys: - $name: parentKeyTemplate values: baseKey: expiration: 1s value: 1 - $name: childKeyTemplate $extend: parentKeyTemplate values: otherKey: value: 2 sets: - $name: parentSetTemplate expiration: 10s values: - value: a - $name: childSetTemplate $extend: parentSetTemplate values: - value: b hashes: - $name: parentHashTemplate values: - key: a value: 1 - key: b value: 2 - $name: childHashTemplate $extend: parentHashTemplate values: - key: c value: 3 - key: d value: 4 lists: - $name: parentListTemplate values: - value: 1 - value: 2 - $name: childListTemplate values: - value: 3 - value: 4 zsets: - $name: parentZSetTemplate values: - value: 1 score: 2.1 - value: 2 score: 4.3 - $name: childZSetTemplate value: - value: 3 score: 6.5 - value: 4 score: 8.7 databases: 1: keys: $extend: childKeyTemplate values: key1: value: value1 key2: expiration: 10s value: value2 sets: values: set1: $extend: childSetTemplate expiration: 10s values: - value: a - value: b set3: expiration: 5s values: - value: x - value: y hashes: values: map1: $extend: childHashTemplate values: - key: a value: 1 - key: b value: 2 map2: values: - key: c value: 3 - key: d value: 4 lists: values: list1: $extend: childListTemplate values: - value: 1 - value: 100 - value: 200 zsets: values: zset1: $extend: childZSetTemplate values: - value: 5 score: 10.1 2: keys: values: key3: value: value3 key4: expiration: 5s value: value4 ``` -------------------------------- ### Request Constraints Example Source: https://github.com/lamoda/gonkey/blob/master/_autodocs/mocks-api.md Example of defining request constraints in YAML, including method and JSON body matching. ```yaml mocks: payment: requestConstraints: - kind: methodIs method: POST - kind: bodyMatchesJSON body: | { "amount": 100, "currency": "USD" } strategy: constant body: '{"transactionId":"tx123"}' statusCode: 200 ``` -------------------------------- ### Start ServiceMock Server on Specific Address Source: https://github.com/lamoda/gonkey/blob/master/_autodocs/mocks-api.md Starts the mock service and binds it to a specific network address. This is useful for predictable testing environments. ```go if err := mock.StartServerWithAddr("127.0.0.1:8090"); err != nil { log.Fatal(err) } ``` -------------------------------- ### Multi-Database Fixture Loading Example Source: https://github.com/lamoda/gonkey/blob/master/_autodocs/test-definition-schema.md Shows how to load fixtures across multiple named databases. Useful for testing systems with distinct data stores. ```yaml fixturesMultiDb: - dbName: "primary" files: - users - orders - dbName: "analytics" files: - user_events ``` -------------------------------- ### Create ConstantReply Instance Source: https://github.com/lamoda/gonkey/blob/master/_autodocs/mocks-api.md Example of creating an instance of ConstantReply with specific status code, body, and headers. ```go reply := &mocks.ConstantReply{ StatusCode: 200, Body: `{"data":[]}`, Headers: map[string]string{"Content-Type": "application/json"}, } ``` -------------------------------- ### Database Validation Example (YAML) Source: https://github.com/lamoda/gonkey/blob/master/_autodocs/checkers-and-output.md Example demonstrating database validation using YAML. It includes a query to select user data and compares the result with an expected JSON structure. ```yaml - name: Create user and verify database method: POST path: /api/users request: '{"name":"John","email":"john@example.com"}' response: 201: '{"id":"$matchRegexp([0-9]+)","name":"John"}' dbQuery: > SELECT id, name, email FROM users WHERE email='john@example.com' dbResponse: - '{"id":1,"name":"John","email":"john@example.com"}' # Alternative: multiple queries per test dbChecks: - dbQuery: 'SELECT COUNT(*) as count FROM users' dbResponse: - '{"count":1}' - dbQuery: 'SELECT status FROM user_status WHERE user_id=1' dbResponse: - '{"status":"active"}' ``` -------------------------------- ### Basic Library Usage with Runner Source: https://github.com/lamoda/gonkey/blob/master/_autodocs/00-START-HERE.txt Demonstrates the basic setup for running Gonkey tests using its Go library API. This is suitable for integrating Gonkey into your Go test suites. ```go import "github.com/lamoda/gonkey/runner" runner.RunWithTesting(t, &runner.RunWithTestingParams{ Server: httptest.NewServer(handler), TestsDir: "./tests", }) ``` -------------------------------- ### Response Header Validation Example (YAML) Source: https://github.com/lamoda/gonkey/blob/master/_autodocs/checkers-and-output.md Example demonstrating how to configure response header validation using YAML. It specifies expected Content-Type, Cache-Control, and Set-Cookie headers. ```yaml - name: Check response headers method: GET path: /api/users response: '{"users":[]}' responseHeaders: 200: Content-Type: "application/json" Cache-Control: "no-store" Set-Cookie: "session=abc123" ``` -------------------------------- ### Configure Service with Mock Addresses Source: https://github.com/lamoda/gonkey/blob/master/README.md Configures a new server instance with addresses obtained from the started mock servers. This directs service requests to the mocks. ```go srv := server.NewServer(&server.Config{ CartAddr: m.Service("cart").ServerAddr(), LoyaltyAddr: m.Service("loyalty").ServerAddr(), CatalogAddr: m.Service("catalog").ServerAddr(), MadminAddr: m.Service("madmin").ServerAddr(), OkzAddr: m.Service("okz").ServerAddr(), DiscountsAddr: m.Service("discounts").ServerAddr(), }) defersrv.Close() ``` -------------------------------- ### Go Example for Multi-Database Fixtures Source: https://github.com/lamoda/gonkey/blob/master/_autodocs/types.md Illustrates how to define FixturesMultiDb for tests involving multiple databases, specifying fixtures for 'primary' and 'cache' databases. ```Go fixtures := models.FixturesMultiDb{ {DbName: "primary", Files: []string{"users", "orders"}}, {DbName: "cache", Files: []string{"sessions"}}, } ``` -------------------------------- ### Create and Run Mock Services with Gonkey Source: https://github.com/lamoda/gonkey/blob/master/_autodocs/mocks-api.md This Go code demonstrates how to create a mock service definition for an API endpoint, instantiate a service mock, start the mock manager, and retrieve the service address. It also shows how to check for errors after running tests. ```go package main import ( "log" "github.com/lamoda/gonkey/mocks" ) func main() { // Create mock services paymentDef := mocks.NewDefinition( "/api/pay", nil, &mocks.ConstantReply{ StatusCode: 200, Body: `{"status":"success"}`, }, mocks.CallsNoConstraint, ) paymentMock := mocks.NewServiceMock("payment", paymentDef) // Create manager and start m := mocks.New(paymentMock) if err := m.Start(); err != nil { log.Fatal(err) } defer m.Shutdown() // Get service address for configuration addr := m.Service("payment").ServerAddr() log.Printf("Payment mock running at: %s", addr) // Run tests... // Check for mock errors errs := m.EndRunningContext() if len(errs) > 0 { for _, err := range errs { log.Printf("Mock error: %v", err) } } } ``` -------------------------------- ### CLI Runner Configuration with All Features Source: https://github.com/lamoda/gonkey/blob/master/_autodocs/checkers-and-output.md Example of configuring the Gonkey runner for CLI usage, including adding multiple response body, header, and database checkers, along with console and Allure report outputs. ```go import ( "github.com/lamoda/gonkey/runner" "github.com/lamoda/gonkey/checker/response_body" "github.com/lamoda/gonkey/checker/response_header" "github.com/lamoda/gonkey/checker/response_db" "github.com/lamoda/gonkey/output/console_colored" "github.com/lamoda/gonkey/output/allure_report" ) runner := runner.New(config, loader, handler) // Add checkers runner.AddCheckers( response_body.NewChecker(), response_header.NewChecker(), response_db.NewChecker(db), ) // Add outputs runner.AddOutput(console_colored.NewOutput(verbose)) allure := allure_report.NewAllure2Output("./allure-results"). WithDefaultLabels("api", "UserHandler") deferrallure.Finalize() runner.AddOutput(allure) if err := runner.Run(); err != nil { log.Fatal(err) } ``` -------------------------------- ### Run Tests with PostgreSQL Fixtures Source: https://github.com/lamoda/gonkey/blob/master/_autodocs/README.md Execute tests using PostgreSQL fixtures for data setup. Requires a running PostgreSQL instance and a configured database. Ensure the fixtures directory is specified. ```go db, _ := sql.Open("postgres", "postgres://localhost/testdb") runner.RunWithTesting(t, &runner.RunWithTestingParams{ Server: httptest.NewServer(handler), TestsDir: "./tests", DB: db, DbType: fixtures.Postgres, FixturesDir: "./fixtures", }) ``` -------------------------------- ### Configure Service with Mock Addresses Source: https://github.com/lamoda/gonkey/wiki/Mocks Configures a server to use the addresses of the started mock servers. This ensures that service requests are directed to the mocks. ```go srv := server.NewServer(&server.Config{ CartAddr: m.Service("cart").ServerAddr(), LoyaltyAddr: m.Service("loyalty").ServerAddr(), CatalogAddr: m.Service("catalog").ServerAddr(), MadminAddr: m.Service("madmin").ServerAddr(), OkzAddr: m.Service("okz").ServerAddr(), DiscountsAddr: m.Service("discounts").ServerAddr(), }) deferr srv.Close() ``` -------------------------------- ### YAML Fixture Inheritance Example Source: https://github.com/lamoda/gonkey/blob/master/_autodocs/test-definition-schema.md Demonstrates how to define a base fixture and then inherit from it in another fixture file. Use this to share common test data structures and configurations. ```yaml # fixtures/base.yml templates: default_user: is_active: true created_at: $eval(NOW()) # fixtures/users.yml inherits: - base tables: users: - $name: admin_user $extend: default_user email: "admin@example.com" ``` -------------------------------- ### Run Gonkey Tests from CLI Source: https://github.com/lamoda/gonkey/blob/master/_autodocs/README.md Execute Gonkey tests directly from the command line. This example shows how to specify the host, test directory, fixtures, database type, DSN, and enable Allure reporting. ```bash gonkey \ -host http://localhost:8080 \ -tests ./test_cases \ -fixtures ./fixtures \ -db-type postgres \ -db_dsn "postgres://localhost/testdb" \ -allure \ -v ``` -------------------------------- ### Script Definition Example Source: https://github.com/lamoda/gonkey/blob/master/_autodocs/test-definition-schema.md Defines a script to be executed before an HTTP request, including its path and timeout. Supports templating for dynamic paths. ```yaml beforeScript: path: "./scripts/setup.sh" # Script file path timeout: 5 # Max seconds (default 3) ``` -------------------------------- ### Allure Reporting Setup in Go Source: https://github.com/lamoda/gonkey/blob/master/_autodocs/integration-patterns.md Configure Allure reporting by setting environment variables for the output directory and format. This enables integration with tools like TestIT. ```go package myapp_test import ( "os" "testing" "github.com/lamoda/gonkey/runner" ) func TestAPIWithAllure(t *testing.T) { // Set up Allure reporting via environment variables os.Setenv("GONKEY_ALLURE_DIR", "./allure-results") os.Setenv("GONKEY_ALLURE_FORMAT", "v2") runner.RunWithTesting(t, &runner.RunWithTestingParams{ Server: srv, TestsDir: "./testdata/cases", AllurePackage: "api", // TestIT: package label AllureTestClass: "UserController", // TestIT: test class label }) } ``` -------------------------------- ### Managing Complex Configurations with Shell Scripts Source: https://github.com/lamoda/gonkey/blob/master/_autodocs/cli-configuration.md Use shell scripts to manage complex Gonkey configurations by setting environment variables and passing them as arguments. This allows for flexible and dynamic setup of test environments. ```bash #!/bin/bash # run_tests.sh HOST="${API_HOST:-http://localhost:8080}" TESTS="${TESTS_DIR:-./tests}" DB_DSN="${DATABASE_URL}" FIXTURES="${FIXTURES_DIR:-./fixtures}" gonkey \ -host "$HOST" \ -tests "$TESTS" \ -db-type postgres \ -db_dsn "$DB_DSN" \ -fixtures "$FIXTURES" \ -allure-format v2 \ -v ``` ```bash API_HOST=api.example.com DB_DSN="postgres://..." ./run_tests.sh ``` -------------------------------- ### Get ServiceMock Server Address Source: https://github.com/lamoda/gonkey/blob/master/_autodocs/mocks-api.md Retrieves the network address (host:port) of the currently running mock server. Panics if the server has not been started. ```go addr := mock.ServerAddr() // "127.0.0.1:54321" url := fmt.Sprintf("http://%s/api", addr) ``` -------------------------------- ### Running Gonkey Tests with Docker Source: https://github.com/lamoda/gonkey/blob/master/_autodocs/cli-configuration.md Execute Gonkey tests within a Docker container, mounting local directories for tests and fixtures. This example demonstrates connecting to a host service running on the Docker host. ```bash docker run --rm \ -v $(pwd)/tests:/tests \ -v $(pwd)/fixtures:/fixtures \ gonkey \ -host http://host.docker.internal:8080 \ -tests /tests \ -fixtures /fixtures \ -db-type postgres \ -db_dsn "postgres://user:pass@db:5432/testdb" ``` -------------------------------- ### GitHub Actions CI/CD Integration Source: https://github.com/lamoda/gonkey/blob/master/_autodocs/cli-configuration.md Configure GitHub Actions to automatically run API tests using Gonkey on push or pull request events. This setup includes installing Gonkey, running tests against a local PostgreSQL service, and uploading Allure reports. ```yaml name: API Tests on: [push, pull_request] jobs: test: runs-on: ubuntu-latest services: postgres: image: postgres:14 env: POSTGRES_DB: testdb POSTGRES_PASSWORD: password steps: - uses: actions/checkout@v3 - uses: actions/setup-go@v4 - name: Install Gonkey run: go install github.com/lamoda/gonkey@latest - name: Run API Tests run: | gonkey \ -host http://localhost:8080 \ -tests ./tests \ -db-type postgres \ -db_dsn "postgres://postgres:password@localhost/testdb" \ -fixtures ./fixtures \ -allure-format v2 \ -v - name: Upload Allure Report if: always() uses: actions/upload-artifact@v3 with: name: allure-results path: ./allure-results ``` -------------------------------- ### Define HTTP Request and Response Structure in YAML Source: https://github.com/lamoda/gonkey/blob/master/README.md Example of how to define HTTP request parameters (method, path, headers, cookies) and response structures (body, headers) within a test configuration. ```yaml - method: "{{ $method }}" description: "{{ $description }}" path: "/some/path/{{ $pathPart }}" query: "{{ $query }}" headers: header1: "{{ $header }}" request: '{"reqParam": "{{ $reqParam }}"}' response: 200: "{{ $resp }}" mocks: server_mock: strategy: constant body: > { "message": "{{ $mockParam }}" } statusCode: 200 dbQuery: > SELECT id, name FROM testing_tools WHERE id={{ $sqlQueryParam }} dbResponse: - '{"id": {{ $sqlResultParam }}, "name": "gonkey"}' ``` -------------------------------- ### Match GET request query parameters Source: https://github.com/lamoda/gonkey/wiki/Mocks Verifies that the GET request parameters match the provided query string. The order of parameters does not matter, and only specified keys are checked. ```yaml ... mocks: service1: requestConstraints: # this check will demand that the request contains key1 и key2 # and the values are key1=value1, key1=value11 и key2=value2. # Keys not mentioned here are omitted while running the check. - kind: queryMatches expectedQuery: key1=value1&key2=value2&key1=value11 ... ``` -------------------------------- ### GET Request Test Scenario Source: https://github.com/lamoda/gonkey/blob/master/README.md Defines a test scenario for a GET request to retrieve a list of orders. Includes query parameters, fixtures, and a successful JSON response structure. ```yaml - name: WHEN the list of orders is requested MUST successfully response method: GET status: "" path: /jsonrpc/v2/order.getBriefList query: ?id=550e8400-e29b-41d4-a716-446655440000&jsonrpc=2.0&user_id=00001 fixtures: - order_0001 - order_0002 response: 200: | { "id": "550e8400-e29b-41d4-a716-446655440000", "jsonrpc": "2.0", "result": { "data": [ "ORDER0001", "ORDER0002" ], "meta": { "items": 0, "limit": 50, "page": 0, "pages": 0 } } } ``` -------------------------------- ### Create a New Runner Instance Source: https://github.com/lamoda/gonkey/blob/master/_autodocs/runner-api.md Initialize a new Runner with configuration, a test loader, and a test handler. Ensure the config specifies the target host. ```go import ( "github.com/lamoda/gonkey/runner" "github.com/lamoda/gonkey/testloader/yaml_file" ) cfg := &runner.Config{ Host: "http://localhost:8080", } r := runner.New( cfg, yaml_file.NewLoader("./tests"), someHandler, ) ``` -------------------------------- ### Redis Fixture Loader Initialization (Go) Source: https://github.com/lamoda/gonkey/blob/master/_autodocs/fixtures-api.md Initialize a Redis fixture loader with custom options. Requires fixture directory path and Redis client options. ```go import redisLoader "github.com/lamoda/gonkey/fixtures/redis" import redisClient "github.com/redis/go-redis/v9" opts, _ := redisClient.ParseURL("redis://localhost:6379/1") loader := redisLoader.New(redisLoader.LoaderOptions{ FixtureDir: "./fixtures", Redis: opts, }) ``` -------------------------------- ### Result Methods for Test Status Source: https://github.com/lamoda/gonkey/blob/master/_autodocs/types.md Provides methods to determine if a test passed and to get its status for reporting. ```go func (r *Result) Passed() bool ``` ```go func (r *Result) AllureStatus() (string, error) ``` -------------------------------- ### Library Usage with Go Testing Package Source: https://github.com/lamoda/gonkey/blob/master/_autodocs/runner-api.md Demonstrates how to integrate the runner with Go's built-in testing package for automated tests. ```go func TestAPI(t *testing.T) { runner.RunWithTesting(t, &runner.RunWithTestingParams{ Server: httptest.NewServer(httpHandler), TestsDir: "./test_cases", FixturesDir: "./fixtures", DB: dbConnection, DbType: fixtures.Postgres, AllurePackage: "api", AllureTestClass: "UserHandler", }) } ``` -------------------------------- ### methodIs Source: https://github.com/lamoda/gonkey/wiki/Mocks Verifies that the request method matches the specified HTTP method. Includes shortcuts for GET and POST. ```APIDOC ## methodIs ### Description Checks that the request method corresponds to the expected one. ### Parameters - `method` (mandatory) - string to compare the request method to. There are also 2 short variations that don't require `method` parameter: - `methodIsGET` - `methodIsPOST` ### Mock Configuration Example ```yaml ... mocks: service1: requestConstraints: - kind: methodIs method: PUT service2: requestConstraints: - kind: methodIsPOST ... ``` ``` -------------------------------- ### CLI Usage with Fixtures Source: https://github.com/lamoda/gonkey/blob/master/_autodocs/00-START-HERE.txt Illustrates how to run Gonkey tests from the CLI while specifying database connection details and fixture paths. This enables tests that rely on pre-populated database states. ```bash gonkey -host api.example.com -tests ./tests \ -db-type postgres \ -db_dsn "postgres://user:pass@localhost/testdb" \ -fixtures ./fixtures ``` -------------------------------- ### Get Brief List of Orders Source: https://github.com/lamoda/gonkey/blob/master/README.md Retrieves a brief list of orders. Supports query parameters for filtering and identification. ```APIDOC ## GET /jsonrpc/v2/order.getBriefList ### Description Retrieves a brief list of orders. Supports query parameters for filtering and identification. ### Method GET ### Endpoint /jsonrpc/v2/order.getBriefList ### Query Parameters - **id** (string) - Required - Unique identifier for the request. - **jsonrpc** (string) - Required - Specifies the JSON-RPC version. - **user_id** (string) - Required - Identifier for the user. ### Response #### Success Response (200) - **id** (string) - The request ID. - **jsonrpc** (string) - The JSON-RPC version. - **result** (object) - Contains the order data and metadata. - **data** (array) - A list of order identifiers. - **meta** (object) - Metadata about the pagination and limits. - **items** (integer) - Total number of items. - **limit** (integer) - The limit of items per page. - **page** (integer) - The current page number. - **pages** (integer) - The total number of pages. ### Response Example ```json { "id": "550e8400-e29b-41d4-a716-446655440000", "jsonrpc": "2.0", "result": { "data": [ "ORDER0001", "ORDER0002" ], "meta": { "items": 0, "limit": 50, "page": 0, "pages": 0 } } } ``` ``` -------------------------------- ### Typical Gonkey Project Structure Source: https://github.com/lamoda/gonkey/blob/master/_autodocs/README.md Illustrates a standard directory layout for a Gonkey project, including internal application code, test files, fixtures, and the go.mod file. ```text myproject/ ├── internal/ │ └── myapp/ │ └── handler.go ├── tests/ │ ├── cases/ │ │ ├── users.yaml │ │ ├── products.yaml │ │ └── orders.yaml │ ├── fixtures/ │ │ ├── users.yaml │ │ ├── products.yaml │ │ └── orders.yaml │ └── api_test.go └── go.mod ``` -------------------------------- ### queryMatches Source: https://github.com/lamoda/gonkey/wiki/Mocks Ensures that the GET request query parameters match a specified set of key-value pairs, ignoring parameter order. ```APIDOC ## queryMatches ### Description Checks that the GET request parameters correspond to the ones defined in the `query` parameter. ### Parameters - `expectedQuery` (mandatory) - a list of parameters to compare the parameter string to. The order of parameters is not important. ### Mock Configuration Example ```yaml ... mocks: service1: requestConstraints: # this check will demand that the request contains key1 и key2 # and the values are key1=value1, key1=value11 и key2=value2. # Keys not mentioned here are omitted while running the check. - kind: queryMatches expectedQuery: key1=value1&key2=value2&key1=value11 ... ``` ``` -------------------------------- ### Configure PostgreSQL Fixture Loader Source: https://github.com/lamoda/gonkey/blob/master/_autodocs/fixtures-api.md Set up the fixture loader for PostgreSQL databases. Ensure the database connection is established and the fixture configuration points to the correct directory. ```go import ( "database/sql" "github.com/lamoda/gonkey/runner" "github.com/lamoda/gonkey/fixtures" ) db, _ := sql.Open("postgres", "postgres://user:pass@localhost/testdb?sslmode=disable") fixtureLoader := fixtures.NewLoader(&fixtures.Config{ DB: db, DbType: fixtures.Postgres, Location: "./fixtures", Debug: os.Getenv("DEBUG") != "", }) runner.RunWithTesting(t, &runner.RunWithTestingParams{ Server: srv, TestsDir: "./tests", DB: db, FixturesDir: "./fixtures", DbType: fixtures.Postgres, }) ``` -------------------------------- ### Get Specific Order Source: https://github.com/lamoda/gonkey/blob/master/README.md Retrieves details for a specific order using its order number. Requires authentication via headers and cookies. ```APIDOC ## POST /jsonrpc/v2/order.getOrder ### Description Retrieves details for a specific order using its order number. Requires authentication via headers and cookies. ### Method POST ### Endpoint /jsonrpc/v2/order.getOrder ### Headers - **Authorization** (string) - Required - Bearer token for authentication. - **Content-Type** (string) - Required - Specifies the request body format as JSON. ### Cookies - **sid** (string) - Session ID. - **lid** (string) - Login ID. ### Request Body - **jsonrpc** (string) - Required - Specifies the JSON-RPC version. - **id** (string) - Required - Unique identifier for the request. - **method** (string) - Required - The method to call, 'order.getOrder'. - **params** (array) - Required - An array containing order details. - **order_nr** (string) - Required - The order number to retrieve. ### Request Example ```json { "jsonrpc": "2.0", "id": "550e8400-e29b-41d4-a716-446655440000", "method": "order.getOrder", "params": [ { "order_nr": {{ .orderNr }} } ] } ``` ### Response #### Success Response (200) - **id** (string) - The request ID. - **jsonrpc** (string) - The JSON-RPC version. - **result** (object) - Contains the order details. - **user_id** (string) - The ID of the user associated with the order. - **amount** (integer) - The total amount of the order. - **token** (string) - A token, matching the regex ^\\w{16}$. ### Response Example ```json { "id": "550e8400-e29b-41d4-a716-446655440000", "jsonrpc": "2.0", "result": { "user_id": {{ .userId }}, "amount": {{ .amount }}, "token": "$matchRegexp(^\\w{16}$)" } } ``` ### Response Headers (200) - **Content-Type** (string) - Specifies the response body format as JSON. - **Cache-Control** (string) - Cache directives. - **Set-Cookie** (string) - Cookies to be set by the client. ``` -------------------------------- ### Library Usage with Testing Framework Source: https://github.com/lamoda/gonkey/blob/master/_autodocs/checkers-and-output.md Demonstrates how to use Gonkey within a Go testing framework (`testing.T`) for API testing, specifying server, test directory, database connection, and checkers. ```go import ( "testing" "github.com/lamoda/gonkey/runner" "github.com/lamoda/gonkey/checker/response_db" ) func TestAPI(t *testing.T) { runner.RunWithTesting(t, &runner.RunWithTestingParams{ Server: srv, TestsDir: "./tests", DB: db, DbType: fixtures.Postgres, Checkers: []checker.CheckerInterface{ response_db.NewChecker(db), }, }) } ``` -------------------------------- ### Match request method Source: https://github.com/lamoda/gonkey/wiki/Mocks Checks if the request method matches the specified value. Provides specific shortcuts for GET and POST methods. ```yaml ... mocks: service1: requestConstraints: - kind: methodIs method: PUT service2: requestConstraints: - kind: methodIsPOST ... ``` -------------------------------- ### Create a Mock Definition Source: https://github.com/lamoda/gonkey/blob/master/_autodocs/mocks-api.md Create a new mock definition specifying the request path, constraints, response strategy, and call count. ```go def := mocks.NewDefinition( "/api/status", []mocks.Verifier{}, mocks.NewConstantReply(200, `{"ok":true}`, nil), mocks.CallsNoConstraint, ) ``` -------------------------------- ### Check Gonkey Host and Port Source: https://github.com/lamoda/gonkey/blob/master/_autodocs/cli-configuration.md If you encounter a 'connection refused' error, verify that the Gonkey service is running and that the hostname and port are correctly specified. ```bash gonkey -host http://localhost:8080 ... ``` -------------------------------- ### Create Fixture Loader Source: https://github.com/lamoda/gonkey/blob/master/_autodocs/fixtures-api.md Creates a new fixture loader instance for a specified database. Requires a configuration object including database connection, type, and location. ```go import ( "database/sql" "github.com/lamoda/gonkey/fixtures" ) db, _ := sql.Open("postgres", "...") loader := fixtures.NewLoader(&fixtures.Config{ DB: db, DbType: fixtures.Postgres, Location: "./fixtures", Debug: true, }) ``` -------------------------------- ### Single Database Query Example Source: https://github.com/lamoda/gonkey/blob/master/_autodocs/test-definition-schema.md Specifies a SQL query to execute after an HTTP request and its expected results. Use for verifying data changes or state. ```yaml dbQuery: | SELECT id, name, email FROM users WHERE created_at > NOW() - INTERVAL 1 DAY dbResponse: - '{"id":123,"name":"John","email":"john@example.com"}' - '{"id":124,"name":"Jane","email":"jane@example.com"}' ```