def test_process_aggregation_request_valid_request(mock_args, mock_cache_file):
    with patch('aggregation.aggregation_processor.requests.get') as mock_get:
        mock_get.return_value.status_code = 200
        mock_get.return_value.text = '{}'
        mock_get.return_value.headers = {}

        response, error = process_aggregation_request(mock_args)

    assert error is None
    assert response == {}
def test_process_aggregation_request_bad_request():
    params = {
        'aggregation': 'sum',
        'field': 'countries',
        'by': 'region',
    }
    response, error = process_aggregation_request(params)

    assert response is None

    errors_dict = json.loads(error)
    assert len(errors_dict) == 1
    assert errors_dict.get('field') == ['unallowed value countries']
def get_country_data():
    """Retrieve aggregated stats by aggregation type, metric, and region
    """

    parser = argparse.ArgumentParser(
        description=
        'Retrieve aggregated stats by aggregation type, metric, and region.', )
    parser.add_argument(
        '--aggregation',
        required=True,
        choices=[
            'avg',
            'count',
            'max',
            'min',
            'sum',
        ],
        help='Aggregation type',
    )
    parser.add_argument(
        '--field',
        required=True,
        choices=[
            'area',
            'borders',
            'countries',
            'currencies',
            'gini',
            'languages',
            'latlng',
            'population',
        ],
        help='Metric to aggregate',
    )
    parser.add_argument(
        '--by',
        required=True,
        choices=[
            'region',
            'subregion',
        ],
        help='Field to group aggregates by',
    )

    args = parser.parse_args()
    params = {
        'aggregation': args.aggregation,
        'field': args.field,
        'by': args.by,
    }
    return process_aggregation_request(params)
def test_process_aggregation_request_valid_request_cached_data(mock_args, mock_cache_file):
    with patch('aggregation.country_data_aggregator.os.path.isfile') as mock_isfile:
        mock_isfile.return_value = True
        expiry = datetime.datetime.now() + datetime.timedelta(hours=1)
        read_data = {
            'country_data': {},
            'country_data_expiry': expiry.strftime('%Y-%m-%d %H:%M:%S'),
            'aggregation_request_results': {},
        }
        with patch('builtins.open', mock_open(read_data=json.dumps(read_data))) as mock_cache_file:
            response, error = process_aggregation_request(mock_args)

    assert error is None
    assert response == {}
def test_process_aggregation_request_valid_request_with_max_age(mock_args, mock_cache_file):
    with patch('aggregation.aggregation_processor.requests.get') as mock_get:
        mock_get.return_value.status_code = 200
        mock_get.return_value.text = '{}'
        mock_get.return_value.headers = {'Cache-Control': 'max-age=60'}

        response, error = process_aggregation_request(mock_args)

    assert error is None
    assert response == {}

    expiry = datetime.datetime.now() + datetime.timedelta(seconds=60)
    cache_data = {
        'country_data': {},
        'country_data_expiry': expiry.strftime('%Y-%m-%d %H:%M:%S'),
        'aggregation_request_results': {"sum:area:region": {}},
    }
    handle = mock_cache_file()
    handle.write.assert_called_with(json.dumps(cache_data))
def test_process_aggregation_request_api_exception(mock_args, mock_cache_file):
    with patch('aggregation.aggregation_processor.requests.get') as mock_get:
        mock_get.side_effect = Exception('test')
        response, error = process_aggregation_request(mock_args)

    assert error == 'Could not retrieve country data, please try again later.'
def test_process_aggregation_request_api_error(mock_args, mock_cache_file):
    with patch('aggregation.aggregation_processor.requests.get') as mock_get:
        mock_get.return_value.status_code = 500
        response, error = process_aggregation_request(mock_args)

    assert error == 'Could not retrieve country data, please try again later.'