Guides

Generating Mocks

Generating Mocks

Introduction

In the Mock APIs section, you learned the basic approach to managing dependencies by simulating endpoints and services in Python. With Mock Generation, you can save time and effort by automatically generating the mocks you need with full control over mocking logic.

Generate Command

With the skyramp mocker generate command, you can swiftly generate mock code with customized parameters. Use flags to tailor mock generation, specifying fields such as the API specification, service alias, port, output language, and endpoint path. Here's an example of generating mocks for a REST service:

skyramp mocker generate rest \
    --alias my-service \
    --api-schema openapi.yaml \
    --port 443 \
    --language python \
    --path

This command creates a Python file (typically mocks.py) containing code to mock the specified service.

Example Output File (mocks.py)

The generated file initializes endpoints, defines response constants, and provides functions to apply negative values to JSON payload fields:

import skyramp

# Initialize Endpoint(s)
artists_endpoint = skyramp.RestEndpoint(
    name="my-service",
    port=443,
    rest_path="/artists"
)

# Create JSON Payload Constants
artists_POST_response = r'''{
  "id": 1,
  "name": "John Doe"
}'''

# Define Response Values
artists_POST_response_value = skyramp.ResponseValue(
    name="artists_POST",
    method_name="POST",
    endpoint_descriptor=artists_endpoint,
    blob=artists_POST_response
)

# Define functions to apply negative values for different fields in the JSON payload
# Each function creates a skyramp MockObject with specific overrides 
def apply_negative_artists_POST_invalid_id():
    return skyramp.MockObject(
        name="negative_artists_POST_invalid_id",
        response_value=artists_POST_response_value,
        blob_override={"id": "abcdefg"}
    )
    ...
# (Functions omitted for brevity)

# Define a generator function to yield all negative test cases
def getAllArtistsPOST():
    ...

# Define a function to apply a mock object to a Kubernetes namespace or Docker address
def applyMock(namespace=None, address=None, mock_object: skyramp.MockObject=None):
    ...

Note: The use of skyramp mocker generate rest here is an example of how to generate mocks for a REST service and endpoint. Subcommands for mocker generate are available to perform across protocols (gRPC, JSON-RPC, etc.). For more details on available subcommands and their usage, refer to the mocker generate command documentation.

This structured mock code empowers you to efficiently mock service responses for the specified API endpoint /artists. Customize mock generation parameters to fit your testing needs, ensuring flexibility and productivity in your testing workflow.

© 2024 Skyramp, Inc. All rights reserved.

© 2024 Skyramp, Inc. All rights reserved.

© 2024 Skyramp, Inc. All rights reserved.