Skip to content

Commit 28479cf

Browse files
author
Sergio García Prado
committed
ISSUE #346
* Refactor `PostgresAsyncTestCase`.
1 parent 00691f5 commit 28479cf

File tree

11 files changed

+83
-73
lines changed

11 files changed

+83
-73
lines changed

packages/core/minos-microservice-aggregate/tests/test_aggregate/test_events/test_repositories/test_pg.py

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -21,9 +21,10 @@
2121
class TestPostgreSqlEventRepositorySubmit(EventRepositorySubmitTestCase, PostgresAsyncTestCase):
2222
__test__ = True
2323

24-
def build_event_repository(self) -> EventRepository:
24+
@staticmethod
25+
def build_event_repository() -> EventRepository:
2526
"""Fort testing purposes."""
26-
return PostgreSqlEventRepository(**self.repository_db)
27+
return PostgreSqlEventRepository()
2728

2829
def test_constructor(self):
2930
pool = DatabaseClientPool.from_config(self.config)
@@ -41,7 +42,7 @@ def test_from_config(self):
4142
self.assertEqual(repository_config["port"], repository.port)
4243

4344
async def test_setup(self):
44-
async with aiopg.connect(**self.repository_db) as connection:
45+
async with aiopg.connect(**self.config.get_default_database()) as connection:
4546
async with connection.cursor() as cursor:
4647
await cursor.execute(
4748
"SELECT EXISTS (SELECT FROM information_schema.tables WHERE table_name = 'aggregate_event');"
@@ -53,9 +54,10 @@ async def test_setup(self):
5354
class TestPostgreSqlRepositorySelect(EventRepositorySelectTestCase, PostgresAsyncTestCase):
5455
__test__ = True
5556

56-
def build_event_repository(self) -> EventRepository:
57+
@staticmethod
58+
def build_event_repository() -> EventRepository:
5759
"""Fort testing purposes."""
58-
return PostgreSqlEventRepository(**self.repository_db)
60+
return PostgreSqlEventRepository()
5961

6062

6163
if __name__ == "__main__":

packages/core/minos-microservice-aggregate/tests/test_aggregate/test_snapshots/test_pg/test_abc.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616
class TestPostgreSqlSnapshotSetup(AggregateTestCase, PostgresAsyncTestCase):
1717
async def test_setup_snapshot_table(self):
1818
async with PostgreSqlSnapshotSetup.from_config(self.config):
19-
async with aiopg.connect(**self.snapshot_db) as connection:
19+
async with aiopg.connect(**self.config.get_default_database()) as connection:
2020
async with connection.cursor() as cursor:
2121
await cursor.execute(
2222
"SELECT EXISTS (SELECT FROM pg_tables "
@@ -27,7 +27,7 @@ async def test_setup_snapshot_table(self):
2727

2828
async def test_setup_snapshot_aux_offset_table(self):
2929
async with PostgreSqlSnapshotSetup.from_config(self.config):
30-
async with aiopg.connect(**self.snapshot_db) as connection:
30+
async with aiopg.connect(**self.config.get_default_database()) as connection:
3131
async with connection.cursor() as cursor:
3232
await cursor.execute(
3333
"SELECT EXISTS (SELECT FROM pg_tables WHERE "

packages/core/minos-microservice-aggregate/tests/test_aggregate/test_snapshots/test_pg/test_queries.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -426,7 +426,7 @@ async def test_build_complex(self):
426426
self.assertEqual(self._flatten_parameters(expected_parameters), self._flatten_parameters(observed[1]))
427427

428428
async def _flatten_query(self, query) -> str:
429-
async with aiopg.connect(**self.snapshot_db) as connection:
429+
async with aiopg.connect(**self.config.get_default_database()) as connection:
430430
return query.as_string(connection.raw)
431431

432432
@staticmethod

packages/core/minos-microservice-aggregate/tests/test_aggregate/test_transactions/test_repositories/test_pg.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ class TestPostgreSqlTransactionRepository(AggregateTestCase, PostgresAsyncTestCa
2727
def setUp(self) -> None:
2828
super().setUp()
2929

30-
self.transaction_repository = PostgreSqlTransactionRepository(**self.repository_db)
30+
self.transaction_repository = PostgreSqlTransactionRepository()
3131

3232
self.uuid = uuid4()
3333

@@ -58,7 +58,7 @@ def test_from_config(self):
5858
self.assertEqual(repository_config["password"], repository.password)
5959

6060
async def test_setup(self):
61-
async with aiopg.connect(**self.repository_db) as connection:
61+
async with aiopg.connect(**self.config.get_default_database()) as connection:
6262
async with connection.cursor() as cursor:
6363
await cursor.execute(
6464
"SELECT EXISTS (SELECT FROM information_schema.tables WHERE table_name = 'aggregate_transaction');"
@@ -159,7 +159,7 @@ def setUp(self) -> None:
159159
self.uuid_4 = uuid4()
160160
self.uuid_5 = uuid4()
161161

162-
self.transaction_repository = PostgreSqlTransactionRepository(**self.repository_db)
162+
self.transaction_repository = PostgreSqlTransactionRepository()
163163

164164
self.entries = [
165165
TransactionEntry(self.uuid_1, TransactionStatus.PENDING, 12),

packages/core/minos-microservice-common/minos/common/testing.py

Lines changed: 28 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -74,73 +74,66 @@ def __getattr__(self, item: str) -> Any:
7474
raise AttributeError(f"{type(self).__name__!r} does not contain the {item!r} attribute.")
7575

7676

77+
# noinspection SqlNoDataSourceInspection
7778
class PostgresAsyncTestCase(MinosTestCase, ABC):
7879
def setUp(self):
79-
80-
self._uuid = uuid4()
8180
self._config = Config(self.get_config_file_path())
81+
self._uuid = uuid4()
82+
self._test_db = {"database": f"test_db_{self._uuid.hex}", "user": f"test_user_{self._uuid.hex}"}
83+
super().setUp()
8284

83-
self._meta_repository_db = self._config.get_database_by_name("aggregate")
85+
@property
86+
def repository_db(self) -> dict[str, Any]:
87+
return self.config.get_database_by_name("aggregate") | self._test_db
8488

85-
self._meta_broker_queue_db = self._config.get_database_by_name("broker")
89+
@property
90+
def broker_queue_db(self) -> dict[str, Any]:
91+
return self.config.get_database_by_name("broker") | self._test_db
8692

87-
self._meta_snapshot_db = self._config.get_database_by_name("aggregate")
93+
@property
94+
def snapshot_db(self) -> dict[str, Any]:
95+
return self.config.get_database_by_name("aggregate") | self._test_db
8896

89-
self._test_db = {"database": f"test_db_{self._uuid.hex}", "user": f"test_user_{self._uuid.hex}"}
97+
def get_config(self) -> Config:
98+
config = Config(self.get_config_file_path())
9099

91-
self.repository_db = self._meta_repository_db | self._test_db
92-
self.broker_queue_db = self._meta_broker_queue_db | self._test_db
93-
self.snapshot_db = self._meta_snapshot_db | self._test_db
100+
base_fn = config.get_databases
94101

95-
super().setUp()
102+
def _fn():
103+
return {k: (v | self._test_db) for k, v in base_fn().items()}
96104

97-
def get_config(self) -> Config:
98-
return Config(
99-
self.get_config_file_path(),
100-
repository_database=self.repository_db["database"],
101-
repository_user=self.repository_db["user"],
102-
broker_queue_database=self.broker_queue_db["database"],
103-
broker_queue_user=self.broker_queue_db["user"],
104-
snapshot_database=self.snapshot_db["database"],
105-
snapshot_user=self.snapshot_db["user"],
106-
)
105+
config.get_databases = _fn
106+
return config
107107

108108
def get_injections(self) -> list[Union[InjectableMixin, type[InjectableMixin], str]]:
109109
return [PoolFactory.from_config(self.config, default_classes={"database": DatabaseClientPool})]
110110

111111
async def asyncSetUp(self):
112112
pairs = self._drop_duplicates(
113-
[
114-
(self._meta_repository_db, self.repository_db),
115-
(self._meta_broker_queue_db, self.broker_queue_db),
116-
(self._meta_snapshot_db, self.snapshot_db),
117-
]
113+
[(db, self._test_db) for db in self._config.get_databases().values() if "database" in db]
118114
)
115+
119116
for meta, test in pairs:
120-
await self._setup_database(dict(meta), dict(test))
117+
await self._setup_database(meta, test)
121118

122119
async def _setup_database(self, meta: dict[str, Any], test: dict[str, Any]) -> None:
123120
await self._teardown_database(meta, test)
124121

125122
async with aiopg.connect(**meta) as connection:
126123
async with connection.cursor() as cursor:
127124
template = "CREATE ROLE {user} WITH SUPERUSER CREATEDB LOGIN ENCRYPTED PASSWORD {password!r};"
128-
await cursor.execute(template.format(**test))
125+
await cursor.execute(template.format(**(meta | test)))
129126

130127
template = "CREATE DATABASE {database} WITH OWNER = {user};"
131-
await cursor.execute(template.format(**test))
128+
await cursor.execute(template.format(**(meta | test)))
132129

133130
await super().asyncSetUp()
134131

135132
async def asyncTearDown(self):
136133
await super().asyncTearDown()
137134

138135
pairs = self._drop_duplicates(
139-
[
140-
(self._meta_repository_db, self.repository_db),
141-
(self._meta_broker_queue_db, self.broker_queue_db),
142-
(self._meta_snapshot_db, self.snapshot_db),
143-
]
136+
[(db, self._test_db) for db in self._config.get_databases().values() if "database" in db]
144137
)
145138

146139
for meta, test in pairs:
@@ -159,7 +152,7 @@ async def _teardown_database(meta: dict[str, Any], test: dict[str, Any]) -> None
159152
async with aiopg.connect(**meta) as connection:
160153
async with connection.cursor() as cursor:
161154
template = "DROP DATABASE IF EXISTS {database}"
162-
await cursor.execute(template.format(**test))
155+
await cursor.execute(template.format(**(meta | test)))
163156

164157
template = "DROP ROLE IF EXISTS {user};"
165-
await cursor.execute(template.format(**test))
158+
await cursor.execute(template.format(**(meta | test)))

packages/core/minos-microservice-common/tests/test_common/test_config/test_abc.py

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@
1818
MinosConfigException,
1919
)
2020
from tests.utils import (
21-
CONFIG_FILE_PATH,
21+
BASE_PATH,
2222
)
2323

2424

@@ -69,7 +69,8 @@ def _get_saga(self) -> dict[str, Any]:
6969
class TestConfig(unittest.TestCase):
7070
def setUp(self) -> None:
7171
super().setUp()
72-
self.config = _Config(CONFIG_FILE_PATH)
72+
self.file_path = BASE_PATH / "config" / "v1.yml"
73+
self.config = _Config(self.file_path)
7374

7475
def test_is_subclass(self):
7576
self.assertTrue(issubclass(Config, InjectableMixin))
@@ -78,10 +79,10 @@ def test_get_injectable_name(self):
7879
self.assertTrue("config", _Config.get_injectable_name())
7980

8081
def test_file_path(self):
81-
self.assertEqual(CONFIG_FILE_PATH, self.config.file_path)
82+
self.assertEqual(self.file_path, self.config.file_path)
8283

8384
def test_file_path_from_str(self):
84-
self.assertEqual(CONFIG_FILE_PATH, _Config(str(CONFIG_FILE_PATH)).file_path)
85+
self.assertEqual(self.file_path, _Config(str(self.file_path)).file_path)
8586

8687
def test_file_raises(self):
8788
with self.assertRaises(MinosConfigException):
@@ -215,7 +216,7 @@ def test_get_saga(self):
215216
self.assertEqual([call()], mock.call_args_list)
216217

217218
def test_new(self):
218-
config = Config(CONFIG_FILE_PATH)
219+
config = Config(self.file_path)
219220
self.assertIsInstance(config, ConfigV1)
220221

221222
def test_new_raises(self):
@@ -224,13 +225,17 @@ def test_new_raises(self):
224225

225226

226227
class TestMinosConfig(unittest.TestCase):
228+
def setUp(self) -> None:
229+
super().setUp()
230+
self.file_path = BASE_PATH / "config" / "v1.yml"
231+
227232
def test_is_subclass(self):
228233
self.assertTrue(issubclass(MinosConfig, Config))
229234

230235
def test_warnings(self):
231236
with warnings.catch_warnings():
232237
warnings.simplefilter("ignore", DeprecationWarning)
233-
config = MinosConfig(CONFIG_FILE_PATH)
238+
config = MinosConfig(self.file_path)
234239
self.assertIsInstance(config, Config)
235240

236241

packages/core/minos-microservice-common/tests/test_common/test_database/test_abc.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,7 @@ async def test_submit_query(self):
6262
async with DatabaseMixin() as database:
6363
await database.submit_query("CREATE TABLE foo (id INT NOT NULL);")
6464

65-
async with aiopg.connect(**self.repository_db) as connection:
65+
async with aiopg.connect(**self.config.get_default_database()) as connection:
6666
async with connection.cursor() as cursor:
6767
await cursor.execute("SELECT EXISTS (SELECT FROM information_schema.tables WHERE table_name = 'foo');")
6868
self.assertTrue((await cursor.fetchone())[0])
@@ -71,7 +71,7 @@ async def test_submit_query_locked(self):
7171
async with DatabaseMixin() as database:
7272
await database.submit_query("CREATE TABLE foo (id INT NOT NULL);", lock=1234)
7373

74-
async with aiopg.connect(**self.repository_db) as connection:
74+
async with aiopg.connect(**self.config.get_default_database()) as connection:
7575
async with connection.cursor() as cursor:
7676
await cursor.execute("SELECT EXISTS (SELECT FROM information_schema.tables WHERE table_name = 'foo');")
7777
self.assertTrue((await cursor.fetchone())[0])

packages/core/minos-microservice-common/tests/test_common/test_database/test_locks.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -22,27 +22,27 @@ def test_base(self):
2222
self.assertTrue(issubclass(DatabaseLock, Lock))
2323

2424
async def test_wrapped_connection(self):
25-
wrapped_connection = aiopg.connect(**self.repository_db)
25+
wrapped_connection = aiopg.connect(**self.config.get_default_database())
2626
lock = DatabaseLock(wrapped_connection, "foo")
2727
self.assertEqual(wrapped_connection, lock.wrapped_connection)
2828

2929
async def test_key(self):
30-
wrapped_connection = aiopg.connect(**self.repository_db)
30+
wrapped_connection = aiopg.connect(**self.config.get_default_database())
3131
lock = DatabaseLock(wrapped_connection, "foo")
3232
self.assertEqual("foo", lock.key)
3333

3434
async def test_key_raises(self):
35-
wrapped_connection = aiopg.connect(**self.repository_db)
35+
wrapped_connection = aiopg.connect(**self.config.get_default_database())
3636
with self.assertRaises(ValueError):
3737
DatabaseLock(wrapped_connection, [])
3838

3939
async def test_hashed_key(self):
40-
wrapped_connection = aiopg.connect(**self.repository_db)
40+
wrapped_connection = aiopg.connect(**self.config.get_default_database())
4141
lock = DatabaseLock(wrapped_connection, "foo")
4242
self.assertEqual(hash("foo"), lock.hashed_key)
4343

4444
async def test_cursor(self):
45-
wrapped_connection = aiopg.connect(**self.repository_db)
45+
wrapped_connection = aiopg.connect(**self.config.get_default_database())
4646
async with DatabaseLock(wrapped_connection, "foo") as lock:
4747
self.assertIsInstance(lock.cursor, Cursor)
4848

packages/core/minos-microservice-common/tests/test_common/test_launchers.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,7 @@ def test_from_config(self):
5959
launcher = EntrypointLauncher.from_config(self.config)
6060
self.assertIsInstance(launcher, EntrypointLauncher)
6161
self.assertEqual(self.config, launcher.config)
62-
self.assertEqual(12, len(launcher.injections))
62+
self.assertEqual(len(self.config.get_injections()), len(launcher.injections))
6363

6464
for injection in launcher.injections.values():
6565
self.assertIsInstance(injection, InjectableMixin)

packages/core/minos-microservice-common/tests/test_common/test_pools.py

Lines changed: 22 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -19,22 +19,18 @@
1919
from minos.common import (
2020
MinosPool,
2121
Pool,
22+
PoolFactory,
2223
SetupMixin,
2324
)
25+
from tests.utils import (
26+
CommonTestCase,
27+
)
2428

2529

26-
class _Pool(Pool):
27-
def __init__(self):
28-
super().__init__()
29-
self.create_instance_call_count = 0
30-
self.destroy_instance_call_count = 0
31-
32-
async def _create_instance(self):
33-
self.create_instance_call_count += 1
34-
return "foo"
35-
36-
async def _destroy_instance(self, instance: t.Any) -> None:
37-
self.destroy_instance_call_count += 1
30+
class TestPoolFactory(CommonTestCase):
31+
def test_constructor(self):
32+
factory = PoolFactory.from_config(self.config)
33+
self.assertIsInstance(factory, PoolFactory)
3834

3935

4036
class TestPool(unittest.IsolatedAsyncioTestCase):
@@ -70,6 +66,20 @@ async def _fn2(p):
7066
self.assertEqual(1, pool_mock.call_count)
7167

7268

69+
class _Pool(Pool):
70+
def __init__(self):
71+
super().__init__()
72+
self.create_instance_call_count = 0
73+
self.destroy_instance_call_count = 0
74+
75+
async def _create_instance(self):
76+
self.create_instance_call_count += 1
77+
return "foo"
78+
79+
async def _destroy_instance(self, instance: t.Any) -> None:
80+
self.destroy_instance_call_count += 1
81+
82+
7383
class TestMinosPool(unittest.IsolatedAsyncioTestCase):
7484
def test_is_subclass(self):
7585
self.assertTrue(issubclass(MinosPool, SetupMixin))

0 commit comments

Comments
 (0)