Skip to content

Commit 93b3e0e

Browse files
committed
migrated aiopg -> aymcpg in pg products
1 parent 4807c22 commit 93b3e0e

File tree

7 files changed

+79
-122
lines changed

7 files changed

+79
-122
lines changed

packages/postgres-database/tests/products/conftest.py

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -7,15 +7,14 @@
77
from collections.abc import Callable
88

99
import pytest
10-
from aiopg.sa.exc import ResourceClosedError
1110
from faker import Faker
1211
from pytest_simcore.helpers.faker_factories import random_product
1312
from simcore_postgres_database.webserver_models import products
1413
from sqlalchemy.dialects.postgresql import insert as pg_insert
1514

1615

1716
@pytest.fixture
18-
def products_regex() -> dict:
17+
def products_regex() -> dict[str, str]:
1918
return {
2019
"s4l": r"(^s4l[\.-])|(^sim4life\.)",
2120
"osparc": r"^osparc.",
@@ -24,19 +23,20 @@ def products_regex() -> dict:
2423

2524

2625
@pytest.fixture
27-
def products_names(products_regex: dict) -> list[str]:
26+
def products_names(products_regex: dict[str, str]) -> list[str]:
2827
return list(products_regex)
2928

3029

3130
@pytest.fixture
32-
def make_products_table(products_regex: dict, faker: Faker) -> Callable:
31+
def make_products_table(products_regex: dict[str, str], faker: Faker) -> Callable:
3332
async def _make(conn) -> None:
3433
for n, (name, regex) in enumerate(products_regex.items()):
3534

3635
result = await conn.execute(
3736
pg_insert(products)
3837
.values(
3938
**random_product(
39+
fake=faker,
4040
name=name,
4141
display_name=f"Product {name.capitalize()}",
4242
short_name=name[:3].lower(),
@@ -45,6 +45,7 @@ async def _make(conn) -> None:
4545
)
4646
)
4747
.on_conflict_do_update(
48+
# osparc might be already injected as default!
4849
index_elements=[products.c.name],
4950
set_={
5051
"display_name": f"Product {name.capitalize()}",
@@ -55,9 +56,7 @@ async def _make(conn) -> None:
5556
)
5657
)
5758

58-
assert result.closed
59+
assert not result.closed
5960
assert not result.returns_rows
60-
with pytest.raises(ResourceClosedError):
61-
await result.scalar()
6261

6362
return _make

packages/postgres-database/tests/products/test_models_products.py

Lines changed: 14 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -3,15 +3,10 @@
33
# pylint: disable=redefined-outer-name
44
# pylint: disable=unused-argument
55

6-
7-
import json
86
from collections.abc import Callable
97
from pathlib import Path
10-
from pprint import pprint
118

129
import sqlalchemy as sa
13-
from aiopg.sa.engine import Engine
14-
from aiopg.sa.result import ResultProxy, RowProxy
1510
from simcore_postgres_database.models.jinja2_templates import jinja2_templates
1611
from simcore_postgres_database.models.products import (
1712
EmailFeedback,
@@ -23,40 +18,37 @@
2318
)
2419
from simcore_postgres_database.webserver_models import products
2520
from sqlalchemy.dialects.postgresql import insert as pg_insert
21+
from sqlalchemy.ext.asyncio import AsyncEngine
2622

2723

2824
async def test_load_products(
29-
aiopg_engine: Engine, make_products_table: Callable, products_regex: dict
25+
asyncpg_engine: AsyncEngine, make_products_table: Callable, products_regex: dict
3026
):
3127
exclude = {
3228
products.c.created,
3329
products.c.modified,
3430
}
3531

36-
async with aiopg_engine.acquire() as conn:
32+
async with asyncpg_engine.connect() as conn:
3733
await make_products_table(conn)
3834

3935
stmt = sa.select(*[c for c in products.columns if c not in exclude])
40-
result: ResultProxy = await conn.execute(stmt)
41-
assert result.returns_rows
42-
43-
rows: list[RowProxy] = await result.fetchall()
36+
result = await conn.execute(stmt)
37+
rows = result.fetchall()
4438
assert rows
4539

46-
assert {
47-
row[products.c.name]: row[products.c.host_regex] for row in rows
48-
} == products_regex
40+
assert {row.name: row.host_regex for row in rows} == products_regex
4941

5042

5143
async def test_jinja2_templates_table(
52-
aiopg_engine: Engine, osparc_simcore_services_dir: Path
44+
asyncpg_engine: AsyncEngine, osparc_simcore_services_dir: Path
5345
):
5446
templates_common_dir = (
5547
osparc_simcore_services_dir
5648
/ "web/server/src/simcore_service_webserver/templates/common"
5749
)
5850

59-
async with aiopg_engine.acquire() as conn:
51+
async with asyncpg_engine.connect() as conn:
6052
templates = []
6153
# templates table
6254
for p in templates_common_dir.glob("*.jinja2"):
@@ -105,10 +97,9 @@ async def test_jinja2_templates_table(
10597
products.c.name, jinja2_templates.c.name, products.c.short_name
10698
).select_from(j)
10799

108-
result: ResultProxy = await conn.execute(stmt)
109-
assert result.rowcount == 2
110-
rows = await result.fetchall()
111-
assert sorted(r.as_tuple() for r in rows) == sorted(
100+
result = await conn.execute(stmt)
101+
rows = result.fetchall()
102+
assert sorted(tuple(r) for r in rows) == sorted(
112103
[
113104
("osparc", "registration_email.jinja2", "osparc"),
114105
("s4l", "registration_email.jinja2", "s4l web"),
@@ -135,7 +126,7 @@ async def test_jinja2_templates_table(
135126

136127

137128
async def test_insert_select_product(
138-
aiopg_engine: Engine,
129+
asyncpg_engine: AsyncEngine,
139130
):
140131
osparc_product = {
141132
"name": "osparc",
@@ -172,9 +163,7 @@ async def test_insert_select_product(
172163
],
173164
}
174165

175-
print(json.dumps(osparc_product))
176-
177-
async with aiopg_engine.acquire() as conn:
166+
async with asyncpg_engine.begin() as conn:
178167
# writes
179168
stmt = (
180169
pg_insert(products)
@@ -188,12 +177,9 @@ async def test_insert_select_product(
188177

189178
# reads
190179
stmt = sa.select(products).where(products.c.name == name)
191-
row = await (await conn.execute(stmt)).fetchone()
192-
print(row)
180+
row = (await conn.execute(stmt)).one_or_none()
193181
assert row
194182

195-
pprint(dict(**row))
196-
197183
assert row.manuals
198184
assert row.manuals == osparc_product["manuals"]
199185

packages/postgres-database/tests/products/test_products_to_templates.py

Lines changed: 53 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -10,12 +10,12 @@
1010

1111
import pytest
1212
import sqlalchemy as sa
13-
from aiopg.sa.connection import SAConnection
1413
from faker import Faker
1514
from simcore_postgres_database.models.jinja2_templates import jinja2_templates
1615
from simcore_postgres_database.models.products import products
1716
from simcore_postgres_database.models.products_to_templates import products_to_templates
1817
from sqlalchemy.dialects.postgresql import insert as pg_insert
18+
from sqlalchemy.ext.asyncio import AsyncEngine
1919

2020

2121
@pytest.fixture
@@ -48,54 +48,58 @@ def templates_dir(
4848

4949
@pytest.fixture
5050
async def product_templates_in_db(
51-
connection: SAConnection,
51+
asyncpg_engine: AsyncEngine,
5252
make_products_table: Callable,
5353
products_names: list[str],
5454
templates_names: list[str],
5555
):
56-
await make_products_table(connection)
57-
58-
# one version of all tempaltes
59-
for template_name in templates_names:
60-
await connection.execute(
61-
jinja2_templates.insert().values(
62-
name=template_name, content="fake template in database"
56+
async with asyncpg_engine.begin() as conn:
57+
await make_products_table(conn)
58+
59+
# one version of all tempaltes
60+
for template_name in templates_names:
61+
await conn.execute(
62+
jinja2_templates.insert().values(
63+
name=template_name, content="fake template in database"
64+
)
6365
)
64-
)
6566

66-
# only even products have templates
67-
for product_name in products_names[0::2]:
68-
await connection.execute(
69-
products_to_templates.insert().values(
70-
template_name=template_name, product_name=product_name
67+
# only even products have templates
68+
for product_name in products_names[0::2]:
69+
await conn.execute(
70+
products_to_templates.insert().values(
71+
template_name=template_name, product_name=product_name
72+
)
7173
)
72-
)
7374

7475

7576
async def test_export_and_import_table(
76-
connection: SAConnection,
77+
asyncpg_engine: AsyncEngine,
7778
product_templates_in_db: None,
7879
):
79-
exported_values = []
80-
excluded_names = {"created", "modified", "group_id"}
81-
async for row in connection.execute(
82-
sa.select(*(c for c in products.c if c.name not in excluded_names))
83-
):
84-
assert row
85-
exported_values.append(dict(row))
86-
87-
# now just upsert them
88-
for values in exported_values:
89-
values["display_name"] += "-changed"
90-
await connection.execute(
91-
pg_insert(products)
92-
.values(**values)
93-
.on_conflict_do_update(index_elements=[products.c.name], set_=values)
80+
81+
async with asyncpg_engine.connect() as connection:
82+
exported_values = []
83+
excluded_names = {"created", "modified", "group_id"}
84+
result = await connection.stream(
85+
sa.select(*(c for c in products.c if c.name not in excluded_names))
9486
)
87+
async for row in result:
88+
assert row
89+
exported_values.append(row._asdict())
90+
91+
# now just upsert them
92+
for values in exported_values:
93+
values["display_name"] += "-changed"
94+
await connection.execute(
95+
pg_insert(products)
96+
.values(**values)
97+
.on_conflict_do_update(index_elements=[products.c.name], set_=values)
98+
)
9599

96100

97101
async def test_create_templates_products_folder(
98-
connection: SAConnection,
102+
asyncpg_engine: AsyncEngine,
99103
templates_dir: Path,
100104
products_names: list[str],
101105
tmp_path: Path,
@@ -121,20 +125,22 @@ async def test_create_templates_products_folder(
121125
shutil.copy(p, product_folder / p.name, follow_symlinks=False)
122126

123127
# overrides if with files in database
124-
async for row in connection.execute(
125-
sa.select(
126-
products_to_templates.c.product_name,
127-
jinja2_templates.c.name,
128-
jinja2_templates.c.content,
128+
async with asyncpg_engine.connect() as conn:
129+
result = await conn.stream(
130+
sa.select(
131+
products_to_templates.c.product_name,
132+
jinja2_templates.c.name,
133+
jinja2_templates.c.content,
134+
)
135+
.select_from(products_to_templates.join(jinja2_templates))
136+
.where(products_to_templates.c.product_name == product_name)
129137
)
130-
.select_from(products_to_templates.join(jinja2_templates))
131-
.where(products_to_templates.c.product_name == product_name)
132-
):
133-
assert row
134138

135-
template_path = product_folder / row.name
136-
template_path.write_text(row.content)
139+
async for row in result:
140+
assert row
141+
template_path = product_folder / row.name
142+
template_path.write_text(row.content)
137143

138-
assert sorted(
139-
product_folder / template_name for template_name in templates_names
140-
) == sorted(product_folder.rglob("*.*"))
144+
assert sorted(
145+
product_folder / template_name for template_name in templates_names
146+
) == sorted(product_folder.rglob("*.*"))

packages/postgres-database/tests/products/test_utils_products.py

Lines changed: 2 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@
33
# pylint: disable=redefined-outer-name
44
# pylint: disable=unused-argument
55

6-
import asyncio
76
from collections.abc import Callable
87

98
import pytest
@@ -13,7 +12,6 @@
1312
from simcore_postgres_database.utils_products import (
1413
execute_get_or_create_product_group,
1514
get_default_product_name,
16-
get_or_create_product_group,
1715
get_product_group_id,
1816
)
1917
from sqlalchemy.ext.asyncio import AsyncEngine
@@ -22,7 +20,7 @@
2220
async def test_default_product(
2321
asyncpg_engine: AsyncEngine, make_products_table: Callable
2422
):
25-
async with asyncpg_engine.connect() as conn:
23+
async with asyncpg_engine.begin() as conn:
2624
await make_products_table(conn)
2725
default_product = await get_default_product_name(conn)
2826
assert default_product == "s4l"
@@ -31,7 +29,7 @@ async def test_default_product(
3129
@pytest.mark.parametrize("pg_sa_engine", ["sqlModels"], indirect=True)
3230
async def test_default_product_undefined(asyncpg_engine: AsyncEngine):
3331
async with asyncpg_engine.connect() as conn:
34-
with pytest.raises(ValueError):
32+
with pytest.raises(ValueError, match="No product"):
3533
await get_default_product_name(conn)
3634

3735

@@ -100,32 +98,3 @@ async def test_get_or_create_group_product(
10098
conn, product_name=product_row.name
10199
)
102100
assert product_group_id is None
103-
104-
105-
@pytest.mark.skip(
106-
reason="Not relevant. Will review in https://github.com/ITISFoundation/osparc-simcore/issues/3754"
107-
)
108-
async def test_get_or_create_group_product_concurrent(
109-
asyncpg_engine: AsyncEngine, make_products_table: Callable
110-
):
111-
async with asyncpg_engine.connect() as conn:
112-
await make_products_table(conn)
113-
114-
async def _auto_create_products_groups():
115-
async with asyncpg_engine.connect() as conn:
116-
async for product_row in await conn.stream(
117-
sa.select(products.c.name, products.c.group_id).order_by(
118-
products.c.priority
119-
)
120-
):
121-
# get or create
122-
return await get_or_create_product_group(
123-
conn, product_name=product_row.name
124-
)
125-
return None
126-
127-
tasks = [asyncio.create_task(_auto_create_products_groups()) for _ in range(5)]
128-
129-
results = await asyncio.gather(*tasks)
130-
131-
assert all(res == results[0] for res in results[1:])

services/catalog/src/simcore_service_catalog/db/repositories/products.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,6 @@
55

66
class ProductsRepository(BaseRepository):
77
async def get_default_product_name(self) -> str:
8-
async with self.db_engine.begin() as conn:
8+
async with self.db_engine.connect() as conn:
99
product_name: str = await get_default_product_name(conn)
1010
return product_name

services/web/server/src/simcore_service_webserver/products/_repository.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -68,8 +68,8 @@ async def _get_product_payment_fields(
6868
min_payment_amount_usd=None,
6969
)
7070

71-
assert price_info.usd_per_credit > 0
72-
assert price_info.min_payment_amount_usd > 0
71+
assert price_info.usd_per_credit > 0 # nosec
72+
assert price_info.min_payment_amount_usd > 0 # nosec
7373

7474
return PaymentFieldsTuple(
7575
enabled=True,

0 commit comments

Comments
 (0)