๐Ÿ“ฆ aminalaee / sqladmin

๐Ÿ“„ test_ajax.py ยท 313 lines
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313from typing import Any, AsyncGenerator

import pytest
from httpx import ASGITransport, AsyncClient
from sqlalchemy import Column, ForeignKey, Integer, String, select
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import declarative_base, relationship, selectinload, sessionmaker
from starlette.applications import Starlette

from sqladmin import Admin, ModelView
from sqladmin.ajax import create_ajax_loader
from tests.common import async_engine as engine

pytestmark = pytest.mark.anyio

Base = declarative_base()  # type: Any
session_maker = sessionmaker(bind=engine, class_=AsyncSession, expire_on_commit=False)

app = Starlette()
admin = Admin(app=app, engine=engine)


class User(Base):
    __tablename__ = "users"

    id = Column(Integer, primary_key=True)
    name = Column(String(length=16))

    addresses = relationship("Address", back_populates="user")
    rooms = relationship("Room", back_populates="user")

    def __str__(self) -> str:
        return f"User {self.id}"


class City(Base):
    __tablename__ = "cities"

    id = Column(Integer, primary_key=True)
    name = Column(String(length=16))
    state = Column(String(length=3))

    addresses = relationship("Address", back_populates="city")
    rooms = relationship("Room", back_populates="city")

    def __str__(self) -> str:
        return f"{self.name}, {self.state}"


class Address(Base):
    __tablename__ = "addresses"

    id = Column(Integer, primary_key=True)
    user_id = Column(Integer, ForeignKey("users.id"))
    city_id = Column(Integer, ForeignKey("cities.id"))

    user = relationship("User", back_populates="addresses")
    city = relationship("City", back_populates="addresses")

    def __str__(self) -> str:
        return f"Address {self.id}"


class Room(Base):
    __tablename__ = "rooms"

    id = Column(Integer, primary_key=True)
    user_id = Column(Integer, ForeignKey("users.id"))
    city_id = Column(Integer, ForeignKey("cities.id"))

    user = relationship("User", back_populates="rooms")
    city = relationship("City", back_populates="rooms")

    def __str__(self) -> str:
        return f"Room {self.id}"


class UserAdmin(ModelView, model=User):
    form_ajax_refs = {
        "addresses": {
            "fields": ("id",),
        }
    }


class AddressAdmin(ModelView, model=Address):
    form_ajax_refs = {
        "user": {
            "fields": ("name",),
            "order_by": ("id"),
        },
        "city": {
            "fields": ("name", "state"),
            "order_by": ["state", "id"],
            "limit": 2,
        },
    }


class RoomAdmin(ModelView, model=Room):
    form_ajax_refs = {
        "user": {"fields": ("name",), "order_by": ("id"), "limit": 3},
        "city": {
            "fields": ("name", "state"),
            "order_by": ["state", "name"],
            "limit": 2,
        },
    }


admin.add_view(UserAdmin)
admin.add_view(AddressAdmin)
admin.add_view(RoomAdmin)


@pytest.fixture
async def prepare_database() -> AsyncGenerator[None, None]:
    async with engine.begin() as conn:
        await conn.run_sync(Base.metadata.create_all)
    yield
    async with engine.begin() as conn:
        await conn.run_sync(Base.metadata.drop_all)
    await engine.dispose()


@pytest.fixture
async def client(prepare_database: Any) -> AsyncGenerator[AsyncClient, None]:
    transport = ASGITransport(app=app)
    async with AsyncClient(transport=transport, base_url="http://testserver") as client:
        yield client


async def test_ajax_lookup_invalid_query_params(client: AsyncClient) -> None:
    response = await client.get("/admin/user/ajax/lookup")
    assert response.status_code == 400

    response = await client.get("/admin/address/ajax/lookup")
    assert response.status_code == 400

    response = await client.get("/admin/user/ajax/lookup?name=test&term=x")
    assert response.status_code == 400


async def test_ajax_response_test(client: AsyncClient) -> None:
    user = User(name="John Snow")
    async with session_maker() as s:
        s.add(user)
        await s.commit()

    response = await client.get("/admin/address/ajax/lookup?name=user&term=john")

    assert response.status_code == 200
    assert response.json() == {"results": [{"id": "1", "text": "User 1"}]}


async def test_ajax_response_order_by(client: AsyncClient) -> None:
    async with session_maker() as s:
        s.add(City(name="Sydney", state="NSW"))
        s.add(City(name="Melbourne", state="VIC"))
        s.add(City(name="Newcastle", state="NSW"))
        s.add(City(name="Byron Bay", state="NSW"))
        s.add(City(name="Melbourne", state="TAS"))
        await s.commit()

    response = await client.get("/admin/address/ajax/lookup?name=city&term=nsw")
    # Sorted by state then id
    assert response.status_code == 200
    assert response.json() == {
        "results": [
            {"id": "1", "text": "Sydney, NSW"},
            {"id": "3", "text": "Newcastle, NSW"},
        ]
    }

    response = await client.get("/admin/room/ajax/lookup?name=city&term=nsw")
    # Sorted by state then name
    assert response.status_code == 200
    assert response.json() == {
        "results": [
            {"id": "4", "text": "Byron Bay, NSW"},
            {"id": "3", "text": "Newcastle, NSW"},
        ]
    }
    response = await client.get("/admin/room/ajax/lookup?name=city&term=melb")
    # Sorted by state then name
    assert response.status_code == 200
    assert response.json() == {
        "results": [
            {"id": "5", "text": "Melbourne, TAS"},
            {"id": "2", "text": "Melbourne, VIC"},
        ]
    }


async def test_ajax_response_limit(client: AsyncClient) -> None:
    users_to_create = 5
    user_list = [User(name=f"John Snow {i}") for i in range(users_to_create)]
    async with session_maker() as s:
        for user in user_list:
            s.add(user)
        await s.commit()

    response = await client.get("/admin/address/ajax/lookup?name=user&term=john")

    assert response.status_code == 200
    # Address admin has no limit so will return all created users
    # (up to default cap of 10)
    assert response.json() == {
        "results": [
            {"id": f"{i + 1}", "text": f"User {i + 1}"} for i in range(users_to_create)
        ]
    }

    response = await client.get("/admin/room/ajax/lookup?name=user&term=john")

    assert response.status_code == 200
    # Room admin has a limit 3 of
    assert response.json() == {
        "results": [{"id": f"{i + 1}", "text": f"User {i + 1}"} for i in range(3)]
    }


async def test_create_ajax_loader_exceptions() -> None:
    with pytest.raises(ValueError):
        create_ajax_loader(model_admin=AddressAdmin(), name="x", options={})

    with pytest.raises(ValueError):
        create_ajax_loader(model_admin=AddressAdmin(), name="user", options={})


async def test_create_page_template(client: AsyncClient) -> None:
    response = await client.get("/admin/user/create")

    assert 'data-json="[]"' in response.text
    assert 'data-role="select2-ajax"' in response.text
    assert 'data-url="/admin/user/ajax/lookup"' in response.text

    response = await client.get("/admin/address/create")

    assert 'data-role="select2-ajax"' in response.text
    assert 'data-url="/admin/address/ajax/lookup"' in response.text


async def test_edit_page_template(client: AsyncClient) -> None:
    user = User(name="John Snow")
    async with session_maker() as s:
        s.add(user)
        await s.flush()

        address = Address(user=user)
        s.add(address)
        await s.commit()

    response = await client.get("/admin/user/edit/1")
    assert (
        'data-json="[{"id": "1", "text": "Address 1"}]"'
        in response.text
    )
    assert 'data-role="select2-ajax"' in response.text
    assert 'data-url="/admin/user/ajax/lookup"' in response.text

    response = await client.get("/admin/address/edit/1")
    assert (
        'data-json="[{"id": "1", "text": "User 1"}]"'
        in response.text
    )
    assert 'data-role="select2-ajax"' in response.text
    assert 'data-url="/admin/address/ajax/lookup"' in response.text


async def test_create_and_edit_forms(client: AsyncClient) -> None:
    response = await client.post("/admin/address/create", data={})
    assert response.status_code == 302
    response = await client.post("/admin/address/create", data={"id": "2"})
    assert response.status_code == 302

    data = {"addresses": ["1"], "name": "Tyrion"}
    response = await client.post("/admin/user/create", data=data)
    assert response.status_code == 302

    data = {}
    response = await client.post("/admin/address/edit/1", data=data)
    assert response.status_code == 302

    async with session_maker() as s:
        stmt = select(User).options(selectinload(User.addresses))
        result = await s.execute(stmt)

    user = result.scalar_one()
    assert len(user.addresses) == 0

    data = {"addresses": ["1"]}
    response = await client.post("/admin/user/edit/1", data=data)
    assert response.status_code == 302

    async with session_maker() as s:
        stmt = select(User).options(selectinload(User.addresses))
        result = await s.execute(stmt)

    user = result.scalar_one()
    assert len(user.addresses) == 1

    data = {"addresses": ["1", "2"]}
    response = await client.post("/admin/user/edit/1", data=data)
    assert response.status_code == 302

    async with session_maker() as s:
        stmt = select(User).options(selectinload(User.addresses))
        result = await s.execute(stmt)

    user = result.scalar_one()
    assert len(user.addresses) == 2