You are viewing documentation for version 3 of the AWS SDK for Ruby. Version 2 documentation can be found here.

Module: Aws::ClientStubs

Included in:
ACM::Client, ACMPCA::Client, APIGateway::Client, AlexaForBusiness::Client, AppStream::Client, AppSync::Client, ApplicationAutoScaling::Client, ApplicationDiscoveryService::Client, Athena::Client, AutoScaling::Client, AutoScalingPlans::Client, Batch::Client, Budgets::Client, Aws::Cloud9::Client, Aws::CloudDirectory::Client, Aws::CloudFormation::Client, Aws::CloudFront::Client, Aws::CloudHSM::Client, Aws::CloudHSMV2::Client, Aws::CloudSearch::Client, Aws::CloudSearchDomain::Client, Aws::CloudTrail::Client, Aws::CloudWatch::Client, Aws::CloudWatchEvents::Client, Aws::CloudWatchLogs::Client, Aws::CodeBuild::Client, Aws::CodeCommit::Client, Aws::CodeDeploy::Client, Aws::CodePipeline::Client, Aws::CodeStar::Client, Aws::CognitoIdentity::Client, Aws::CognitoIdentityProvider::Client, Aws::CognitoSync::Client, Aws::Comprehend::Client, Aws::ConfigService::Client, Aws::Connect::Client, Aws::CostExplorer::Client, Aws::CostandUsageReportService::Client, DAX::Client, DLM::Client, DataPipeline::Client, DatabaseMigrationService::Client, DeviceFarm::Client, DirectConnect::Client, DirectoryService::Client, DynamoDB::Client, DynamoDBStreams::Client, EC2::Client, ECR::Client, ECS::Client, EFS::Client, EKS::Client, EMR::Client, ElastiCache::Client, ElasticBeanstalk::Client, ElasticLoadBalancing::Client, ElasticLoadBalancingV2::Client, ElasticTranscoder::Client, ElasticsearchService::Client, FMS::Client, Firehose::Client, GameLift::Client, Glacier::Client, Glue::Client, Greengrass::Client, GuardDuty::Client, Health::Client, IAM::Client, ImportExport::Client, Inspector::Client, IoT1ClickDevicesService::Client, IoT1ClickProjects::Client, IoT::Client, IoTAnalytics::Client, IoTDataPlane::Client, IoTJobsDataPlane::Client, KMS::Client, Kinesis::Client, KinesisAnalytics::Client, KinesisVideo::Client, KinesisVideoArchivedMedia::Client, KinesisVideoMedia::Client, Lambda::Client, LambdaPreview::Client, Lex::Client, LexModelBuildingService::Client, LexRuntimeService::Client, Lightsail::Client, MQ::Client, MTurk::Client, MachineLearning::Client, Macie::Client, MarketplaceCommerceAnalytics::Client, MarketplaceEntitlementService::Client, MarketplaceMetering::Client, MediaConvert::Client, MediaLive::Client, MediaPackage::Client, MediaStore::Client, MediaStoreData::Client, MediaTailor::Client, MigrationHub::Client, Mobile::Client, Neptune::Client, OpsWorks::Client, OpsWorksCM::Client, Organizations::Client, PI::Client, Pinpoint::Client, Polly::Client, Pricing::Client, RDS::Client, Redshift::Client, Rekognition::Client, ResourceGroups::Client, ResourceGroupsTaggingAPI::Client, Route53::Client, Route53Domains::Client, S3::Client, SES::Client, SFN::Client, SMS::Client, SNS::Client, SQS::Client, SSM::Client, STS::Client, SWF::Client, SageMaker::Client, SageMakerRuntime::Client, SecretsManager::Client, ServerlessApplicationRepository::Client, ServiceCatalog::Client, ServiceDiscovery::Client, Shield::Client, Signer::Client, SimpleDB::Client, Snowball::Client, States::Client, StorageGateway::Client, Support::Client, TranscribeService::Client, Translate::Client, WAF::Client, WAFRegional::Client, WorkDocs::Client, WorkMail::Client, WorkSpaces::Client, XRay::Client
Defined in:
gems/aws-sdk-core/lib/aws-sdk-core/client_stubs.rb

Overview

This module provides the ability to specify the data and/or errors to return when a client is using stubbed responses. Pass :stub_responses => true to a client constructor to enable this behavior.

Also allows you to see the requests made by the client by reading the api_requests instance variable

Instance Method Summary collapse

Instance Method Details

#api_requests(options = {}) ⇒ Array

Allows you to access all of the requests that the stubbed client has made

Returns:

  • (Array)

    Returns an array of the api requests made, each request object contains the :operation_name, :params, and :context of the request.

Raises:

  • (NotImplementedError)

    Raises NotImplementedError when the client is not stubbed



192
193
194
195
196
197
198
199
200
201
202
203
204
# File 'gems/aws-sdk-core/lib/aws-sdk-core/client_stubs.rb', line 192

def api_requests(options = {})
  if config.stub_responses
    if options[:exclude_presign]
      @api_requests.reject {|req| req[:context][:presigned_url] }
    else
      @api_requests
    end
  else
    msg = 'This method is only implemented for stubbed clients, and is '
    msg << 'available when you enable stubbing in the constructor with `stub_responses: true`'
    raise NotImplementedError.new(msg)
  end
end

#stub_data(operation_name, data = {}) ⇒ Structure

Generates and returns stubbed response data from the named operation.

s3 = Aws::S3::Client.new
s3.stub_data(:list_buckets)
#=> #<struct Aws::S3::Types::ListBucketsOutput buckets=[], owner=#<struct Aws::S3::Types::Owner display_name="DisplayName", id="ID">>

In addition to generating default stubs, you can provide data to apply to the response stub.

s3.stub_data(:list_buckets, buckets:[{name:'aws-sdk'}])
#=> #<struct Aws::S3::Types::ListBucketsOutput
  buckets=[#<struct Aws::S3::Types::Bucket name="aws-sdk", creation_date=nil>],
  owner=#<struct Aws::S3::Types::Owner display_name="DisplayName", id="ID">>

Parameters:

  • operation_name (Symbol)
  • data (Hash) (defaults to: {})

Returns:

  • (Structure)

    Returns a stubbed response data structure. The actual class returned will depend on the given operation_name.



224
225
226
# File 'gems/aws-sdk-core/lib/aws-sdk-core/client_stubs.rb', line 224

def stub_data(operation_name, data = {})
  Stubbing::StubData.new(config.api.operation(operation_name)).stub(data)
end

#stub_responses(operation_name, *stubs) ⇒ void

This method returns an undefined value.

Configures what data / errors should be returned from the named operation when response stubbing is enabled.

Basic usage

When you enable response stubbing, the client will generate fake responses and will not make any HTTP requests.

client = Aws::S3::Client.new(stub_responses: true)
client.list_buckets
#=> #<struct Aws::S3::Types::ListBucketsOutput buckets=[], owner=nil>

You can provide stub data that will be returned by the client.

# stub data in the constructor
client = Aws::S3::Client.new(stub_responses: {
  list_buckets: { buckets: [{name: 'my-bucket' }] },
  get_object: { body: 'data' },
})

client.list_buckets.buckets.map(&:name) #=> ['my-bucket']
client.get_object(bucket:'name', key:'key').body.read #=> 'data'

You can also specify the stub data using #stub_responses

client = Aws::S3::Client.new(stub_responses: true)
client.stub_responses(:list_buckets, {
  buckets: [{ name: 'my-bucket' }]
})

client.list_buckets.buckets.map(&:name)
#=> ['my-bucket']

With a Resource class #stub_responses on the corresponding client:

s3 = Aws::S3::Resource.new(stub_responses: true)
s3.client.stub_responses(:list_buckets, {
  buckets: [{ name: 'my-bucket' }]
})

s3.buckets.map(&:name)
#=> ['my-bucket']

Lastly, default stubs can be configured via Aws.config:

Aws.config[:s3] = {
  stub_responses: {
    list_buckets: { buckets: [{name: 'my-bucket' }] }
  }
}

Aws::S3::Client.new.list_buckets.buckets.map(&:name)
#=> ['my-bucket']

Aws::S3::Resource.new.buckets.map(&:name)
#=> ['my-bucket']

Dynamic Stubbing

In addition to creating static stubs, it's also possible to generate stubs dynamically based on the parameters with which operations were called, by passing a Proc object:

s3 = Aws::S3::Resource.new(stub_responses: true)
s3.client.stub_responses(:put_object, -> (context) {
  s3.client.stub_responses(:get_object, content_type: context.params[:content_type])
})

The yielded object is an instance of Seahorse::Client::RequestContext.

Stubbing Errors

When stubbing is enabled, the SDK will default to generate fake responses with placeholder values. You can override the data returned. You can also specify errors it should raise.

# simulate service errors, give the error code
client.stub_responses(:get_object, 'NotFound')
client.get_object(bucket:'aws-sdk', key:'foo')
#=> raises Aws::S3::Errors::NotFound

# to simulate other errors, give the error class, you must
# be able to construct an instance with `.new`
client.stub_responses(:get_object, Timeout::Error)
client.get_object(bucket:'aws-sdk', key:'foo')
#=> raises new Timeout::Error

# or you can give an instance of an error class
client.stub_responses(:get_object, RuntimeError.new('custom message'))
client.get_object(bucket:'aws-sdk', key:'foo')
#=> raises the given runtime error object

Stubbing HTTP Responses

As an alternative to providing the response data, you can provide an HTTP response.

client.stub_responses(:get_object, {
  status_code: 200,
  headers: { 'header-name' => 'header-value' },
  body: "...",
})

To stub a HTTP response, pass a Hash with all three of the following keys set:

  • :status_code - - The HTTP status code
  • :headers - Hash<String,String> - A hash of HTTP header keys and values
  • :body - <String,IO> - The HTTP response body.

Stubbing Multiple Responses

Calling an operation multiple times will return similar responses. You can configure multiple stubs and they will be returned in sequence.

client.stub_responses(:head_object, [
  'NotFound',
  { content_length: 150 },
])

client.head_object(bucket:'aws-sdk', key:'foo')
#=> raises Aws::S3::Errors::NotFound

resp = client.head_object(bucket:'aws-sdk', key:'foo')
resp.content_length #=> 150

Parameters:

  • operation_name (Symbol)
  • stubs (Mixed)

    One or more responses to return from the named operation.

Raises:

  • (RuntimeError)

    Raises a runtime error when called on a client that has not enabled response stubbing via :stub_responses => true.



175
176
177
178
179
180
181
182
183
# File 'gems/aws-sdk-core/lib/aws-sdk-core/client_stubs.rb', line 175

def stub_responses(operation_name, *stubs)
  if config.stub_responses
    apply_stubs(operation_name, stubs.flatten)
  else
    msg = 'stubbing is not enabled; enable stubbing in the constructor '
    msg << 'with `:stub_responses => true`'
    raise msg
  end
end