from mock import MagicMock import boto3 import json import moto import pytest import aws_lambda @moto.mock_s3() def test_process_file(monkeypatch): """Test processing a file. """ spy = MagicMock() def process_data(line): """Verifies the method is called and the dict has the right format. """ spy() assert isinstance(line, dict) for key in ('metric', 'month', 'label_id'): assert key in line monkeypatch.setattr(aws_lambda, 'process_data', process_data) bucket = 'test' name = 'testfile' body = open('tests/fixtures/data.txt', 'rb').read() s3 = boto3.client('s3', 'us-east-1') s3.create_bucket(Bucket=bucket) s3.put_object(Bucket=bucket, Key=name, Body=body) aws_lambda.process_file(bucket, name) assert spy.call_count == 7200 def test_process_data(monkeypatch): """Test processing the data. """ monkeypatch.setattr(aws_lambda, 'dynamodb', MagicMock()) line = open('tests/fixtures/data.txt', 'rb').readline().decode('utf8') line = json.loads(line) aws_lambda.process_data(line) aws_lambda.dynamodb.update_item.assert_called_with( TableName=aws_lambda.TABLE_NAME, Key={ 'metric': {'S': 'S:15894:DT'}, 'month': {'S': '2016-01'} }, AttributeUpdates={ 'label_id':{ 'Action':'PUT', 'Value':{ 'S':'20773' } }, 'subaccount_id':{ 'Action':'PUT', 'Value':{ 'S':'15894' } }, u'11':{ 'Action':'PUT', 'Value':{ 'M':{ 'all':{ 'S':'6' }, 'paid':{ 'S':'6' } } } }, u'10':{ 'Action':'PUT', 'Value':{ 'M':{ 'all':{ 'S':'3' }, 'paid':{ 'S':'3' } } } }, u'27':{ 'Action':'PUT', 'Value':{ 'M':{ 'all':{ 'S':'1' }, 'paid':{ 'S':'1' } } } }, u'20':{ 'Action':'PUT', 'Value':{ 'M':{ 'all':{ 'S':'1' }, 'paid':{ 'S':'1' } } } }, u'07':{ 'Action':'PUT', 'Value':{ 'M':{ 'all':{ 'S':'2' }, 'paid':{ 'S':'2' } } } }, u'23':{ 'Action':'PUT', 'Value':{ 'M':{ 'all':{ 'S':'2' }, 'paid':{ 'S':'2' } } } }, u'30':{ 'Action':'PUT', 'Value':{ 'M':{ 'all':{ 'S':'2' }, 'paid':{ 'S':'2' } } } }, u'15':{ 'Action':'PUT', 'Value':{ 'M':{ 'all':{ 'S':'1' }, 'paid':{ 'S':'1' } } } }, u'14':{ 'Action':'PUT', 'Value':{ 'M':{ 'all':{ 'S':'2' }, 'paid':{ 'S':'2' } } } } }) def test_process_data_without_metric(monkeypatch): """Test processing the data without a metric name. """ monkeypatch.setattr(aws_lambda, 'dynamodb', MagicMock()) with pytest.raises(KeyError) as key: aws_lambda.process_data(dict(month='month')) assert 'KeyError: \'metric\'' in str(key) assert not aws_lambda.dynamodb.update_item.called def test_process_data_without_month(monkeypatch): """Test processing the data without a metric name. """ monkeypatch.setattr(aws_lambda, 'dynamodb', MagicMock()) with pytest.raises(KeyError) as key: aws_lambda.process_data(dict(metric='metric')) assert 'KeyError: \'month\'' in str(key) assert not aws_lambda.dynamodb.update_item.called