1
0

test_base.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  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.utils import TestHomeServer, default_config
  22. class SQLBaseStoreTestCase(unittest.TestCase):
  23. """Test the "simple" SQL generating methods in SQLBaseStore."""
  24. def setUp(self):
  25. self.db_pool = Mock(spec=["runInteraction"])
  26. self.mock_txn = Mock()
  27. self.mock_conn = Mock(spec_set=["cursor", "rollback", "commit"])
  28. self.mock_conn.cursor.return_value = self.mock_txn
  29. self.mock_conn.rollback.return_value = None
  30. # Our fake runInteraction just runs synchronously inline
  31. def runInteraction(func, *args, **kwargs):
  32. return defer.succeed(func(self.mock_txn, *args, **kwargs))
  33. self.db_pool.runInteraction = runInteraction
  34. def runWithConnection(func, *args, **kwargs):
  35. return defer.succeed(func(self.mock_conn, *args, **kwargs))
  36. self.db_pool.runWithConnection = runWithConnection
  37. config = default_config(name="test", parse=True)
  38. hs = TestHomeServer("test", config=config)
  39. sqlite_config = {"name": "sqlite3"}
  40. engine = create_engine(sqlite_config)
  41. fake_engine = Mock(wraps=engine)
  42. fake_engine.can_native_upsert = False
  43. fake_engine.in_transaction.return_value = False
  44. db = DatabasePool(Mock(), Mock(config=sqlite_config), fake_engine)
  45. db._db_pool = self.db_pool
  46. self.datastore = SQLBaseStore(db, None, hs)
  47. @defer.inlineCallbacks
  48. def test_insert_1col(self):
  49. self.mock_txn.rowcount = 1
  50. yield defer.ensureDeferred(
  51. self.datastore.db_pool.simple_insert(
  52. table="tablename", values={"columname": "Value"}
  53. )
  54. )
  55. self.mock_txn.execute.assert_called_with(
  56. "INSERT INTO tablename (columname) VALUES(?)", ("Value",)
  57. )
  58. @defer.inlineCallbacks
  59. def test_insert_3cols(self):
  60. self.mock_txn.rowcount = 1
  61. yield defer.ensureDeferred(
  62. self.datastore.db_pool.simple_insert(
  63. table="tablename",
  64. # Use OrderedDict() so we can assert on the SQL generated
  65. values=OrderedDict([("colA", 1), ("colB", 2), ("colC", 3)]),
  66. )
  67. )
  68. self.mock_txn.execute.assert_called_with(
  69. "INSERT INTO tablename (colA, colB, colC) VALUES(?, ?, ?)", (1, 2, 3)
  70. )
  71. @defer.inlineCallbacks
  72. def test_select_one_1col(self):
  73. self.mock_txn.rowcount = 1
  74. self.mock_txn.__iter__ = Mock(return_value=iter([("Value",)]))
  75. value = yield defer.ensureDeferred(
  76. self.datastore.db_pool.simple_select_one_onecol(
  77. table="tablename", keyvalues={"keycol": "TheKey"}, retcol="retcol"
  78. )
  79. )
  80. self.assertEquals("Value", value)
  81. self.mock_txn.execute.assert_called_with(
  82. "SELECT retcol FROM tablename WHERE keycol = ?", ["TheKey"]
  83. )
  84. @defer.inlineCallbacks
  85. def test_select_one_3col(self):
  86. self.mock_txn.rowcount = 1
  87. self.mock_txn.fetchone.return_value = (1, 2, 3)
  88. ret = yield defer.ensureDeferred(
  89. self.datastore.db_pool.simple_select_one(
  90. table="tablename",
  91. keyvalues={"keycol": "TheKey"},
  92. retcols=["colA", "colB", "colC"],
  93. )
  94. )
  95. self.assertEquals({"colA": 1, "colB": 2, "colC": 3}, ret)
  96. self.mock_txn.execute.assert_called_with(
  97. "SELECT colA, colB, colC FROM tablename WHERE keycol = ?", ["TheKey"]
  98. )
  99. @defer.inlineCallbacks
  100. def test_select_one_missing(self):
  101. self.mock_txn.rowcount = 0
  102. self.mock_txn.fetchone.return_value = None
  103. ret = yield defer.ensureDeferred(
  104. self.datastore.db_pool.simple_select_one(
  105. table="tablename",
  106. keyvalues={"keycol": "Not here"},
  107. retcols=["colA"],
  108. allow_none=True,
  109. )
  110. )
  111. self.assertFalse(ret)
  112. @defer.inlineCallbacks
  113. def test_select_list(self):
  114. self.mock_txn.rowcount = 3
  115. self.mock_txn.__iter__ = Mock(return_value=iter([(1,), (2,), (3,)]))
  116. self.mock_txn.description = (("colA", None, None, None, None, None, None),)
  117. ret = yield defer.ensureDeferred(
  118. self.datastore.db_pool.simple_select_list(
  119. table="tablename", keyvalues={"keycol": "A set"}, retcols=["colA"]
  120. )
  121. )
  122. self.assertEquals([{"colA": 1}, {"colA": 2}, {"colA": 3}], ret)
  123. self.mock_txn.execute.assert_called_with(
  124. "SELECT colA FROM tablename WHERE keycol = ?", ["A set"]
  125. )
  126. @defer.inlineCallbacks
  127. def test_update_one_1col(self):
  128. self.mock_txn.rowcount = 1
  129. yield defer.ensureDeferred(
  130. self.datastore.db_pool.simple_update_one(
  131. table="tablename",
  132. keyvalues={"keycol": "TheKey"},
  133. updatevalues={"columnname": "New Value"},
  134. )
  135. )
  136. self.mock_txn.execute.assert_called_with(
  137. "UPDATE tablename SET columnname = ? WHERE keycol = ?",
  138. ["New Value", "TheKey"],
  139. )
  140. @defer.inlineCallbacks
  141. def test_update_one_4cols(self):
  142. self.mock_txn.rowcount = 1
  143. yield defer.ensureDeferred(
  144. self.datastore.db_pool.simple_update_one(
  145. table="tablename",
  146. keyvalues=OrderedDict([("colA", 1), ("colB", 2)]),
  147. updatevalues=OrderedDict([("colC", 3), ("colD", 4)]),
  148. )
  149. )
  150. self.mock_txn.execute.assert_called_with(
  151. "UPDATE tablename SET colC = ?, colD = ? WHERE" " colA = ? AND colB = ?",
  152. [3, 4, 1, 2],
  153. )
  154. @defer.inlineCallbacks
  155. def test_delete_one(self):
  156. self.mock_txn.rowcount = 1
  157. yield defer.ensureDeferred(
  158. self.datastore.db_pool.simple_delete_one(
  159. table="tablename", keyvalues={"keycol": "Go away"}
  160. )
  161. )
  162. self.mock_txn.execute.assert_called_with(
  163. "DELETE FROM tablename WHERE keycol = ?", ["Go away"]
  164. )