test_base.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  1. # Copyright 2014-2016 OpenMarket Ltd
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. from collections import OrderedDict
  15. from unittest.mock import Mock
  16. from twisted.internet import defer
  17. from synapse.storage._base import SQLBaseStore
  18. from synapse.storage.database import DatabasePool
  19. from synapse.storage.engines import create_engine
  20. from tests import unittest
  21. from tests.server import TestHomeServer
  22. from tests.utils import default_config
  23. class SQLBaseStoreTestCase(unittest.TestCase):
  24. """Test the "simple" SQL generating methods in SQLBaseStore."""
  25. def setUp(self):
  26. self.db_pool = Mock(spec=["runInteraction"])
  27. self.mock_txn = Mock()
  28. self.mock_conn = Mock(spec_set=["cursor", "rollback", "commit"])
  29. self.mock_conn.cursor.return_value = self.mock_txn
  30. self.mock_conn.rollback.return_value = None
  31. # Our fake runInteraction just runs synchronously inline
  32. def runInteraction(func, *args, **kwargs):
  33. return defer.succeed(func(self.mock_txn, *args, **kwargs))
  34. self.db_pool.runInteraction = runInteraction
  35. def runWithConnection(func, *args, **kwargs):
  36. return defer.succeed(func(self.mock_conn, *args, **kwargs))
  37. self.db_pool.runWithConnection = runWithConnection
  38. config = default_config(name="test", parse=True)
  39. hs = TestHomeServer("test", config=config)
  40. sqlite_config = {"name": "sqlite3"}
  41. engine = create_engine(sqlite_config)
  42. fake_engine = Mock(wraps=engine)
  43. fake_engine.can_native_upsert = False
  44. fake_engine.in_transaction.return_value = False
  45. db = DatabasePool(Mock(), Mock(config=sqlite_config), fake_engine)
  46. db._db_pool = self.db_pool
  47. self.datastore = SQLBaseStore(db, None, hs)
  48. @defer.inlineCallbacks
  49. def test_insert_1col(self):
  50. self.mock_txn.rowcount = 1
  51. yield defer.ensureDeferred(
  52. self.datastore.db_pool.simple_insert(
  53. table="tablename", values={"columname": "Value"}
  54. )
  55. )
  56. self.mock_txn.execute.assert_called_with(
  57. "INSERT INTO tablename (columname) VALUES(?)", ("Value",)
  58. )
  59. @defer.inlineCallbacks
  60. def test_insert_3cols(self):
  61. self.mock_txn.rowcount = 1
  62. yield defer.ensureDeferred(
  63. self.datastore.db_pool.simple_insert(
  64. table="tablename",
  65. # Use OrderedDict() so we can assert on the SQL generated
  66. values=OrderedDict([("colA", 1), ("colB", 2), ("colC", 3)]),
  67. )
  68. )
  69. self.mock_txn.execute.assert_called_with(
  70. "INSERT INTO tablename (colA, colB, colC) VALUES(?, ?, ?)", (1, 2, 3)
  71. )
  72. @defer.inlineCallbacks
  73. def test_select_one_1col(self):
  74. self.mock_txn.rowcount = 1
  75. self.mock_txn.__iter__ = Mock(return_value=iter([("Value",)]))
  76. value = yield defer.ensureDeferred(
  77. self.datastore.db_pool.simple_select_one_onecol(
  78. table="tablename", keyvalues={"keycol": "TheKey"}, retcol="retcol"
  79. )
  80. )
  81. self.assertEqual("Value", value)
  82. self.mock_txn.execute.assert_called_with(
  83. "SELECT retcol FROM tablename WHERE keycol = ?", ["TheKey"]
  84. )
  85. @defer.inlineCallbacks
  86. def test_select_one_3col(self):
  87. self.mock_txn.rowcount = 1
  88. self.mock_txn.fetchone.return_value = (1, 2, 3)
  89. ret = yield defer.ensureDeferred(
  90. self.datastore.db_pool.simple_select_one(
  91. table="tablename",
  92. keyvalues={"keycol": "TheKey"},
  93. retcols=["colA", "colB", "colC"],
  94. )
  95. )
  96. self.assertEqual({"colA": 1, "colB": 2, "colC": 3}, ret)
  97. self.mock_txn.execute.assert_called_with(
  98. "SELECT colA, colB, colC FROM tablename WHERE keycol = ?", ["TheKey"]
  99. )
  100. @defer.inlineCallbacks
  101. def test_select_one_missing(self):
  102. self.mock_txn.rowcount = 0
  103. self.mock_txn.fetchone.return_value = None
  104. ret = yield defer.ensureDeferred(
  105. self.datastore.db_pool.simple_select_one(
  106. table="tablename",
  107. keyvalues={"keycol": "Not here"},
  108. retcols=["colA"],
  109. allow_none=True,
  110. )
  111. )
  112. self.assertFalse(ret)
  113. @defer.inlineCallbacks
  114. def test_select_list(self):
  115. self.mock_txn.rowcount = 3
  116. self.mock_txn.__iter__ = Mock(return_value=iter([(1,), (2,), (3,)]))
  117. self.mock_txn.description = (("colA", None, None, None, None, None, None),)
  118. ret = yield defer.ensureDeferred(
  119. self.datastore.db_pool.simple_select_list(
  120. table="tablename", keyvalues={"keycol": "A set"}, retcols=["colA"]
  121. )
  122. )
  123. self.assertEqual([{"colA": 1}, {"colA": 2}, {"colA": 3}], ret)
  124. self.mock_txn.execute.assert_called_with(
  125. "SELECT colA FROM tablename WHERE keycol = ?", ["A set"]
  126. )
  127. @defer.inlineCallbacks
  128. def test_update_one_1col(self):
  129. self.mock_txn.rowcount = 1
  130. yield defer.ensureDeferred(
  131. self.datastore.db_pool.simple_update_one(
  132. table="tablename",
  133. keyvalues={"keycol": "TheKey"},
  134. updatevalues={"columnname": "New Value"},
  135. )
  136. )
  137. self.mock_txn.execute.assert_called_with(
  138. "UPDATE tablename SET columnname = ? WHERE keycol = ?",
  139. ["New Value", "TheKey"],
  140. )
  141. @defer.inlineCallbacks
  142. def test_update_one_4cols(self):
  143. self.mock_txn.rowcount = 1
  144. yield defer.ensureDeferred(
  145. self.datastore.db_pool.simple_update_one(
  146. table="tablename",
  147. keyvalues=OrderedDict([("colA", 1), ("colB", 2)]),
  148. updatevalues=OrderedDict([("colC", 3), ("colD", 4)]),
  149. )
  150. )
  151. self.mock_txn.execute.assert_called_with(
  152. "UPDATE tablename SET colC = ?, colD = ? WHERE" " colA = ? AND colB = ?",
  153. [3, 4, 1, 2],
  154. )
  155. @defer.inlineCallbacks
  156. def test_delete_one(self):
  157. self.mock_txn.rowcount = 1
  158. yield defer.ensureDeferred(
  159. self.datastore.db_pool.simple_delete_one(
  160. table="tablename", keyvalues={"keycol": "Go away"}
  161. )
  162. )
  163. self.mock_txn.execute.assert_called_with(
  164. "DELETE FROM tablename WHERE keycol = ?", ["Go away"]
  165. )