diff --git a/dysql/test/__init__.py b/dysql/test/__init__.py new file mode 100644 --- /dev/null +++ b/dysql/test/__init__.py @@ -0,0 +1,55 @@ +""" +Copyright 2021 Adobe +All Rights Reserved. + +NOTICE: Adobe permits you to use, modify, and distribute this file in accordance +with the terms of the Adobe license agreement accompanying it. +""" + +from unittest.mock import Mock + +from dysql import set_default_connection_parameters, databases + + +def setup_mock_engine(mock_create_engine): + """ + build up the basics of a mock engine for the database + :return: mocked engine for use and manipulation in testing + """ + mock_engine = Mock() + mock_engine.connect().execution_options().__enter__ = Mock() + mock_engine.connect().execution_options().__exit__ = Mock() + set_default_connection_parameters("fake", "user", "password", "test") + + # Clear out the databases before attempting to mock anything + databases.DatabaseContainerSingleton().clear() + mock_create_engine.return_value = mock_engine + return mock_engine + + +def verify_query_params(mock_engine, expected_query, expected_args): + verify_query(mock_engine, expected_query) + verify_query_args(mock_engine, expected_args) + + +def verify_query(mock_engine, expected_query): + execute_call = ( + mock_engine.connect.return_value.execution_options.return_value.execute + ) + execute_call.assert_called() + + query = execute_call.call_args[0][0].text + assert query == expected_query + + +def verify_query_args(mock_engine, expected_args): + execute_call = ( + mock_engine.connect.return_value.execution_options.return_value.execute + ) + query_args = execute_call.call_args[0][1] + + assert query_args + for expected_key in expected_args: + expected_value = expected_args[expected_key] + assert query_args.get(expected_key) + assert expected_value == query_args[expected_key] diff --git a/dysql/test/conftest.py b/dysql/test/conftest.py new file mode 100644 --- /dev/null +++ b/dysql/test/conftest.py @@ -0,0 +1,19 @@ +""" +Copyright 2021 Adobe +All Rights Reserved. + +NOTICE: Adobe permits you to use, modify, and distribute this file in accordance +with the terms of the Adobe license agreement accompanying it. +""" + +from unittest.mock import patch +import pytest + + +@pytest.fixture(name="mock_create_engine") +def mock_create_engine_fixture(): + create_mock = patch("dysql.databases.sqlalchemy.create_engine") + try: + yield create_mock.start() + finally: + create_mock.stop() diff --git a/dysql/test/test_annotations.py b/dysql/test/test_annotations.py new file mode 100644 --- /dev/null +++ b/dysql/test/test_annotations.py @@ -0,0 +1,68 @@ +""" +Copyright 2023 Adobe +All Rights Reserved. + +NOTICE: Adobe permits you to use, modify, and distribute this file in accordance +with the terms of the Adobe license agreement accompanying it. +""" + +from typing import List, Union + +import pytest +from pydantic import BaseModel, ValidationError + +from dysql.annotations import FromCSVToList + + +class StrCSVModel(BaseModel): + values: FromCSVToList[List[str]] + + +class IntCSVModel(BaseModel): + values: FromCSVToList[List[int]] + + +class NullableStrCSVModel(BaseModel): + values: FromCSVToList[Union[List[str], None]] + + +class NullableIntCSVModel(BaseModel): + values: FromCSVToList[Union[List[int], None]] + + +@pytest.mark.parametrize( + "cls, values, expected", + [ + (StrCSVModel, "1,2,3", ["1", "2", "3"]), + (StrCSVModel, "a,b", ["a", "b"]), + (StrCSVModel, "a", ["a"]), + (NullableStrCSVModel, "", None), + (NullableStrCSVModel, None, None), + (StrCSVModel, ["a", "b"], ["a", "b"]), + (StrCSVModel, ["a", "b", "c"], ["a", "b", "c"]), + (IntCSVModel, "1,2,3", [1, 2, 3]), + (IntCSVModel, "1", [1]), + (NullableIntCSVModel, "", None), + (NullableIntCSVModel, None, None), + (IntCSVModel, ["1", "2", "3"], [1, 2, 3]), + (IntCSVModel, ["1", "2", "3", 4, 5], [1, 2, 3, 4, 5]), + ], +) +def test_from_csv_to_list(cls, values, expected): + assert expected == cls(values=values).values + + +@pytest.mark.parametrize( + "cls, values", + [ + (StrCSVModel, ""), + (StrCSVModel, None), + (IntCSVModel, "a,b,c"), + (IntCSVModel, ""), + (IntCSVModel, None), + (IntCSVModel, ["a", "b", "c"]), + ], +) +def test_from_csv_to_list_invalid(cls, values): + with pytest.raises(ValidationError): + cls(values=values) diff --git a/dysql/test/test_database_initialization.py b/dysql/test/test_database_initialization.py new file mode 100644 --- /dev/null +++ b/dysql/test/test_database_initialization.py @@ -0,0 +1,240 @@ +""" +Copyright 2021 Adobe +All Rights Reserved. + +NOTICE: Adobe permits you to use, modify, and distribute this file in accordance +with the terms of the Adobe license agreement accompanying it. +""" + +from unittest import mock + +import pytest + +import dysql.connections +from dysql import ( + sqlquery, + DBNotPreparedError, + set_default_connection_parameters, + QueryData, + set_database_init_hook, +) +from dysql.test import setup_mock_engine + + +""" +These tests reflect what can happen when dealing with a config passing in a value that may not +have been set. There are some parameters that are absolutely necessary, if they aren't set we +want to make sure we are warning the user in different ways. +""" + + +@sqlquery() +def query(): + """ + This is used to call the code that would initialize the database on the first time. + If there were any failures this is where we would expect to see them. + """ + return QueryData("SELECT * FROM table") + + +@pytest.fixture(autouse=True, name="mock_engine") +def fixture_mock_engine(mock_create_engine): + dysql.databases.DatabaseContainerSingleton().clear() + dysql.databases._DEFAULT_CONNECTION_PARAMS_BY_KEY.clear() + + # Reset the database before the test + dysql.databases.reset_current_database() + + yield setup_mock_engine(mock_create_engine) + + # Reset database after the test as well + dysql.databases.reset_current_database() + + +@pytest.fixture(autouse=True) +def fixture_reset_init_hook(): + yield + if hasattr(dysql.databases.Database, "hook_method"): + delattr(dysql.databases.Database, "hook_method") + + +def test_nothing_set(): + dysql.databases._DEFAULT_CONNECTION_PARAMS_BY_KEY.clear() + with pytest.raises(DBNotPreparedError) as error: + query() + assert ( + str(error.value) + == "Unable to connect to a database, set_default_connection_parameters must first be called" + ) + + +@pytest.mark.parametrize( + "host, user, password, database, failed_field", + [ + (None, "u", "p", "d", "host"), + ("", "u", "p", "d", "host"), + ("h", None, "p", "d", "user"), + ("h", "", "p", "d", "user"), + ("h", "u", None, "d", "password"), + ("h", "u", "", "d", "password"), + ("h", "u", "p", None, "database"), + ("h", "u", "p", "", "database"), + ], +) +def test_fields_required(host, user, password, database, failed_field): + with pytest.raises(DBNotPreparedError) as error: + set_default_connection_parameters(host, user, password, database) + assert ( + str(error.value) + == f'Database parameter "{failed_field}" is not set or empty and is required' + ) + + +def test_minimal_credentials(mock_engine): + set_default_connection_parameters("h", "u", "p", "d") + + mock_engine.connect().execution_options().execute.return_value = [] + query() + + +def test_init_hook(mock_engine): + init_hook = mock.MagicMock() + set_database_init_hook(init_hook) + set_default_connection_parameters("h", "u", "p", "d") + dysql.databases.set_current_database("d") + + mock_engine.connect().execution_options().execute.return_value = [] + query() + init_hook.assert_called_once_with("d", mock_engine) + + +def test_init_hook_multiple_databases(mock_engine): + init_hook = mock.MagicMock() + set_database_init_hook(init_hook) + set_default_connection_parameters("h1", "u1", "p1", "d1") + set_default_connection_parameters("h2", "u2", "p2", "d2") + + mock_engine.connect().execution_options().execute.return_value = [] + query() + dysql.databases.set_current_database("d1") + query() + assert init_hook.call_args_list == [ + mock.call("test", mock_engine), + mock.call("d1", mock_engine), + ] + dysql.databases.set_current_database("d2") + query() + assert init_hook.call_args_list == [ + mock.call("test", mock_engine), + mock.call("d1", mock_engine), + mock.call("d2", mock_engine), + ] + + +def test_current_database_default(mock_engine, mock_create_engine): + db_container = dysql.databases.DatabaseContainerSingleton() + assert len(db_container) == 0 + mock_engine.connect().execution_options().execute.return_value = [] + query() + + # Only one database is initialized + assert len(db_container) == 1 + assert "test" in db_container + assert db_container.current_database.database == "test" + mock_create_engine.assert_called_once_with( + "mysql+mysqlconnector://user:password@fake:3306/test?charset=utf8", + echo=False, + pool_pre_ping=True, + pool_recycle=3600, + pool_size=10, + ) + + +def test_different_charset_collation(mock_engine, mock_create_engine): + db_container = dysql.databases.DatabaseContainerSingleton() + set_default_connection_parameters( + "host", + "user", + "password", + "database", + charset="other", + collation="other_collation", + ) + assert len(db_container) == 0 + dysql.databases.set_current_database("database") + mock_engine.connect().execution_options().execute.return_value = [] + query() + + # Only one database is initialized + mock_create_engine.assert_called_once_with( + "mysql+mysqlconnector://user:password@host:3306/database?charset=other&collation=other_collation", + echo=False, + pool_pre_ping=True, + pool_recycle=3600, + pool_size=10, + ) + + +def test_is_set_current_database_supported(): + # This test only asserts that true is always returned since this method is deprecated + assert dysql.databases.is_set_current_database_supported() + + +def test_current_database_set(mock_engine, mock_create_engine): + db_container = dysql.databases.DatabaseContainerSingleton() + set_default_connection_parameters("h1", "u1", "p1", "d1", database_key="db1") + dysql.databases.set_current_database("db1") + mock_engine.connect().execution_options().execute.return_value = [] + query() + + assert len(db_container) == 1 + assert "db1" in db_container + assert db_container.current_database.database == "db1" + mock_create_engine.assert_called_once_with( + "mysql+mysqlconnector://u1:p1@h1:3306/d1?charset=utf8", + echo=False, + pool_pre_ping=True, + pool_recycle=3600, + pool_size=10, + ) + + +def test_current_database_cached(mock_engine, mock_create_engine): + db_container = dysql.databases.DatabaseContainerSingleton() + mock_engine.connect().execution_options().execute.return_value = [] + query() + + assert len(db_container) == 1 + assert "test" in db_container + assert db_container.current_database.database == "test" + + set_default_connection_parameters("h1", "u1", "p1", "db1") + dysql.databases.set_current_database("db1") + query() + assert len(db_container) == 2 + assert "test" in db_container + assert db_container.current_database.database == "db1" + + # Set back to default + dysql.databases.reset_current_database() + query() + assert len(db_container) == 2 + assert db_container.current_database.database == "test" + + assert mock_create_engine.call_count == 2 + assert mock_create_engine.call_args_list == [ + mock.call( + "mysql+mysqlconnector://user:password@fake:3306/test?charset=utf8", + echo=False, + pool_pre_ping=True, + pool_recycle=3600, + pool_size=10, + ), + mock.call( + "mysql+mysqlconnector://u1:p1@h1:3306/db1?charset=utf8", + echo=False, + pool_pre_ping=True, + pool_recycle=3600, + pool_size=10, + ), + ] diff --git a/dysql/test/test_mappers.py b/dysql/test/test_mappers.py new file mode 100644 --- /dev/null +++ b/dysql/test/test_mappers.py @@ -0,0 +1,227 @@ +""" +Copyright 2021 Adobe +All Rights Reserved. + +NOTICE: Adobe permits you to use, modify, and distribute this file in accordance +with the terms of the Adobe license agreement accompanying it. +""" + +import pytest + +from dysql import ( + RecordCombiningMapper, + SingleRowMapper, + SingleColumnMapper, + SingleRowAndColumnMapper, + CountMapper, + KeyValueMapper, +) +from dysql.mappers import MapperError + + +class TestMappers: + """ + Test Mappers + """ + + @staticmethod + def _unwrap_results(results): + return [r.raw() for r in results] + + def test_record_combining(self): + mapper = RecordCombiningMapper() + assert len(mapper.map_records([])) == 0 + assert self._unwrap_results(mapper.map_records([{"a": 1, "b": 2}])) == [ + {"a": 1, "b": 2} + ] + assert self._unwrap_results( + mapper.map_records( + [ + {"id": 1, "a": 1, "b": 2}, + {"id": 2, "a": 1, "b": 2}, + {"id": 1, "c": 3}, + ] + ) + ) == [ + {"id": 1, "a": 1, "b": 2, "c": 3}, + {"id": 2, "a": 1, "b": 2}, + ] + + @staticmethod + def test_record_combining_no_record_mapper(): + mapper = RecordCombiningMapper(record_mapper=None) + assert len(mapper.map_records([])) == 0 + assert mapper.map_records([{"a": 1, "b": 2}]) == [{"a": 1, "b": 2}] + assert mapper.map_records( + [ + {"id": 1, "a": 1, "b": 2}, + {"id": 2, "a": 1, "b": 2}, + {"id": 1, "c": 3}, + ] + ) == [ + {"id": 1, "a": 1, "b": 2}, + {"id": 2, "a": 1, "b": 2}, + {"id": 1, "c": 3}, + ] + + @staticmethod + def test_single_row(): + mapper = SingleRowMapper() + assert mapper.map_records([]) is None + assert mapper.map_records([{"a": 1, "b": 2}]).raw() == {"a": 1, "b": 2} + assert mapper.map_records( + [ + {"id": 1, "a": 1, "b": 2}, + {"id": 2, "a": 1, "b": 2}, + {"id": 1, "c": 3}, + ] + ).raw() == {"id": 1, "a": 1, "b": 2} + + @staticmethod + def test_single_row_no_record_mapper(): + mapper = SingleRowMapper(record_mapper=None) + assert mapper.map_records([]) is None + assert mapper.map_records([{"a": 1, "b": 2}]) == {"a": 1, "b": 2} + assert mapper.map_records( + [ + {"id": 1, "a": 1, "b": 2}, + {"id": 2, "a": 1, "b": 2}, + {"id": 1, "c": 3}, + ] + ) == {"id": 1, "a": 1, "b": 2} + + @staticmethod + def test_single_column(): + mapper = SingleColumnMapper() + assert len(mapper.map_records([])) == 0 + assert mapper.map_records([{"a": 1, "b": 2}]) == [1] + assert mapper.map_records( + [ + {"id": "myid1", "a": 1, "b": 2}, + {"id": "myid2", "a": 1, "b": 2}, + {"id": "myid3", "c": 3}, + ] + ) == ["myid1", "myid2", "myid3"] + + @staticmethod + @pytest.mark.parametrize( + "mapper", + [ + SingleRowAndColumnMapper(), + # Alias for the other one + CountMapper(), + ], + ) + def test_single_column_and_row(mapper): + assert mapper.map_records([]) is None + assert mapper.map_records([{"a": 1, "b": 2}]) == 1 + assert ( + mapper.map_records( + [ + {"id": "myid", "a": 1, "b": 2}, + {"id": 2, "a": 1, "b": 2}, + {"id": 1, "c": 3}, + ] + ) + == "myid" + ) + + @staticmethod + @pytest.mark.parametrize( + "mapper, expected", + [ + (KeyValueMapper(), {"a": 4, "b": 7}), + (KeyValueMapper(key_column="column_named_something"), {"a": 4, "b": 7}), + (KeyValueMapper(value_column="column_with_some_value"), {"a": 4, "b": 7}), + ( + KeyValueMapper(has_multiple_values_per_key=True), + {"a": [1, 2, 3, 4], "b": [3, 4, 5, 6, 7]}, + ), + ( + KeyValueMapper( + key_column="column_named_something", + has_multiple_values_per_key=True, + ), + {"a": [1, 2, 3, 4], "b": [3, 4, 5, 6, 7]}, + ), + ( + KeyValueMapper( + key_column="column_with_some_value", + value_column="column_named_something", + has_multiple_values_per_key=True, + ), + { + 1: ["a"], + 2: ["a"], + 3: ["a", "b"], + 4: ["a", "b"], + 5: ["b"], + 6: ["b"], + 7: ["b"], + }, + ), + ( + KeyValueMapper( + key_column="column_with_some_value", + value_column="column_named_something", + ), + {1: "a", 2: "a", 3: "b", 4: "b", 5: "b", 6: "b", 7: "b"}, + ), + ], + ) + def test_key_mapper_key_has_multiple(mapper, expected): + result = mapper.map_records( + [ + HelperRow( + ("column_named_something", "column_with_some_value"), ["a", 1] + ), + HelperRow( + ("column_named_something", "column_with_some_value"), ["a", 2] + ), + HelperRow( + ("column_named_something", "column_with_some_value"), ["a", 3] + ), + HelperRow( + ("column_named_something", "column_with_some_value"), ["a", 4] + ), + HelperRow( + ("column_named_something", "column_with_some_value"), ["b", 3] + ), + HelperRow( + ("column_named_something", "column_with_some_value"), ["b", 4] + ), + HelperRow( + ("column_named_something", "column_with_some_value"), ["b", 5] + ), + HelperRow( + ("column_named_something", "column_with_some_value"), ["b", 6] + ), + HelperRow( + ("column_named_something", "column_with_some_value"), ["b", 7] + ), + ] + ) + assert len(result) == len(expected) + assert result == expected + + @staticmethod + def test_key_mapper_key_value_same(): + with pytest.raises( + MapperError, match="key and value columns cannot be the same" + ): + KeyValueMapper(key_column="same", value_column="same") + + +class HelperRow: # pylint: disable=too-few-public-methods + """ + Helper class does the most basic functionality we see when accessing records passed in + """ + + def __init__(self, fields, values): + self.fields = fields + self.values = values + + def __getitem__(self, key): + if isinstance(key, int): + return self.values[key] + return self.values[self.fields.index(key)] diff --git a/dysql/test/test_mariadbmap_tojson.py b/dysql/test/test_mariadbmap_tojson.py new file mode 100644 --- /dev/null +++ b/dysql/test/test_mariadbmap_tojson.py @@ -0,0 +1,47 @@ +""" +Copyright 2021 Adobe +All Rights Reserved. + +NOTICE: Adobe permits you to use, modify, and distribute this file in accordance +with the terms of the Adobe license agreement accompanying it. +""" + +import json +import pytest + +from dysql import DbMapResult + + +@pytest.mark.parametrize( + "name, expected_json, mariadb_map", + [ + ( + "basic", + '{"id": 1, "name": "test"}', + DbMapResult(id=1, name="test"), + ), + ( + "basic_with_list", + '{"id": 1, "name": "test", "my_list": ["a", "b", "c"]}', + DbMapResult(id=1, name="test", my_list=["a", "b", "c"]), + ), + ( + "inner_map", + '{"id": 1, "inner_map": {"id": 2, "name": "inner_test"}}', + DbMapResult(id=1, inner_map=DbMapResult(id=2, name="inner_test")), + ), + ( + "inner_list_of_maps", + '{"id": 1, "inner_map_list": [{"id": 2, "name": "inner_test_2"}, {"id": 3, "name": "inner_test_3"}]}', + DbMapResult( + id=1, + inner_map_list=[ + DbMapResult(id=2, name="inner_test_2"), + DbMapResult(id=3, name="inner_test_3"), + ], + ), + ), + ], +) +def test_raw_json_format(name, expected_json, mariadb_map): + assert json.dumps(mariadb_map.raw()) == expected_json, "error with " + name diff --git a/dysql/test/test_pydantic_mappers.py b/dysql/test/test_pydantic_mappers.py new file mode 100644 --- /dev/null +++ b/dysql/test/test_pydantic_mappers.py @@ -0,0 +1,291 @@ +""" +Copyright 2021 Adobe +All Rights Reserved. + +NOTICE: Adobe permits you to use, modify, and distribute this file in accordance +with the terms of the Adobe license agreement accompanying it. +""" + +import json +from typing import Any, Dict, List, Set, Optional +import pytest + +from pydantic import ValidationError + +from dysql import ( + RecordCombiningMapper, + SingleRowMapper, +) +from dysql.pydantic_mappers import DbMapResultModel + + +class ConversionDbModel(DbMapResultModel): + id: int + field_str: str + field_int: int + field_bool: bool + + +class CombiningDbModel(DbMapResultModel): + _list_fields: Set[str] = {"list1"} + _set_fields: Set[str] = {"set1"} + _dict_key_fields: Dict[str, str] = {"key1": "dict1", "key2": "dict2"} + _dict_value_mappings: Dict[str, str] = {"dict1": "val1", "dict2": "val2"} + + id: int = None + list1: List[str] + set1: Set[str] = set() + dict1: Dict[str, Any] = {} + dict2: Dict[str, int] = {} + + +class DefaultListCombiningDbModel(CombiningDbModel): + list1: List[str] = [] + + +class ListWithStringsModel(DbMapResultModel): + _csv_list_fields: Set[str] = {"list1", "list2"} + + id: int + list1: Optional[List[str]] = None + list2: List[int] = [] # help test empty list gets filled + + +class JsonModel(DbMapResultModel): + _json_fields: Set[str] = {"json1", "json2"} + + id: int + json1: dict + json2: Optional[dict] = None + + +class MultiKeyModel(DbMapResultModel): + @classmethod + def get_key_columns(cls): + return ["a", "b"] + + _list_fields = {"c"} + a: int + b: str + c: List[str] + + +def _unwrap_results(results): + return [r.raw() for r in results] + + +def test_field_conversion(): + mapper = SingleRowMapper(record_mapper=ConversionDbModel) + assert mapper.map_records( + [ + {"id": 1, "field_str": "str1", "field_int": 1, "field_bool": 1}, + ] + ).raw() == {"id": 1, "field_str": "str1", "field_int": 1, "field_bool": True} + + +def test_complex_object_record_combining(): + mapper = RecordCombiningMapper(record_mapper=CombiningDbModel) + assert len(mapper.map_records([])) == 0 + assert _unwrap_results( + mapper.map_records( + [ + { + "id": 1, + "list1": "val1", + "set1": "val2", + "key1": "k1", + "val1": "v1", + "key2": "k3", + "val2": 3, + }, + {"id": 2, "list1": "val1"}, + { + "id": 1, + "list1": "val3", + "set1": "val4", + "key1": "k2", + "val1": "v2", + "key2": "k4", + "val2": 4, + }, + ] + ) + ) == [ + { + "id": 1, + "list1": ["val1", "val3"], + "set1": {"val2", "val4"}, + "dict1": {"k1": "v1", "k2": "v2"}, + "dict2": {"k3": 3, "k4": 4}, + }, + { + "id": 2, + "list1": ["val1"], + "set1": set(), + "dict1": {}, + "dict2": {}, + }, + ] + + +def test_record_combining_multi_column_id(): + mapper = RecordCombiningMapper(MultiKeyModel) + assert len(mapper.map_records([])) == 0 + assert _unwrap_results( + mapper.map_records( + [ + {"a": 1, "b": "test", "c": "one"}, + {"a": 1, "b": "test", "c": "two"}, + {"a": 1, "b": "test", "c": "three"}, + {"a": 2, "b": "test", "c": "one"}, + {"a": 2, "b": "test", "c": "two"}, + {"a": 1, "b": "othertest", "c": "one"}, + ] + ) + ) == [ + {"a": 1, "b": "test", "c": ["one", "two", "three"]}, + {"a": 2, "b": "test", "c": ["one", "two"]}, + {"a": 1, "b": "othertest", "c": ["one"]}, + ] + + +def test_complex_object_with_null_values(): + mapper = SingleRowMapper(record_mapper=DefaultListCombiningDbModel) + assert mapper.map_records( + [ + {"id": 1}, + ] + ).raw() == { + "id": 1, + "list1": [], + "set1": set(), + "dict1": {}, + "dict2": {}, + } + + +def test_csv_list_field(): + mapper = SingleRowMapper(record_mapper=ListWithStringsModel) + assert mapper.map_records( + [{"id": 1, "list1": "a,b,c,d", "list2": "1,2,3,4"}] + ).raw() == {"id": 1, "list1": ["a", "b", "c", "d"], "list2": [1, 2, 3, 4]} + + +def test_csv_list_field_single_value(): + mapper = SingleRowMapper(record_mapper=ListWithStringsModel) + assert mapper.map_records([{"id": 1, "list1": "a", "list2": "1"}]).raw() == { + "id": 1, + "list1": ["a"], + "list2": [1], + } + + +def test_csv_list_field_empty_string(): + mapper = SingleRowMapper(record_mapper=ListWithStringsModel) + assert mapper.map_records([{"id": 1, "list1": "", "list2": ""}]).raw() == { + "id": 1, + "list1": None, + "list2": [], + } + + +def test_csv_list_field_extends(): + mapper = RecordCombiningMapper(record_mapper=ListWithStringsModel) + assert mapper.map_records( + [ + {"id": 1, "list1": "a,b", "list2": "1,2"}, + {"id": 1, "list1": "c,d", "list2": "3,4"}, + ] + )[0].raw() == {"id": 1, "list1": ["a", "b", "c", "d"], "list2": [1, 2, 3, 4]} + + +def test_csv_list_field_multiple_records_duplicates(): + mapper = RecordCombiningMapper(record_mapper=ListWithStringsModel) + assert mapper.map_records( + [ + {"id": 1, "list1": "a,b,c,d", "list2": "1,2,3,4"}, + {"id": 1, "list1": "a,b,c,d", "list2": "1,2,3,4"}, + ] + )[0].raw() == { + "id": 1, + "list1": ["a", "b", "c", "d", "a", "b", "c", "d"], + "list2": [1, 2, 3, 4, 1, 2, 3, 4], + } + + +def test_csv_list_field_none_in_first_record(): + mapper = RecordCombiningMapper(record_mapper=ListWithStringsModel) + assert mapper.map_records( + [ + {"id": 1, "list1": "a,b,c,d", "list2": None}, + {"id": 1, "list1": "e,f,g", "list2": "1,2,3,4"}, + ] + )[0].raw() == { + "id": 1, + "list1": ["a", "b", "c", "d", "e", "f", "g"], + "list2": [1, 2, 3, 4], + } + + +def test_csv_list_field_without_mapping_ignored(): + mapper = SingleRowMapper(record_mapper=ListWithStringsModel) + assert mapper.map_records( + [{"id": 1, "list1": "a,b, c,d", "list2": "1,2,3,4", "list3": "x,y,z"}] + ).raw() == {"id": 1, "list1": ["a", "b", "c", "d"], "list2": [1, 2, 3, 4]} + + +def test_csv_list_field_invalid_type(): + mapper = RecordCombiningMapper(record_mapper=ListWithStringsModel) + with pytest.raises(ValidationError, match="1 validation error for list"): + mapper.map_records( + [ + {"id": 1, "list1": "a,b", "list2": "1,2"}, + {"id": 1, "list1": "c,d", "list2": "3,a"}, + ] + ) + + +def test_json_field(): + mapper = SingleRowMapper(record_mapper=JsonModel) + assert mapper.map_records( + [ + { + "id": 1, + "json1": json.dumps( + {"a": 1, "b": 2, "c": {"x": 10, "y": 9, "z": {"deep": "value"}}} + ), + } + ] + ).model_dump() == { + "id": 1, + "json1": {"a": 1, "b": 2, "c": {"x": 10, "y": 9, "z": {"deep": "value"}}}, + "json2": None, + } + + +@pytest.mark.parametrize( + "json1, json2", + [ + ('{ "json": value', None), + ('{ "json": value', '{ "json": value }'), + ('{ "json": value }', '{ "json": value'), + (None, '{ "json": value'), + ], +) +def test_invalid_json(json1, json2): + with pytest.raises(ValidationError, match="Invalid JSON"): + mapper = SingleRowMapper(record_mapper=JsonModel) + mapper.map_records([{"id": 1, "json1": json1, "json2": json2}]) + + +def test_json_none(): + mapper = SingleRowMapper(record_mapper=JsonModel) + assert mapper.map_records( + [{"id": 1, "json1": '{ "first": "value" }', "json2": None}] + ).model_dump() == { + "id": 1, + "json1": { + "first": "value", + }, + "json2": None, + } diff --git a/dysql/test/test_sql_decorator.py b/dysql/test/test_sql_decorator.py new file mode 100644 --- /dev/null +++ b/dysql/test/test_sql_decorator.py @@ -0,0 +1,399 @@ +""" +Copyright 2021 Adobe +All Rights Reserved. + +NOTICE: Adobe permits you to use, modify, and distribute this file in accordance +with the terms of the Adobe license agreement accompanying it. +""" + +import pytest + +from dysql import ( + sqlupdate, + sqlquery, + DbMapResult, + CountMapper, + SingleRowMapper, + QueryData, + QueryDataError, +) +from dysql.test import setup_mock_engine + + +class TestSqlSelectDecorator: + """ + Test Sql Select Decorator + """ + + @staticmethod + @pytest.fixture + def mock_results(): + return [ + { + "id": 1, + "name": "jack", + "email": "jack@adobe.com", + "hobbies": ["golf", "bikes", "coding"], + }, + { + "id": 2, + "name": "flora", + "email": "flora@adobe.com", + "hobbies": ["golf", "coding"], + }, + { + "id": 3, + "name": "Terrence", + "email": "terrence@adobe.com", + "hobbies": ["coding", "watching tv", "hot dog eating contest"], + }, + ] + + @staticmethod + @pytest.fixture + def mock_engine(mock_results, mock_create_engine): + mock_engine = setup_mock_engine(mock_create_engine) + mock_engine.connect.return_value.execution_options.return_value.execute.return_value = mock_results + return mock_engine + + @staticmethod + def test_non_query_data_fails(mock_create_engine): + # This argument forces the fixture setup + _ = mock_create_engine + + @sqlquery() + def select_with_string(): + return "SELECT" + + with pytest.raises(QueryDataError): + select_with_string() + + def test_map_not_specified(self, mock_results, mock_engine): + mock_engine.connect.return_value.execution_options.return_value.execute.return_value = mock_results + assert isinstance(list(self._select_all())[0], DbMapResult) + + def test_single(self, mock_results, mock_engine): + mock_engine.connect.return_value.execution_options.return_value.execute.return_value = mock_results + result = self._select_single() + assert isinstance(result, DbMapResult) + + def test_count(self, mock_engine): + mock_engine.connect.return_value.execution_options.return_value.execute.return_value = [ + {"count": 2}, + {"count": 3}, + ] + assert self._select_count() == 2 + + def test_execute_no_params(self, mock_engine): + self._select_all() + mock_engine.connect.return_value.execution_options.return_value.execute.assert_called() + call_args = mock_engine.connect.return_value.execution_options.return_value.execute.call_args + assert call_args[0][0].text == "SELECT * FROM my_table" + assert call_args[0][1] == {} + + def test_execute_params(self, mock_engine): + self._select_filtered(3) + mock_engine.connect.return_value.execution_options.return_value.execute.assert_called() + + call_args = mock_engine.connect.return_value.execution_options.return_value.execute.call_args + assert call_args[0][0].text == "SELECT * FROM my_table WHERE id=:id" + assert call_args[0][1] == {"id": 3} + + def test_list_results_map(self, mock_results, mock_engine): + mock_engine.connect.return_value.execution_options.return_value.execute.return_value = [ + mock_results[2] + ] + results = self._select_filtered(3) + + assert len(results) == 1 + assert len(list(results)[0].hobbies) == 3 + + def test_isolation_default(self, mock_engine): + mock_connect = mock_engine.connect.return_value.execution_options + self._select_all() + mock_connect.assert_called_with(isolation_level="READ_COMMITTED") + + def test_isolation_default_read_uncommited(self, mock_engine): + mock_connect = mock_engine.connect.return_value.execution_options + self._select_uncommitted() + mock_connect.assert_called_with(isolation_level="READ_UNCOMMITTED") + mock_connect.return_value.execute.assert_called() + + @staticmethod + @sqlquery() + def _select_all(): + """ + method is static just to help show you can use static methods if + you don't want to instantiate an instance of the class + """ + return QueryData("SELECT * FROM my_table") + + @staticmethod + @sqlquery(mapper=SingleRowMapper()) + def _select_single(): + return QueryData("SELECT * FROM my_table") + + @staticmethod + @sqlquery(mapper=CountMapper) + def _select_count(): + return QueryData("SELECT COUNT(*) FROM my_table") + + @staticmethod + @sqlquery() + def _select_filtered(_id): + return QueryData( + "SELECT * FROM my_table WHERE id=:id", query_params={"id": _id} + ) + + @staticmethod + @sqlquery(isolation_level="READ_UNCOMMITTED") + def _select_uncommitted(): + return QueryData("SELECT * FROM uncommitted") + + +class TestSqlUpdateDecorator: + """ + Test Sql Update Decorator + """ + + @staticmethod + @pytest.fixture + def mock_engine(mock_create_engine): + return setup_mock_engine(mock_create_engine) + + @staticmethod + @pytest.fixture + def mock_connect(mock_engine): + return mock_engine.connect.return_value.execution_options + + def test_isolation_default(self, mock_connect): + self._update_something({"id": 1, "value": "test"}) + mock_connect.assert_called_with(isolation_level="READ_COMMITTED") + + def test_isolation_default_read_uncommited(self, mock_connect): + self._update_something_uncommited_isolation({"id": 1, "value": "test"}) + mock_connect.assert_called_with(isolation_level="READ_UNCOMMITTED") + mock_connect.return_value.begin.assert_called() + mock_connect.return_value.begin.return_value.commit.assert_called() + mock_connect.return_value.__exit__.assert_called() + + def test_transaction(self, mock_connect): + self._update_something({"id": 1, "value": "test"}) + mock_connect().begin.assert_called() + mock_connect().begin.return_value.commit.assert_called() + mock_connect().__exit__.assert_called() + + def test_transaction_fails(self, mock_connect): + mock_connect().execute.side_effect = Exception("error") + with pytest.raises(Exception): + self._update_something({"id": 1, "value": "test"}) + mock_connect().begin.return_value.commit.assert_not_called() + mock_connect().begin.return_value.rollback.assert_called() + mock_connect().__exit__.assert_called() + + def test_execute_passes_values(self, mock_engine): + values = {"id": 1, "value": "test"} + self._update_something(values) + + execute_call = ( + mock_engine.connect.return_value.execution_options.return_value.execute + ) + execute_call.assert_called() + + execute_call_args = execute_call.call_args[0] + assert execute_call_args[0].text == "INSERT something" + assert values == execute_call_args[1] + + def test_execute_query_values_none(self, mock_engine): + self._update_something(None) + + execute_call = ( + mock_engine.connect.return_value.execution_options.return_value.execute + ) + execute_call.assert_called() + + self._expect_args_list(execute_call.call_args_list[0], "INSERT something") + + def test_execute_query_values_not_given(self, mock_engine): + # pylint: disable=unused-argument + self._update_something_no_params() + + def test_execute_multi_yield(self, mock_connect): + expected_values = [ + {"id": 1, "value": "test 1"}, + {"id": 2, "value": "test 2"}, + {"id": 3, "value": "test 3"}, + ] + self._update_something_multi_yield(expected_values) + + execute_call = mock_connect().execute + assert execute_call.call_count == 3 + + for call_args in execute_call.call_args_list: + self._expect_args_list(call_args, "INSERT something") + + def test_execute_fails_list_if_multi_false(self): + expected_values = [ + {"id": 1, "value": "test 1"}, + {"id": 2, "value": "test 2"}, + {"id": 3, "value": "test 3"}, + ] + with pytest.raises(Exception): + self._update_list_when_multi_false(expected_values) + + def test_execute_multi_yield_and_lists(self, mock_engine): + expected_values = [ + {"id": 1, "value": "test 1"}, + {"id": 2, "value": "test 2"}, + {"id": 3, "value": "test 3"}, + ] + other_expected_values = [ + {"id": 5, "value": "test 5"}, + {"id": 6, "value": "test 6"}, + {"id": 7, "value": "test 7"}, + ] + self._update_yield_with_lists(expected_values, other_expected_values) + + execute_call = ( + mock_engine.connect.return_value.execution_options.return_value.execute + ) + assert execute_call.call_count == 2 + + self._expect_args_list( + execute_call.call_args_list[0], + "INSERT some VALUES ( :values__in_0_0, :values__in_0_1 ), ( :values__in_1_0, :values__in_1_1 ), " + "( :values__in_2_0, :values__in_2_1 ) ", + ) + self._expect_args_list( + execute_call.call_args_list[1], + "INSERT some more VALUES ( :values__other_0_0, :values__other_0_1 ), " + "( :values__other_1_0, :values__other_1_1 ), ( :values__other_2_0, :values__other_2_1 ) ", + ) + + def test_execute_multi_yield_and_lists_some_no_params(self, mock_engine): + expected_values = [ + {"id": 1, "value": "test 1"}, + {"id": 2, "value": "test 2"}, + {"id": 3, "value": "test 3"}, + ] + self._update_yield_with_lists_some_no_params(expected_values) + + execute_call = ( + mock_engine.connect.return_value.execution_options.return_value.execute + ) + assert execute_call.call_count == 4 + + self._expect_args_list( + execute_call.call_args_list[0], + "INSERT some VALUES ( :values__in_0_0, :values__in_0_1 ), ( :values__in_1_0, :values__in_1_1 ), " + "( :values__in_2_0, :values__in_2_1 ) ", + ) + self._expect_args_list(execute_call.call_args_list[1], "UPDATE some more") + self._expect_args_list(execute_call.call_args_list[2], "UPDATE some more") + self._expect_args_list(execute_call.call_args_list[3], "DELETE some more") + + def test_set_foreign_key_checks_default(self, mock_engine): + self._update_something_no_params() + + execute_call = ( + mock_engine.connect.return_value.execution_options.return_value.execute + ) + assert execute_call.call_count == 1 + + def test_set_foreign_key_checks_true(self, mock_engine): + self._update_without_foreign_key_checks() + + execute_call = ( + mock_engine.connect.return_value.execution_options.return_value.execute + ) + assert execute_call.call_count == 4 + assert execute_call.call_args_list[0][0][0].text == "SET FOREIGN_KEY_CHECKS=0" + assert execute_call.call_args_list[-1][0][0].text == "SET FOREIGN_KEY_CHECKS=1" + + @staticmethod + def _expect_args_list(call_args, expected_query): + assert expected_query == call_args[0][0].text + + @staticmethod + @sqlupdate(disable_foreign_key_checks=True) + def _update_without_foreign_key_checks(): + yield QueryData("INSERT B_RELIES_ON_A") + yield QueryData("INSERT A") + + @staticmethod + @sqlupdate() + def _update_something(values): + return QueryData("INSERT something", query_params=values) + + @staticmethod + @sqlupdate(isolation_level="READ_UNCOMMITTED") + def _update_something_uncommited_isolation(values): + return QueryData(f"INSERT WITH uncommitted {values}") + + @staticmethod + @sqlupdate() + def _update_something_no_params(): + return QueryData("INSERT something") + + @staticmethod + @sqlupdate() + def _update_something_multi_yield(multiple_values): + for values in multiple_values: + yield QueryData("INSERT something", query_params=values) + + @staticmethod + @sqlupdate() + def _update_something_return_list(multiple_values): + return QueryData("INSERT something", query_params=multiple_values) + + @staticmethod + @sqlupdate() + def _update_list_when_multi_false(multiple_values): + return "INSERT something", multiple_values + + @staticmethod + @sqlupdate() + def _update_yield_with_lists(multiple_values, other_values): + """ + method is static just to help show you can use static methods if + you don't want to instantiate an instance of the class + + NOTE: + """ + yield QueryData( + "INSERT some {values__in}", + template_params=_get_template_params("values__in", multiple_values), + ) + yield QueryData( + "INSERT some more {values__other}", + template_params=_get_template_params("values__other", other_values), + ) + + @staticmethod + @sqlupdate() + def _update_yield_with_lists_some_no_params(multiple_values): + """ + method is static just to help show you can use static methods if + you don't want to instantiate an instance of the class + """ + yield QueryData( + "INSERT some {values__in}", + template_params=_get_template_params("values__in", multiple_values), + ) + yield QueryData("UPDATE some more") + yield QueryData("UPDATE some more") + yield QueryData("DELETE some more") + + +def _get_template_params(key, values): + """ + template parameters is handled here as an example of what you might end up + doing. usually data coming in is going to be a list + + :param key: the template key we want to use to build our template with + :param values: the list of objects or mariadbmaps, + :return: a keyed list of tuples or mariadbmaps + """ + if isinstance(values[0], DbMapResult): + return {key: values} + return {key: [(v["id"], v["value"]) for v in values]} diff --git a/dysql/test/test_sql_exists_decorator.py b/dysql/test/test_sql_exists_decorator.py new file mode 100644 --- /dev/null +++ b/dysql/test/test_sql_exists_decorator.py @@ -0,0 +1,165 @@ +""" +Copyright 2021 Adobe +All Rights Reserved. + +NOTICE: Adobe permits you to use, modify, and distribute this file in accordance +with the terms of the Adobe license agreement accompanying it. +""" + +from unittest.mock import Mock + +import pytest + +from dysql import sqlexists, QueryData +from dysql.test import setup_mock_engine + + +TRUE_QUERY = "SELECT 1 from table" +TRUE_QUERY_PARAMS = "SELECT 1 from table where key=:key" +FALSE_QUERY = "SELECT 1 from false_table " +FALSE_QUERY_PARAMS = "SELECT 1 from table where key=:key" +TRUE_PARAMS = {"key": 123} +FALSE_PARAMS = {"key": 456} +SELECT_EXISTS_QUERY = "SELECT 1 WHERE EXISTS ( {} )" +SELECT_EXISTS_NO_WHERE_QUERY = "SELECT EXISTS ( {} )" +EXISTS_QUERIES = { + "true": SELECT_EXISTS_QUERY.format(TRUE_QUERY), + "false": SELECT_EXISTS_QUERY.format(FALSE_QUERY), + "true_params": SELECT_EXISTS_QUERY.format(TRUE_QUERY_PARAMS), + "false_params": SELECT_EXISTS_QUERY.format(FALSE_QUERY_PARAMS), + "true_no_where": SELECT_EXISTS_NO_WHERE_QUERY.format(TRUE_QUERY), + "false_no_where": SELECT_EXISTS_NO_WHERE_QUERY.format(FALSE_QUERY), +} + + +@pytest.fixture(autouse=True) +def mock_engine_fixture(mock_create_engine): + mock_engine = setup_mock_engine(mock_create_engine) + mock_engine.connect.return_value.execution_options.return_value.execute.side_effect = _check_query_and_return_result + mock_engine.connect().execution_options().__enter__ = Mock() + mock_engine.connect().execution_options().__exit__ = Mock() + + +def test_exists_true(): + assert _exists_true() + + +def test_exists_false(): + assert not _exists_false() + + +def test_exists_true_params(): + assert _exists_true_params() + + +def test_exists_false_params(): + assert not _exists_false_params() + + +def test_exists_query_contains_with_exists_true(): + """ + this helps to test that if someone adds an exists statement, we don't add the exists + exists(exists()) will always give a 'true' result + """ + # should match against the same query, should still match + assert _exists_specified("true") + + +def test_exists_query_contains_with_exists_false(): + """ + this helps to test that if someone adds an exists statement, we don't add the exists + exists(exists()) will always give a 'true' result + """ + # should match against the same query, should still match + assert not _exists_specified("false") + + +def test_exists_without_where_true(): + """ + this helps avoid an issue discovered when using the 'utf8' charset, some queries with the exists + query would fail to decode the '0' returned with a query as just `SELECT EXISTS` but work as expected + when using `SELECT 1 WHERE EXISTS` + """ + assert _select_exists_no_where_true() + + +def test_exists_witohut_where_false(): + """ + this helps avoid an issue discovered when using the 'utf8' charset, some queries with the exists + query would fail to decode the '0' returned with a query as just `SELECT EXISTS` but work as expected + when using `SELECT 1 WHERE EXISTS` + """ + assert not _select_exists_no_where_false() + + +def test_exists_query_starts_with_exists_handles_whitespace(): + """ + this helps to test that if someone adds an exists statement, we don't add the exists + exists(exists()) will always give a 'true' result + """ + # should trim the whitespace and match appropiately + assert _exists_whitespace() + + +@sqlexists() +def _select_exists_no_where_false(): + return QueryData(EXISTS_QUERIES["false_no_where"]) + + +@sqlexists() +def _select_exists_no_where_true(): + return QueryData(EXISTS_QUERIES["true_no_where"]) + + +@sqlexists() +def _exists_specified(key): + return QueryData(EXISTS_QUERIES[key]) + + +@sqlexists() +def _exists_true(): + return QueryData(TRUE_QUERY) + + +@sqlexists() +def _exists_false(): + return QueryData(FALSE_QUERY) + + +@sqlexists() +def _exists_true_params(): + return QueryData(TRUE_QUERY, TRUE_PARAMS) + + +@sqlexists() +def _exists_false_params(): + return QueryData(FALSE_QUERY, FALSE_PARAMS) + + +@sqlexists() +def _exists_whitespace(): + return QueryData( + """ + """ + + TRUE_QUERY + ) + + +def _check_query_and_return_result(query, params): + """ + check that the query matches our expectations + and then set the return value for the scalar call. + scalar() returns either 1 or 0, 1 for true, 0 for false + """ + assert query.text in list(EXISTS_QUERIES.values()) + scalar_mock = Mock() + # default mock responses to true, then we only handle setting false responses + scalar_mock.scalar.return_value = 1 + if query.text == EXISTS_QUERIES["true_params"]: + assert params.get("key") == 123 + if query.text == EXISTS_QUERIES["false_params"]: + assert params.get("key") == 456 + scalar_mock.scalar.return_value = 0 + elif query.text == EXISTS_QUERIES["false"]: + scalar_mock.scalar.return_value = 0 + return scalar_mock diff --git a/dysql/test/test_sql_in_list_templates.py b/dysql/test/test_sql_in_list_templates.py new file mode 100644 --- /dev/null +++ b/dysql/test/test_sql_in_list_templates.py @@ -0,0 +1,289 @@ +""" +Copyright 2021 Adobe +All Rights Reserved. + +NOTICE: Adobe permits you to use, modify, and distribute this file in accordance +with the terms of the Adobe license agreement accompanying it. +""" + +# pylint: disable=too-many-public-methods +import pytest + +import dysql +from dysql import QueryData, sqlquery +from dysql.test import ( + verify_query, + verify_query_args, + verify_query_params, + setup_mock_engine, +) + + +@pytest.fixture(name="mock_engine", autouse=True) +def mock_engine_fixture(mock_create_engine): + mock_engine = setup_mock_engine(mock_create_engine) + mock_engine.connect().execution_options().execute.side_effect = lambda x, y: [] + return mock_engine + + +def test_list_in_numbers(mock_engine): + _query( + "SELECT * FROM table WHERE {in__column_a}", + template_params={"in__column_a": [1, 2, 3, 4]}, + ) + verify_query_params( + mock_engine, + "SELECT * FROM table WHERE column_a IN ( :in__column_a_0, :in__column_a_1, :in__column_a_2, :in__column_a_3 ) ", + { + "in__column_a_0": 1, + "in__column_a_1": 2, + "in__column_a_2": 3, + "in__column_a_3": 4, + }, + ) + + +def test_list_in__strings(mock_engine): + _query( + "SELECT * FROM table WHERE {in__column_a}", + template_params={"in__column_a": ["a", "b", "c", "d"]}, + ) + verify_query_params( + mock_engine, + "SELECT * FROM table WHERE column_a IN ( :in__column_a_0, :in__column_a_1, :in__column_a_2, :in__column_a_3 ) ", + { + "in__column_a_0": "a", + "in__column_a_1": "b", + "in__column_a_2": "c", + "in__column_a_3": "d", + }, + ) + + +def test_list_not_in_numbers(mock_engine): + _query( + "SELECT * FROM table WHERE {not_in__column_b}", + template_params={"not_in__column_b": [1, 2, 3, 4]}, + ) + verify_query_params( + mock_engine, + "SELECT * FROM table WHERE column_b NOT IN ( :not_in__column_b_0, :not_in__column_b_1, " + ":not_in__column_b_2, :not_in__column_b_3 ) ", + { + "not_in__column_b_0": 1, + "not_in__column_b_1": 2, + "not_in__column_b_2": 3, + "not_in__column_b_3": 4, + }, + ) + + +def test_list_not_in_strings(mock_engine): + _query( + "SELECT * FROM table WHERE {not_in__column_b}", + template_params={"not_in__column_b": ["a", "b", "c", "d"]}, + ) + verify_query_params( + mock_engine, + "SELECT * FROM table WHERE column_b NOT IN ( :not_in__column_b_0, :not_in__column_b_1, " + ":not_in__column_b_2, :not_in__column_b_3 ) ", + { + "not_in__column_b_0": "a", + "not_in__column_b_1": "b", + "not_in__column_b_2": "c", + "not_in__column_b_3": "d", + }, + ) + + +def test_list_in_handles_empty(mock_engine): + _query( + "SELECT * FROM table WHERE {in__column_a}", template_params={"in__column_a": []} + ) + verify_query(mock_engine, "SELECT * FROM table WHERE 1 <> 1 ") + + +def test_list_in_handles_no_param(): + with pytest.raises( + dysql.query_utils.ListTemplateException, match="['in__column_a']" + ): + _query("SELECT * FROM table WHERE {in__column_a}") + + +def test_list_in_multiple_lists(mock_engine): + _query( + "SELECT * FROM table WHERE {in__column_a} OR {in__column_b}", + template_params={"in__column_a": ["first", "second"], "in__column_b": [1, 2]}, + ) + verify_query( + mock_engine, + "SELECT * FROM table WHERE column_a IN ( :in__column_a_0, :in__column_a_1 ) " + "OR column_b IN ( :in__column_b_0, :in__column_b_1 ) ", + ) + + +def test_list_in_multiple_lists_one_empty(mock_engine): + _query( + "SELECT * FROM table WHERE {in__column_a} OR {in__column_b}", + template_params={"in__column_a": ["first", "second"], "in__column_b": []}, + ) + verify_query( + mock_engine, + "SELECT * FROM table WHERE column_a IN ( :in__column_a_0, :in__column_a_1 ) OR 1 <> 1 ", + ) + + +def test_list_in_multiple_lists_one_missing(): + with pytest.raises( + dysql.query_utils.ListTemplateException, match="['in__column_a']" + ): + _query( + "SELECT * FROM table WHERE {in__column_a} OR {in__column_b} ", + template_params={"in__column_b": [1, 2]}, + ) + + +def test_list_in_multiple_lists_all_missing(): + with pytest.raises( + dysql.query_utils.ListTemplateException, match="['in__column_a','in__column_b']" + ): + _query("SELECT * FROM table WHERE {in__column_a} OR {in__column_b} ") + + +def test_list_not_in_handles_empty(mock_engine): + _query( + "SELECT * FROM table WHERE {not_in__column_b}", + template_params={"not_in__column_b": []}, + ) + verify_query(mock_engine, "SELECT * FROM table WHERE 1 = 1 ") + + +def test_list_not_in_handles_no_param(): + with pytest.raises( + dysql.query_utils.ListTemplateException, match="['not_in__column_b']" + ): + _query("SELECT * FROM table WHERE {not_in__column_b} ") + + +def test_list_gives_template_space_before(mock_engine): + _query( + "SELECT * FROM table WHERE{in__space}", template_params={"in__space": [9, 8]} + ) + verify_query( + mock_engine, + "SELECT * FROM table WHERE space IN ( :in__space_0, :in__space_1 ) ", + ) + + +def test_list_gives_template_space_after(mock_engine): + _query( + "SELECT * FROM table WHERE {in__space}AND other_condition = 1", + template_params={"in__space": [9, 8]}, + ) + verify_query( + mock_engine, + "SELECT * FROM table WHERE space IN ( :in__space_0, :in__space_1 ) AND other_condition = 1", + ) + + +def test_list_gives_template_space_before_and_after(mock_engine): + _query( + "SELECT * FROM table WHERE{in__space}AND other_condition = 1", + template_params={"in__space": [9, 8]}, + ) + verify_query( + mock_engine, + "SELECT * FROM table WHERE space IN ( :in__space_0, :in__space_1 ) AND other_condition = 1", + ) + + +def test_in_contains_whitespace(mock_engine): + _query("{in__column_one}", template_params={"in__column_one": [1, 2]}) + verify_query( + mock_engine, " column_one IN ( :in__column_one_0, :in__column_one_1 ) " + ) + + +def test_template_handles_table_qualifier(mock_engine): + """ + when the table is specified with a dot separator, we need to split the table out of the + keyword and the keyword passed in should be passed in without the keyword + + {in__table.column} -> {table}.{in__column} -> table.column IN (:in__column_0, :in__column_1) + :return: + """ + _query( + "SELECT * FROM table WHERE {in__table.column}", + template_params={"in__table.column": [1, 2]}, + ) + verify_query( + mock_engine, + "SELECT * FROM table WHERE table.column IN ( :in__table_column_0, :in__table_column_1 ) ", + ) + verify_query_args(mock_engine, {"in__table_column_0": 1, "in__table_column_1": 2}) + + +def test_template_handles_multiple_table_qualifier(mock_engine): + _query( + "SELECT * FROM table WHERE {in__table.column} AND {not_in__other_column}", + template_params={ + "in__table.column": [1, 2], + "not_in__other_column": ["a", "b"], + }, + ) + verify_query( + mock_engine, + "SELECT * FROM table WHERE table.column IN ( :in__table_column_0, :in__table_column_1 ) " + "AND other_column NOT IN ( :not_in__other_column_0, :not_in__other_column_1 ) ", + ) + verify_query_args( + mock_engine, + { + "in__table_column_0": 1, + "in__table_column_1": 2, + "not_in__other_column_0": "a", + "not_in__other_column_1": "b", + }, + ) + + +def test_empty_in_contains_whitespace(mock_engine): + _query("{in__column_one}", template_params={"in__column_one": []}) + verify_query(mock_engine, " 1 <> 1 ") + + +def test_multiple_templates_same_column_diff_table(mock_engine): + template_params = { + "in__table.status": ["on", "off", "waiting"], + "in__other_table.status": ["success", "partial_success"], + } + expected_params_from_template = { + "in__table_status_0": "on", + "in__table_status_1": "off", + "in__table_status_2": "waiting", + "in__other_table_status_0": "success", + "in__other_table_status_1": "partial_success", + } + + # writing each of these queries out to help see what we expect compared to + # the query we actually sent + _query( + "SELECT * FROM table WHERE {in__table.status} AND {in__other_table.status}", + template_params=template_params, + ) + expected_query = ( + "SELECT * FROM table WHERE table.status IN ( :in__table_status_0, :in__table_status_1, " + ":in__table_status_2 ) AND other_table.status IN ( :in__other_table_status_0, " + ":in__other_table_status_1 ) " + ) + + connection = mock_engine.connect.return_value.execution_options.return_value + execute_call = connection.execute + execute_call.assert_called_once() + assert execute_call.call_args[0][0].text == expected_query + assert execute_call.call_args[0][1] == expected_params_from_template + + +@sqlquery() +def _query(query, query_params=None, template_params=None): + return QueryData(query, query_params=query_params, template_params=template_params) diff --git a/dysql/test/test_sql_insert_templates.py b/dysql/test/test_sql_insert_templates.py new file mode 100644 --- /dev/null +++ b/dysql/test/test_sql_insert_templates.py @@ -0,0 +1,174 @@ +""" +Copyright 2021 Adobe +All Rights Reserved. + +NOTICE: Adobe permits you to use, modify, and distribute this file in accordance +with the terms of the Adobe license agreement accompanying it. +""" + +import pytest + +import dysql +from dysql import QueryData, sqlupdate, QueryDataError +from dysql.test import ( + verify_query, + verify_query_args, + setup_mock_engine, +) + + +@pytest.fixture(name="mock_engine", autouse=True) +def mock_engine_fixture(mock_create_engine): + initial_id = 0 + + def handle_execute(query=None, args=None): + nonlocal initial_id + if "INSERT INTO get_last(name)" in query.text: + initial_id += 1 + if "SELECT LAST_INSERT_ID()" == query.text: + return type("Result", (), {"scalar": lambda: initial_id}) + return [] + + mock_engine = setup_mock_engine(mock_create_engine) + execute_mock = mock_engine.connect().execution_options().execute + execute_mock.side_effect = handle_execute + return mock_engine + + +def test_insert_non_query_data_fails(): + @sqlupdate() + def select_with_string(): + return "INSERT" + + with pytest.raises(QueryDataError): + select_with_string() + + +def test_insert_single_column(mock_engine): + insert_into_single_value(["Tom", "Jerry"]) + verify_query( + mock_engine, + "INSERT INTO table(name) VALUES ( :values__name_col_0 ), ( :values__name_col_1 ) ", + ) + + +def test_insert_single_column_single_value(mock_engine): + insert_into_single_value("Tom") + verify_query(mock_engine, "INSERT INTO table(name) VALUES ( :values__name_col_0 ) ") + + +def test_insert_single_value_empty(): + with pytest.raises( + dysql.query_utils.ListTemplateException, match="['values_name_col']" + ): + insert_into_single_value([]) + + +def test_insert_single_value_no_key(): + with pytest.raises( + dysql.query_utils.ListTemplateException, match="['values_name_col']" + ): + insert_into_single_value(None) + + +def test_insert_multiple_values(mock_engine): + insert_into_multiple_values( + [ + {"name": "Tom", "email": "tom@adobe.com"}, + {"name": "Jerry", "email": "jerry@adobe.com"}, + ] + ) + verify_query( + mock_engine, + "INSERT INTO table(name, email) VALUES ( :values__users_0_0, :values__users_0_1 ), " + "( :values__users_1_0, :values__users_1_1 ) ", + ) + verify_query_args( + mock_engine, + { + "values__users_0_0": "Tom", + "values__users_0_1": "tom@adobe.com", + "values__users_1_0": "Jerry", + "values__users_1_1": "jerry@adobe.com", + }, + ) + + +@pytest.mark.parametrize( + "args", + [ + ([("bob", "bob@email.com")]), + ([("bob", "bob@email.com"), ("tom", "tom@email.com")]), + None, + (), + ], +) +def test_insert_with_callback(args): + def callback(items): + assert items == args + + @sqlupdate(on_success=callback) + def insert(items): + yield QueryData(f"INSERT INTO table(name, email) {items}") + + insert(args) + + +def test_insert_with_callack_not_called(mock_engine): + def callback(): + assert False + + @sqlupdate(on_success=callback) + def insert(): + yield QueryData("INSERT INTO table(name, email)") + + mock_engine.connect().execution_options.return_value.execute.side_effect = ( + Exception() + ) + with pytest.raises(Exception): + insert() + + +@sqlupdate() +def insert_into_multiple_values(users): + yield QueryData( + "INSERT INTO table(name, email) {values__users}", + template_params={"values__users": [(d["name"], d["email"]) for d in users]}, + ) + + +@sqlupdate() +def insert_into_single_value(names): + template_params = {} + if names is not None: + template_params = {"values__name_col": names} + + return QueryData( + "INSERT INTO table(name) {values__name_col}", template_params=template_params + ) + + +def test_last_insert_id(): + @sqlupdate() + def insert(get_last_insert_id=None): + yield QueryData("INSERT INTO get_last(name) VALUES ('Tom')") + assert get_last_insert_id + assert get_last_insert_id() == 1 + yield QueryData("INSERT INTO get_last(name) VALUES ('Jerry')") + assert get_last_insert_id() == 2 + + insert() + + +def test_last_insert_id_removed_before_callback(): + def callback(**kwargs): + assert "get_last_insert_id" not in kwargs + + @sqlupdate() + def insert(get_last_insert_id=None): + assert get_last_insert_id + yield QueryData("INSERT INTO get_last(name) VALUES ('Tom')") + yield QueryData("INSERT INTO get_last(name) VALUES ('Jerry')") + assert get_last_insert_id() == 2 + + insert() diff --git a/dysql/test/test_template_generators.py b/dysql/test/test_template_generators.py new file mode 100644 --- /dev/null +++ b/dysql/test/test_template_generators.py @@ -0,0 +1,222 @@ +""" +Copyright 2021 Adobe +All Rights Reserved. + +NOTICE: Adobe permits you to use, modify, and distribute this file in accordance +with the terms of the Adobe license agreement accompanying it. +""" + +import pytest + +from dysql.query_utils import TemplateGenerators, ListTemplateException + + +class TestTemplatesGenerators: + """ + Test we get templates back from Templates + """ + + number_values = [1, 2, 3, 4] + string_values = ["1", "2", "3", "4"] + set_values = {1, 2, 3, 4} + insert_values = [("ironman", 1), ("batman", 2)] + tuple_values = [(1, 2), (3, 4)] + query = "column_a IN ( :column_a_0, :column_a_1, :column_a_2, :column_a_3 )" + + query_with_list_of_tuples = ( + "(column_a, column_b) IN (( :column_acolumn_b_0_0, :column_acolumn_b_0_1 ), " + "( :column_acolumn_b_1_0, :column_acolumn_b_1_1 ))" + ) + not_query_with_list_of_tuples = ( + "(column_a, column_b) NOT IN (( :column_acolumn_b_0_0, :column_acolumn_b_0_1 ), " + "( :column_acolumn_b_1_0, :column_acolumn_b_1_1 ))" + ) + query_with_table = "table.column_a IN ( :table_column_a_0, :table_column_a_1, :table_column_a_2, :table_column_a_3 )" + not_query = "column_a NOT IN ( :column_a_0, :column_a_1, :column_a_2, :column_a_3 )" + not_query_with_table = "table.column_a NOT IN ( :table_column_a_0, :table_column_a_1, :table_column_a_2, :table_column_a_3 )" + + test_query_data = ( + "template_function, column_name,column_values,expected_query", + [ + (TemplateGenerators.in_column, "column_a", number_values, query), + ( + TemplateGenerators.in_column, + "table.column_a", + number_values, + query_with_table, + ), + ( + TemplateGenerators.in_column, + "table.column_a", + set_values, + query_with_table, + ), + (TemplateGenerators.in_column, "column_a", string_values, query), + ( + TemplateGenerators.in_column, + "table.column_a", + string_values, + query_with_table, + ), + (TemplateGenerators.in_column, "column_a", [], "1 <> 1"), + ( + TemplateGenerators.in_multi_column, + "(column_a, column_b)", + tuple_values, + query_with_list_of_tuples, + ), + ( + TemplateGenerators.not_in_multi_column, + "(column_a, column_b)", + tuple_values, + not_query_with_list_of_tuples, + ), + (TemplateGenerators.not_in_column, "column_a", number_values, not_query), + ( + TemplateGenerators.not_in_column, + "table.column_a", + number_values, + not_query_with_table, + ), + (TemplateGenerators.not_in_column, "column_a", string_values, not_query), + ( + TemplateGenerators.not_in_column, + "table.column_a", + string_values, + not_query_with_table, + ), + ( + TemplateGenerators.not_in_column, + "table.column_a", + set_values, + not_query_with_table, + ), + (TemplateGenerators.not_in_column, "column_a", [], "1 = 1"), + ( + TemplateGenerators.values, + "someid", + insert_values, + "VALUES ( :someid_0_0, :someid_0_1 ), ( :someid_1_0, :someid_1_1 )", + ), + ], + ) + + parameter_numbers = { + "column_a_0": number_values[0], + "column_a_1": number_values[1], + "column_a_2": number_values[2], + "column_a_3": number_values[3], + } + with_table_parameter_numbers = { + "table_column_a_0": number_values[0], + "table_column_a_1": number_values[1], + "table_column_a_2": number_values[2], + "table_column_a_3": number_values[3], + } + parameter_strings = { + "column_a_0": string_values[0], + "column_a_1": string_values[1], + "column_a_2": string_values[2], + "column_a_3": string_values[3], + } + with_table_parameter_strings = { + "table_column_a_0": string_values[0], + "table_column_a_1": string_values[1], + "table_column_a_2": string_values[2], + "table_column_a_3": string_values[3], + } + test_params_data = ( + "template_function, column_name,column_values,expected_params", + [ + ( + TemplateGenerators.in_column, + "column_a", + number_values, + parameter_numbers, + ), + ( + TemplateGenerators.in_column, + "column_a", + set_values, + parameter_numbers, + ), + ( + TemplateGenerators.in_column, + "table.column_a", + number_values, + with_table_parameter_numbers, + ), + ( + TemplateGenerators.in_column, + "column_a", + string_values, + parameter_strings, + ), + ( + TemplateGenerators.in_column, + "table.column_a", + string_values, + with_table_parameter_strings, + ), + (TemplateGenerators.in_column, "column_a", [], None), + ( + TemplateGenerators.not_in_column, + "column_a", + number_values, + parameter_numbers, + ), + ( + TemplateGenerators.not_in_column, + "table.column_a", + number_values, + with_table_parameter_numbers, + ), + ( + TemplateGenerators.not_in_column, + "column_a", + string_values, + parameter_strings, + ), + ( + TemplateGenerators.not_in_column, + "column_a", + set_values, + parameter_numbers, + ), + ( + TemplateGenerators.not_in_column, + "table.column_a", + string_values, + with_table_parameter_strings, + ), + (TemplateGenerators.not_in_column, "column_a", [], None), + ( + TemplateGenerators.values, + "someid", + insert_values, + { + "someid_0_0": insert_values[0][0], + "someid_0_1": insert_values[0][1], + "someid_1_0": insert_values[1][0], + "someid_1_1": insert_values[1][1], + }, + ), + ], + ) + + @staticmethod + @pytest.mark.parametrize(*test_query_data) + def test_query(template_function, column_name, column_values, expected_query): + query, _ = template_function(column_name, column_values) + assert query == expected_query + + @staticmethod + @pytest.mark.parametrize(*test_params_data) + def test_params(template_function, column_name, column_values, expected_params): + _, params = template_function(column_name, column_values) + assert params == expected_params + + @staticmethod + def test_insert_none(): + with pytest.raises(ListTemplateException): + TemplateGenerators.values("someid", None) diff --git a/dysql/test/test_test_managers.py b/dysql/test/test_test_managers.py new file mode 100644 --- /dev/null +++ b/dysql/test/test_test_managers.py @@ -0,0 +1,76 @@ +""" +Copyright 2026 Adobe +All Rights Reserved. + +NOTICE: Adobe permits you to use, modify, and distribute this file in accordance +with the terms of the Adobe license agreement accompanying it. +""" + +import pytest +from unittest.mock import patch + +from dysql.test_managers import MariaDbTestManager + + +class TestMariaDbTestManager: + """ + Tests for MariaDbTestManager + """ + + @patch.object(MariaDbTestManager, "_run") + def test_create_test_db_without_schema(self, mock_run): + """Test that _create_test_db works without a schema_db_name""" + manager = MariaDbTestManager(db_name="test_db") + manager._create_test_db() + + # Should have called _run twice (DROP and CREATE) + assert mock_run.call_count == 2 + + # Verify DROP command + drop_call = mock_run.call_args_list[0] + assert "DROP DATABASE IF EXISTS test_db" in drop_call[0][0] + + # Verify CREATE command + create_call = mock_run.call_args_list[1] + assert "CREATE DATABASE IF NOT EXISTS test_db" in create_call[0][0] + + @patch.object(MariaDbTestManager, "_run") + @pytest.mark.parametrize("command", ["--no-data", "--routines", "source_db"]) + def test_create_test_includes_commands(self, mock_run, command): + """Test that _create_test_db includes --routines flag when copying schema""" + manager = MariaDbTestManager(db_name="test_db", schema_db_name="source_db") + manager._create_test_db() + + # Should have called _run three times (DROP, CREATE, and mysqldump) + assert mock_run.call_count == 3 + + # Verify mysqldump command includes command + mysqldump_call = mock_run.call_args_list[2] + mysqldump_command = mysqldump_call[0][0] + + assert "mariadb-dump" in mysqldump_command + assert command in mysqldump_command + + @patch.object(MariaDbTestManager, "_run") + def test_create_test_db_mysqldump_command_format(self, mock_run): + """Test the exact format of the mysqldump command""" + manager = MariaDbTestManager(db_name="test_db", schema_db_name="source_db") + manager._create_test_db() + + mysqldump_call = mock_run.call_args_list[2] + mysqldump_command = mysqldump_call[0][0] + + # Verify the command has the correct structure + # mysqldump --no-data --routines -p{password} {schema_db_name} -h{host} | mariadb ... + assert "| mariadb" in mysqldump_command + assert "test_db" in mysqldump_command + + @patch.object(MariaDbTestManager, "_run") + def test_tear_down_test_db(self, mock_run): + """Test that _tear_down_test_db drops the database""" + manager = MariaDbTestManager(db_name="test_db") + manager._tear_down_test_db() + + assert mock_run.call_count == 1 + drop_call = mock_run.call_args_list[0] + assert "DROP DATABASE IF EXISTS test_db" in drop_call[0][0] diff --git a/dysql/test_managers.py b/dysql/test_managers.py new file mode 100644 --- /dev/null +++ b/dysql/test_managers.py @@ -0,0 +1,236 @@ +""" +Copyright 2021 Adobe +All Rights Reserved. + +NOTICE: Adobe permits you to use, modify, and distribute this file in accordance +with the terms of the Adobe license agreement accompanying it. +""" + +import abc +import logging +import os +import subprocess +from time import sleep +from typing import Optional + +from .connections import sqlquery +from .databases import ( + is_set_current_database_supported, + set_current_database, + set_default_connection_parameters, +) +from .mappers import CountMapper +from .query_utils import QueryData + +LOGGER = logging.getLogger(__name__) + + +class DbTestManagerBase(abc.ABC): + """ + Base class for all test managers. See individual implementations for usage details. + """ + + # pylint: disable=too-many-instance-attributes + + def __init__( + self, + host: str, + username: str, + password: str, + db_name: str, + schema_db_name: Optional[str], + docker_container: Optional[str] = None, + keep_db: bool = False, + **connection_defaults, + ): # pylint: disable=too-many-arguments + """ + Constructor, any unknown kwargs are passed directly to set_default_connection_parameters. + + :param host: the host to access the test database + :param username: the username to access the test database + :param password: the password to access the test database + :param db_name: the name of the test database + :param schema_db_name: the name of the DB to duplicate schema from (using mariadb-dump) + :param docker_container: the name of the docker container where the database is running (if in docker) + :param keep_db: This prevents teardown from removing the created database after running tests + which can be helpful in debugging + """ + self.host = host + self.username = username + self.password = password + self.db_name = db_name + self.schema_db_name = schema_db_name + self.docker_container = docker_container + self.keep_db = keep_db + self.connection_defaults = connection_defaults + self.in_docker = self._is_running_in_docker() + + @staticmethod + def _is_running_in_docker(): + if os.path.exists("/.dockerenv"): + return True + + if os.path.exists("/proc/1/cgroup"): + with open("/proc/1/cgroup", "rt", encoding="utf8") as fobj: + contents = fobj.read() + for marker in ("docker", "kubepod", "lxc"): + if marker in contents: + return True + return False + + def __enter__(self): + LOGGER.debug(f"Setting up database : {self.db_name}") + # Set the host based on whether we are in buildrunner or not (to test locally) + + self._create_test_db() + set_default_connection_parameters( + self.host, + self.username, + self.password, + self.db_name, + **self.connection_defaults, + ) + + # Set the database if supported by the python runtime + if is_set_current_database_supported(): + set_current_database(self.db_name) + + if self.schema_db_name: + self._wait_for_tables_exist() + + def __exit__(self, exc_type, exc_val, exc_tb): + if not self.keep_db: + LOGGER.debug(f"Tearing down database : {self.db_name}") + self._tear_down_test_db() + + @abc.abstractmethod + def _create_test_db(self) -> None: + """ + Must be overridden in implementing classes. Creates the test database from the self.schema_db_name + database (if present) or an empty database desired. + """ + + @abc.abstractmethod + def _get_tables_count(self, db_name: str) -> int: + """ + Must be overridden in implementing classes. Retrieves the current table count for the database. + :param db_name: the database to retrieve the count for + :return: the number of tables present in the database + """ + + @abc.abstractmethod + def _tear_down_test_db(self) -> None: + """ + Must be overridden in implementing classes. Tears down the test database. + """ + + def _wait_for_tables_exist(self) -> None: + """ + Waits for the tables to exist in the new test database. + """ + tables_exist = False + expected_count = self._get_tables_count(self.schema_db_name) + while not tables_exist: + sleep(0.25) + LOGGER.debug("Tables are still not ready") + actual_count = self._get_tables_count(self.db_name) + tables_exist = expected_count == actual_count + + def _run(self, command: str) -> subprocess.CompletedProcess: + """ + Runs a command, wrapping the command in docker commands if necessary. + :param command: the command to run + :return: the completed process information + """ + if not self.in_docker: + command = f"docker exec {self.docker_container} bash -c '{command}'" + + try: + LOGGER.debug(f"Executing : '{command}'") + completed_process = subprocess.run( + command, shell=True, timeout=30, check=True, capture_output=True + ) + LOGGER.debug(f"Executed : {completed_process.stdout}") + + return completed_process + except subprocess.CalledProcessError: + LOGGER.exception(f"Error handling command : {command}") + raise + + +class MariaDbTestManager(DbTestManagerBase): + """ + May be used in testing to copy and create a database and schema. This class works specifically with + Maria/MySQL databases. + + Example: + + @pytest.fixture(scope='module', autouse=True) + def setup_db(self): + # Pass in the database name and any optional params + with MariaDbTestManager(f'testdb_{self.__class__.__name__.lower()}'): + yield + """ + + # pylint: disable=too-few-public-methods + + def __init__( + self, + db_name: str, + schema_db_name: Optional[str] = None, + echo_queries: bool = False, + keep_db: bool = False, + pool_size=3, + charset="utf8", + ): # pylint: disable=too-many-arguments + """ + :param db_name: the name you want for your test database + :param schema_db_name: the name of the DB to duplicate schema from (using mariadb-dump) + :param echo_queries: True if you want to see queries + :param keep_db: This prevents teardown from removing the created DB after running tests + which can be helpful in debugging + :param charset: This allows you to override the default charset if you need something besides utf8 + """ + super().__init__( + os.getenv("MARIA_HOST", "localhost"), + os.getenv("MARIA_USERNAME", "root"), + os.getenv("MARIA_PASSWORD", "password"), + db_name, + schema_db_name, + port=3306, + echo_queries=echo_queries, + pool_size=pool_size, + docker_container=os.getenv("MARIA_CONTAINER_NAME", "mariadb"), + keep_db=keep_db, + charset=charset, + ) + + def _create_test_db(self) -> None: + self._run( + f'mariadb -p{self.password} -h{self.host} -N -e "DROP DATABASE IF EXISTS {self.db_name}"' + ) + self._run( + f'mariadb -p{self.password} -h{self.host} -s -N -e "CREATE DATABASE IF NOT EXISTS {self.db_name}"' + ) + if self.schema_db_name: + self._run( + f"mariadb-dump --no-data --routines -p{self.password} {self.schema_db_name} -h{self.host} " + f"| mariadb -p{self.password} {self.db_name} -h{self.host}" + ) + + def _tear_down_test_db(self) -> None: + self._run( + f'echo "DROP DATABASE IF EXISTS {self.db_name} " | mariadb -p{self.password} -h{self.host}' + ) + + @sqlquery(mapper=CountMapper()) + def _get_tables_count(self, db_name: str) -> int: + # pylint: disable=unused-argument + return QueryData( + """ + SELECT count(1) + FROM information_schema.TABLES + WHERE TABLE_SCHEMA=:db_name + """, + query_params={"db_name": db_name}, + )