mirror of
https://github.com/getredash/redash.git
synced 2026-03-22 01:00:14 -04:00
* Make core app compatible with Python 3 No backward compatibility with Python 2.7 is kept. This commit mostly contains changes made with 2to3 and manual tweaking when necessary. * Use Python 3.7 as base docker image Since it is not possible to change redash/base:debian to Python 3 without breaking future relases, its Dockerfile is temporarly copied here. * Upgrade some requirements to newest versions Some of the older versions were not compatible with Python 3. * Migrate tests to Python 3 * Build frontend on Python 3 * Make the HMAC sign function compatible with Python 3 In Python 3, HMAC only works with bytes so the strings and the float used in the sign function need to be encoded. Hopefully this is still backward compatible with already generated signatures. * Use assertCountEqual instead of assertItemsEqual The latter is not available in Python 3. See https://bugs.python.org/issue17866 * Remove redundant encoding header for Python 3 modules * Remove redundant string encoding in CLI * Rename list() functions in CLI These functions shadow the builtin list function which is problematic since 2to3 adds a fair amount of calls to the builtin list when it finds dict.keys() and dict.values(). Only the Python function is renamed, from the perspective of the CLI nothing changes. * Replace usage of Exception.message in CLI `message` is not available anymore, instead use the string representation of the exception. * Adapt test handlers to Python 3 * Fix test that relied on dict ordering * Make sure test results are always uploaded (#4215) * Support encoding memoryview to JSON psycopg2 returns `buffer` objects in Python 2.7 and `memoryview` in Python 3. See #3156 * Fix test relying on object address ordering * Decode bytes returned from Redis * Stop using e.message for most exceptions Exception.message is not available in Python 3 anymore, except for some exceptions defined by third-party libraries. * Fix writing XLSX files in Python 3 The buffer for the file should be made of bytes and the actual content written to it strings. Note: I do not know why the diff is so large as it's only a two lines change. Probably a white space or file encoding issue. * Fix test by comparing strings to strings * Fix another exception message unavailable in Python 3 * Fix export to CSV in Python 3 The UnicodeWriter is not used anymore. In Python 3, the interface provided by the CSV module only deals with strings, in and out. The encoding of the output is left to the user, in our case it is given to Flask via `make_response`. * (Python 3) Use Redis' decode_responses=True option (#4232) * Fix test_outdated_queries_works_scheduled_queries_tracker (use utcnow) * Make sure Redis connection uses decoded_responses option * Remove unused imports. * Use Redis' decode_responses option * Remove cases of explicit Redis decoding * Rename helper function and make sure it doesn't apply twice. * Don't add decode_responses to Celery Redis connection URL * Fix displaying error while connecting to SQLite The exception message is always a string in Python 3, so no need to try to decode things. * Fix another missing exception message * Handle JSON encoding for datasources returning bytes SimpleJSON assumes the bytes it receives contain text data, so it tries to UTF-8 encode them. It is sometimes not true, for instance the SQLite datasource returns bytes for BLOB types, which typically do not contain text but truly binary data. This commit disables SimpleJSON auto encoding of bytes to str and instead uses the same method as for memoryviews: generating a hex representation of the data. * Fix Python 3 compatibility with RQ * Revert some changes 2to3 tends to do (#4261) - Revert some changes 2to3 tends to do when it errs on the side of caution regarding dict view objects. - Also fixed some naming issues with one character variables in list comprehensions. - Fix Flask warning. * Upgrade dependencies * Remove useless `iter` added by 2to3 * Fix get_next_path tests (#4280) * Removed setting SERVER_NAME in tests setup to avoid a warning. * Change get_next_path to not return empty string in case of a domain only value. * Fix redirect tests: Since version 0.15 of Werkzeug it uses full path for fixing the location header instead of the root path. * Remove explicit dependency for Werkzeug * Switched pytz and certifi to unbinded versions. * Switch to new library for getting country from IP `python-geoip-geolite2` is not compatible with Python 3, instead use `maxminddb-geolite2` which is very similar as it includes the geolite2 database in the package . * Python 3 RQ modifications (#4281) * show current worker job (alongside with minor cosmetic column tweaks) * avoid loading entire job data for queued jobs * track general RQ queues (default, periodic and schemas) * get all active RQ queues * call get_celery_queues in another place * merge dicts the Python 3 way * extend the result_ttl of refresh_queries to 600 seconds to allow it to continue running periodically even after longer executions * Remove legacy Python flake8 tests
261 lines
9.9 KiB
Python
261 lines
9.9 KiB
Python
from unittest import TestCase
|
|
from mock import patch
|
|
from collections import namedtuple
|
|
import pytest
|
|
|
|
from redash.models.parameterized_query import ParameterizedQuery, InvalidParameterError, QueryDetachedFromDataSourceError, dropdown_values
|
|
|
|
|
|
class TestParameterizedQuery(TestCase):
|
|
def test_returns_empty_list_for_regular_query(self):
|
|
query = ParameterizedQuery("SELECT 1")
|
|
self.assertEqual(set([]), query.missing_params)
|
|
|
|
def test_finds_all_params_when_missing(self):
|
|
query = ParameterizedQuery("SELECT {{param}} FROM {{table}}")
|
|
self.assertEqual(set(['param', 'table']), query.missing_params)
|
|
|
|
def test_finds_all_params(self):
|
|
query = ParameterizedQuery("SELECT {{param}} FROM {{table}}").apply({
|
|
'param': 'value',
|
|
'table': 'value'
|
|
})
|
|
self.assertEqual(set([]), query.missing_params)
|
|
|
|
def test_deduplicates_params(self):
|
|
query = ParameterizedQuery("SELECT {{param}}, {{param}} FROM {{table}}").apply({
|
|
'param': 'value',
|
|
'table': 'value'
|
|
})
|
|
self.assertEqual(set([]), query.missing_params)
|
|
|
|
def test_handles_nested_params(self):
|
|
query = ParameterizedQuery("SELECT {{param}}, {{param}} FROM {{table}} -- {{#test}} {{nested_param}} {{/test}}").apply({
|
|
'param': 'value',
|
|
'table': 'value'
|
|
})
|
|
self.assertEqual(set(['test', 'nested_param']), query.missing_params)
|
|
|
|
def test_handles_objects(self):
|
|
query = ParameterizedQuery("SELECT * FROM USERS WHERE created_at between '{{ created_at.start }}' and '{{ created_at.end }}'").apply({
|
|
'created_at': {
|
|
'start': 1,
|
|
'end': 2
|
|
}
|
|
})
|
|
self.assertEqual(set([]), query.missing_params)
|
|
|
|
def test_raises_on_parameters_not_in_schema(self):
|
|
schema = [{"name": "bar", "type": "text"}]
|
|
query = ParameterizedQuery("foo", schema)
|
|
|
|
with pytest.raises(InvalidParameterError):
|
|
query.apply({"qux": 7})
|
|
|
|
def test_raises_on_invalid_text_parameters(self):
|
|
schema = [{"name": "bar", "type": "text"}]
|
|
query = ParameterizedQuery("foo", schema)
|
|
|
|
with pytest.raises(InvalidParameterError):
|
|
query.apply({"bar": 7})
|
|
|
|
def test_validates_text_parameters(self):
|
|
schema = [{"name": "bar", "type": "text"}]
|
|
query = ParameterizedQuery("foo {{bar}}", schema)
|
|
|
|
query.apply({"bar": "baz"})
|
|
|
|
self.assertEqual("foo baz", query.text)
|
|
|
|
def test_raises_on_invalid_number_parameters(self):
|
|
schema = [{"name": "bar", "type": "number"}]
|
|
query = ParameterizedQuery("foo", schema)
|
|
|
|
with pytest.raises(InvalidParameterError):
|
|
query.apply({"bar": "baz"})
|
|
|
|
def test_validates_number_parameters(self):
|
|
schema = [{"name": "bar", "type": "number"}]
|
|
query = ParameterizedQuery("foo {{bar}}", schema)
|
|
|
|
query.apply({"bar": 7})
|
|
|
|
self.assertEqual("foo 7", query.text)
|
|
|
|
def test_coerces_number_parameters(self):
|
|
schema = [{"name": "bar", "type": "number"}]
|
|
query = ParameterizedQuery("foo {{bar}}", schema)
|
|
|
|
query.apply({"bar": "3.14"})
|
|
|
|
self.assertEqual("foo 3.14", query.text)
|
|
|
|
def test_raises_on_invalid_date_parameters(self):
|
|
schema = [{"name": "bar", "type": "date"}]
|
|
query = ParameterizedQuery("foo", schema)
|
|
|
|
with pytest.raises(InvalidParameterError):
|
|
query.apply({"bar": "baz"})
|
|
|
|
def test_raises_on_none_for_date_parameters(self):
|
|
schema = [{"name": "bar", "type": "date"}]
|
|
query = ParameterizedQuery("foo", schema)
|
|
|
|
with pytest.raises(InvalidParameterError):
|
|
query.apply({"bar": None})
|
|
|
|
def test_validates_date_parameters(self):
|
|
schema = [{"name": "bar", "type": "date"}]
|
|
query = ParameterizedQuery("foo {{bar}}", schema)
|
|
|
|
query.apply({"bar": "2000-01-01 12:00:00"})
|
|
|
|
self.assertEqual("foo 2000-01-01 12:00:00", query.text)
|
|
|
|
def test_raises_on_invalid_enum_parameters(self):
|
|
schema = [{"name": "bar", "type": "enum", "enumOptions": ["baz", "qux"]}]
|
|
query = ParameterizedQuery("foo", schema)
|
|
|
|
with pytest.raises(InvalidParameterError):
|
|
query.apply({"bar": 7})
|
|
|
|
def test_raises_on_unlisted_enum_value_parameters(self):
|
|
schema = [{"name": "bar", "type": "enum", "enumOptions": ["baz", "qux"]}]
|
|
query = ParameterizedQuery("foo", schema)
|
|
|
|
with pytest.raises(InvalidParameterError):
|
|
query.apply({"bar": "shlomo"})
|
|
|
|
def test_raises_on_unlisted_enum_list_value_parameters(self):
|
|
schema = [{
|
|
"name": "bar",
|
|
"type": "enum",
|
|
"enumOptions": ["baz", "qux"],
|
|
"multiValuesOptions": {"separator": ",", "prefix": "", "suffix": ""}
|
|
}]
|
|
query = ParameterizedQuery("foo", schema)
|
|
|
|
with pytest.raises(InvalidParameterError):
|
|
query.apply({"bar": ["shlomo", "baz"]})
|
|
|
|
def test_validates_enum_parameters(self):
|
|
schema = [{"name": "bar", "type": "enum", "enumOptions": ["baz", "qux"]}]
|
|
query = ParameterizedQuery("foo {{bar}}", schema)
|
|
|
|
query.apply({"bar": "baz"})
|
|
|
|
self.assertEqual("foo baz", query.text)
|
|
|
|
def test_validates_enum_list_value_parameters(self):
|
|
schema = [{
|
|
"name": "bar",
|
|
"type": "enum",
|
|
"enumOptions": ["baz", "qux"],
|
|
"multiValuesOptions": {"separator": ",", "prefix": "'", "suffix": "'"}
|
|
}]
|
|
query = ParameterizedQuery("foo {{bar}}", schema)
|
|
|
|
query.apply({"bar": ["qux", "baz"]})
|
|
|
|
self.assertEqual("foo 'qux','baz'", query.text)
|
|
|
|
@patch('redash.models.parameterized_query.dropdown_values', return_value=[{"value": "1"}])
|
|
def test_validation_accepts_integer_values_for_dropdowns(self, _):
|
|
schema = [{"name": "bar", "type": "query", "queryId": 1}]
|
|
query = ParameterizedQuery("foo {{bar}}", schema)
|
|
|
|
query.apply({"bar": 1})
|
|
|
|
self.assertEqual("foo 1", query.text)
|
|
|
|
@patch('redash.models.parameterized_query.dropdown_values')
|
|
def test_raises_on_invalid_query_parameters(self, _):
|
|
schema = [{"name": "bar", "type": "query", "queryId": 1}]
|
|
query = ParameterizedQuery("foo", schema)
|
|
|
|
with pytest.raises(InvalidParameterError):
|
|
query.apply({"bar": 7})
|
|
|
|
@patch('redash.models.parameterized_query.dropdown_values', return_value=[{"value": "baz"}])
|
|
def test_raises_on_unlisted_query_value_parameters(self, _):
|
|
schema = [{"name": "bar", "type": "query", "queryId": 1}]
|
|
query = ParameterizedQuery("foo", schema)
|
|
|
|
with pytest.raises(InvalidParameterError):
|
|
query.apply({"bar": "shlomo"})
|
|
|
|
@patch('redash.models.parameterized_query.dropdown_values', return_value=[{"value": "baz"}])
|
|
def test_validates_query_parameters(self, _):
|
|
schema = [{"name": "bar", "type": "query", "queryId": 1}]
|
|
query = ParameterizedQuery("foo {{bar}}", schema)
|
|
|
|
query.apply({"bar": "baz"})
|
|
|
|
self.assertEqual("foo baz", query.text)
|
|
|
|
def test_raises_on_invalid_date_range_parameters(self):
|
|
schema = [{"name": "bar", "type": "date-range"}]
|
|
query = ParameterizedQuery("foo", schema)
|
|
|
|
with pytest.raises(InvalidParameterError):
|
|
query.apply({"bar": "baz"})
|
|
|
|
def test_validates_date_range_parameters(self):
|
|
schema = [{"name": "bar", "type": "date-range"}]
|
|
query = ParameterizedQuery("foo {{bar.start}} {{bar.end}}", schema)
|
|
|
|
query.apply({"bar": {"start": "2000-01-01 12:00:00", "end": "2000-12-31 12:00:00"}})
|
|
|
|
self.assertEqual("foo 2000-01-01 12:00:00 2000-12-31 12:00:00", query.text)
|
|
|
|
def test_raises_on_unexpected_param_types(self):
|
|
schema = [{"name": "bar", "type": "burrito"}]
|
|
query = ParameterizedQuery("foo", schema)
|
|
|
|
with pytest.raises(InvalidParameterError):
|
|
query.apply({"bar": "baz"})
|
|
|
|
def test_is_not_safe_if_expecting_text_parameter(self):
|
|
schema = [{"name": "bar", "type": "text"}]
|
|
query = ParameterizedQuery("foo", schema)
|
|
|
|
self.assertFalse(query.is_safe)
|
|
|
|
def test_is_safe_if_not_expecting_text_parameter(self):
|
|
schema = [{"name": "bar", "type": "number"}]
|
|
query = ParameterizedQuery("foo", schema)
|
|
|
|
self.assertTrue(query.is_safe)
|
|
|
|
def test_is_safe_if_not_expecting_any_parameters(self):
|
|
schema = []
|
|
query = ParameterizedQuery("foo", schema)
|
|
|
|
self.assertTrue(query.is_safe)
|
|
|
|
@patch('redash.models.parameterized_query._load_result', return_value={
|
|
"columns": [{"name": "id"}, {"name": "Name"}, {"name": "Value"}],
|
|
"rows": [{"id": 5, "Name": "John", "Value": "John Doe"}]})
|
|
def test_dropdown_values_prefers_name_and_value_columns(self, _):
|
|
values = dropdown_values(1, None)
|
|
self.assertEqual(values, [{"name": "John", "value": "John Doe"}])
|
|
|
|
@patch('redash.models.parameterized_query._load_result', return_value={
|
|
"columns": [{"name": "id"}, {"name": "fish"}, {"name": "poultry"}],
|
|
"rows": [{"fish": "Clown", "id": 5, "poultry": "Hen"}]})
|
|
def test_dropdown_values_compromises_for_first_column(self, _):
|
|
values = dropdown_values(1, None)
|
|
self.assertEqual(values, [{"name": 5, "value": "5"}])
|
|
|
|
@patch('redash.models.parameterized_query._load_result', return_value={
|
|
"columns": [{"name": "ID"}, {"name": "fish"}, {"name": "poultry"}],
|
|
"rows": [{"fish": "Clown", "ID": 5, "poultry": "Hen"}]})
|
|
def test_dropdown_supports_upper_cased_columns(self, _):
|
|
values = dropdown_values(1, None)
|
|
self.assertEqual(values, [{"name": 5, "value": "5"}])
|
|
|
|
@patch('redash.models.Query.get_by_id_and_org', return_value=namedtuple('Query', 'data_source')(None))
|
|
def test_dropdown_values_raises_when_query_is_detached_from_data_source(self, _):
|
|
with pytest.raises(QueryDetachedFromDataSourceError):
|
|
dropdown_values(1, None)
|