polka
polka

Reputation: 1529

Mocking boto3 Cloudwatch Log client

A Cloudwatch log is an object with Log Group > Log Stream > Log Events on AWS. I am trying to write tests for this, but the moto mocking raises a client error when applied to boto3.client('logs'). I am looking at other ways to mock the behavior of the log. How would you write a test for this function?

For example:

    client = boto3.client('logs')
    def get_recent_log_stream_name(logGroupName):
        response = client.describe_log_streams(
            logGroupName=logGroupName,
            orderBy='LastEventTime',
            descending=True,
            limit=1)
         logStreamName = response['logStreams'][0]['logStreamName']
         return logStreamName

Upvotes: 2

Views: 5190

Answers (1)

dmulter
dmulter

Reputation: 2758

I would write the test using moto like this:

import boto3
from moto import mock_logs


def get_recent_log_stream_name(logs, logGroupName):
    """Function under test"""
    response = logs.describe_log_streams(
        logGroupName=logGroupName,
        orderBy='LastEventTime',
        descending=True,
        limit=1)
    log_stream_name = response['logStreams'][0]['logStreamName']
    return log_stream_name

@mock_logs
def test_get_recent_log_stream_name():
    """Test function"""
    log_group_name = 'test-group'
    log_stream_name = 'test-stream'
    logs = boto3.client('logs')
    logs.create_log_group(logGroupName=log_group_name)
    logs.create_log_stream(
        logGroupName=log_group_name,
        logStreamName=log_stream_name,
    )
    assert get_recent_log_stream_name(logs, log_group_name) == log_stream_name

test_get_recent_log_stream_name()

Upvotes: 5

Related Questions