"""Test for the ows_product_config module.""" import json from flexmock import flexmock from owsrequest import request from owsrequest import test_utils import requests from label_copy_export.connectors import loggly from label_copy_export.constants import ows_services from label_copy_export.models import ows_product_config logger = loggly.get_current_logger() def test_get_distribution_format_response_404_json(monkeypatch): """Ensure that 404 response doesn't break the flow. Test that error message is propagated in response.errors. """ error_json = {'text': 'not found'} call_spec = { 'service': ows_services.OWS_PRODUCT_CONFIG, 'path': '/distribution-format-media', 'status': 404, 'json': error_json } mocked_process = test_utils.mock_ows_requests([call_spec]) monkeypatch.setattr( request, 'process', mocked_process, raising=False) result = ows_product_config.get_distribution_format_media_types() assert not result assert json.loads(result.errors) == error_json assert result.status == call_spec['status'] def test_get_distribution_format_response_with_valid_data(monkeypatch): """Test that with valid data the result will be successful.""" valid_json = {'items': [{ 'distribution_format_media_id': 2, 'name': '7\' Vinyl' }, { 'distribution_format_media_id': 3, 'name': '12\' Vinyl' }]} call_spec = { 'service': ows_services.OWS_PRODUCT_CONFIG, 'path': '/distribution-format-media', 'status': 200, 'json': valid_json } mocked_process = test_utils.mock_ows_requests([call_spec]) monkeypatch.setattr( request, 'process', mocked_process, raising=False) result = ows_product_config.get_distribution_format_media_types() assert result assert result.message == valid_json def test_get_distribution_format_invalid_json(monkeypatch): """Test get_distribution_format with invalid JSON in response. Tested function should return decoded original message on JSON decode exception. """ not_valid_json = b'non-JSON content' response = flexmock(requests.models.Response()) response._content = not_valid_json response.status_code = 401 flexmock(request).should_receive('process').and_return(response) result = ows_product_config.get_distribution_format_media_types() assert not result assert result.errors == not_valid_json.decode('utf8')