test_rollback_worker.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  1. # Copyright 2021 The Matrix.org Foundation C.I.C.
  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 typing import List
  15. from unittest import mock
  16. from twisted.test.proto_helpers import MemoryReactor
  17. from synapse.app.generic_worker import GenericWorkerServer
  18. from synapse.server import HomeServer
  19. from synapse.storage.database import LoggingDatabaseConnection
  20. from synapse.storage.prepare_database import PrepareDatabaseException, prepare_database
  21. from synapse.storage.schema import SCHEMA_VERSION
  22. from synapse.types import JsonDict
  23. from synapse.util import Clock
  24. from tests.unittest import HomeserverTestCase
  25. def fake_listdir(filepath: str) -> List[str]:
  26. """
  27. A fake implementation of os.listdir which we can use to mock out the filesystem.
  28. Args:
  29. filepath: The directory to list files for.
  30. Returns:
  31. A list of files and folders in the directory.
  32. """
  33. if filepath.endswith("full_schemas"):
  34. return [str(SCHEMA_VERSION)]
  35. return ["99_add_unicorn_to_database.sql"]
  36. class WorkerSchemaTests(HomeserverTestCase):
  37. def make_homeserver(self, reactor: MemoryReactor, clock: Clock) -> HomeServer:
  38. hs = self.setup_test_homeserver(
  39. federation_http_client=None, homeserver_to_use=GenericWorkerServer
  40. )
  41. return hs
  42. def default_config(self) -> JsonDict:
  43. conf = super().default_config()
  44. # Mark this as a worker app.
  45. conf["worker_app"] = "yes"
  46. return conf
  47. def test_rolling_back(self) -> None:
  48. """Test that workers can start if the DB is a newer schema version"""
  49. db_pool = self.hs.get_datastores().main.db_pool
  50. db_conn = LoggingDatabaseConnection(
  51. db_pool._db_pool.connect(),
  52. db_pool.engine,
  53. "tests",
  54. )
  55. cur = db_conn.cursor()
  56. cur.execute("UPDATE schema_version SET version = ?", (SCHEMA_VERSION + 1,))
  57. db_conn.commit()
  58. prepare_database(db_conn, db_pool.engine, self.hs.config)
  59. def test_not_upgraded_old_schema_version(self) -> None:
  60. """Test that workers don't start if the DB has an older schema version"""
  61. db_pool = self.hs.get_datastores().main.db_pool
  62. db_conn = LoggingDatabaseConnection(
  63. db_pool._db_pool.connect(),
  64. db_pool.engine,
  65. "tests",
  66. )
  67. cur = db_conn.cursor()
  68. cur.execute("UPDATE schema_version SET version = ?", (SCHEMA_VERSION - 1,))
  69. db_conn.commit()
  70. with self.assertRaises(PrepareDatabaseException):
  71. prepare_database(db_conn, db_pool.engine, self.hs.config)
  72. def test_not_upgraded_current_schema_version_with_outstanding_deltas(self) -> None:
  73. """
  74. Test that workers don't start if the DB is on the current schema version,
  75. but there are still outstanding delta migrations to run.
  76. """
  77. db_pool = self.hs.get_datastores().main.db_pool
  78. db_conn = LoggingDatabaseConnection(
  79. db_pool._db_pool.connect(),
  80. db_pool.engine,
  81. "tests",
  82. )
  83. # Set the schema version of the database to the current version
  84. cur = db_conn.cursor()
  85. cur.execute("UPDATE schema_version SET version = ?", (SCHEMA_VERSION,))
  86. db_conn.commit()
  87. # Path `os.listdir` here to make synapse think that there is a migration
  88. # file ready to be run.
  89. # Note that we can't patch this function for the whole method, else Synapse
  90. # will try to find the file when building the database initially.
  91. with mock.patch("os.listdir", mock.Mock(side_effect=fake_listdir)):
  92. with self.assertRaises(PrepareDatabaseException):
  93. # Synapse should think that there is an outstanding migration file due to
  94. # patching 'os.listdir' in the function decorator.
  95. #
  96. # We expect Synapse to raise an exception to indicate the master process
  97. # needs to apply this migration file.
  98. prepare_database(db_conn, db_pool.engine, self.hs.config)