"""Tests gainst the DynamoDB model.""" import time from unittest.mock import MagicMock from unittest.mock import patch import pytest from owsrequest import model from owsrequest.constants.environment import PROD_ENVIRONMENT from owsrequest.constants.environment import QA_ENVIRONMENT @patch('owsrequest.connectors.dynamodb') def test_get_table(dynamodb): """Test getting the table for qa and prod.""" for environment in [QA_ENVIRONMENT, PROD_ENVIRONMENT]: model.get_table(QA_ENVIRONMENT) assert dynamodb.Table.called_with(model.TABLE_NAME.format( environment=environment)) @patch('owsrequest.connectors.dynamodb') def test_get_table_from_non_prod_or_qa_environment(dynamodb): """Test getting the table for a non qa or prod environment.""" for environment in ['dev', '', None]: model.get_table(environment) assert dynamodb.Table.called_with(model.TABLE_NAME.format( environment=QA_ENVIRONMENT)) def test_save_authorization(monkeypatch): """Test saving an authorization.""" table_mock = MagicMock() now = time.time() monkeypatch.setattr( model, 'get_table', MagicMock( return_value=table_mock, spec=model.get_table)) monkeypatch.setattr( time, 'time', MagicMock(return_value=now)) environment = QA_ENVIRONMENT hmac = 'validhmac' sender = 'ows-grass' recipient = 'ows-auth' secret = 'random secret' model.save_authorization(environment, hmac, sender, recipient, secret) table_mock.put_item.assert_called_with(Item={ 'authorization': '{recipient}:{hmac}'.format( recipient=recipient, hmac=hmac), 'sender': sender, 'secret': secret, 'created_at': int(now) }) @pytest.mark.parametrize('environment', [QA_ENVIRONMENT, PROD_ENVIRONMENT]) def test_get_authorization(monkeypatch, environment): """Test getting an authorization.""" table_mock = MagicMock() monkeypatch.setattr( model, 'get_table', MagicMock( return_value=table_mock, spec=model.get_table)) token_value = 'service_b:hmac' for token in ['sender/{}'.format(token_value), token_value]: model.get_authorization(environment, token) model.get_table.assert_called_with(environment) table_mock.get_item.assert_called_with( Key={'authorization': token_value}, ConsistentRead=True)