test_database.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2020 The Matrix.org Foundation C.I.C.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. from synapse.storage.database import make_tuple_comparison_clause
  16. from synapse.storage.engines import BaseDatabaseEngine
  17. from tests import unittest
  18. def _stub_db_engine(**kwargs) -> BaseDatabaseEngine:
  19. # returns a DatabaseEngine, circumventing the abc mechanism
  20. # any kwargs are set as attributes on the class before instantiating it
  21. t = type(
  22. "TestBaseDatabaseEngine",
  23. (BaseDatabaseEngine,),
  24. dict(BaseDatabaseEngine.__dict__),
  25. )
  26. # defeat the abc mechanism
  27. t.__abstractmethods__ = set()
  28. for k, v in kwargs.items():
  29. setattr(t, k, v)
  30. return t(None, None)
  31. class TupleComparisonClauseTestCase(unittest.TestCase):
  32. def test_native_tuple_comparison(self):
  33. db_engine = _stub_db_engine(supports_tuple_comparison=True)
  34. clause, args = make_tuple_comparison_clause(db_engine, [("a", 1), ("b", 2)])
  35. self.assertEqual(clause, "(a,b) > (?,?)")
  36. self.assertEqual(args, [1, 2])
  37. def test_emulated_tuple_comparison(self):
  38. db_engine = _stub_db_engine(supports_tuple_comparison=False)
  39. clause, args = make_tuple_comparison_clause(
  40. db_engine, [("a", 1), ("b", 2), ("c", 3)]
  41. )
  42. self.assertEqual(
  43. clause, "(a >= ? AND (a > ? OR (b >= ? AND (b > ? OR c > ?))))"
  44. )
  45. self.assertEqual(args, [1, 1, 2, 2, 3])