Skip to content

Commit 768a13f

Browse files
authored
add test code (#37)
* add test code * add a pre test prompt * exec pre-commit
1 parent a19d942 commit 768a13f

File tree

6 files changed

+142
-0
lines changed

6 files changed

+142
-0
lines changed

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,3 +7,4 @@ backend/app/log/
77
backend/app/alembic/versions/
88
backend/app/static/media/
99
.ruff_cache/
10+
.pytest_cache/

README.md

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,3 +70,21 @@ git clone https://github.com/wu-clan/fastapi_best_architecture.git
7070
## Init the test data
7171

7272
Execute the `backend/app/init_test_data.py` file
73+
74+
## Test
75+
76+
Perform tests via pytest
77+
78+
**Tip**: Before the test starts, please execute init the test data first, also, the fastapi service needs to be started
79+
80+
1. First, go to the app directory
81+
82+
```shell
83+
cd backend/app/
84+
```
85+
86+
2. Execute the test command
87+
88+
```shell
89+
pytest -vs --disable-warnings
90+
```

backend/app/init_test_data.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,22 @@ class InitData:
1717
def __init__(self):
1818
self.fake = Faker('zh_CN')
1919

20+
@staticmethod
21+
async def create_test_user():
22+
"""创建测试用户"""
23+
username = 'test'
24+
password = 'test'
25+
26+
user_obj = User(
27+
username=username,
28+
password=get_hash_password(password),
29+
email=email,
30+
is_superuser=True,
31+
)
32+
async with async_db_session.begin() as db:
33+
db.add(user_obj)
34+
log.info(f'测试用户创建成功,账号:{username},密码:{password}')
35+
2036
@staticmethod
2137
async def create_superuser_by_yourself():
2238
"""手动创建管理员账户"""
@@ -108,6 +124,7 @@ async def fake_no_active_superuser(self):
108124
async def init_data(self):
109125
"""自动创建数据"""
110126
log.info('⏳ 开始初始化数据')
127+
await self.create_test_user()
111128
await self.create_superuser_by_yourself()
112129
await self.fake_user()
113130
await self.fake_no_active_user()

backend/app/test/conftest.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
#!/usr/bin/env python3
2+
# -*- coding: utf-8 -*-
3+
import sys
4+
5+
import pytest
6+
from httpx import AsyncClient
7+
8+
sys.path.append('../../')
9+
10+
from backend.app.common.redis import redis_client # noqa: E402
11+
from backend.app.core.conf import settings # noqa: E402
12+
13+
14+
@pytest.fixture(scope='session')
15+
def anyio_backend():
16+
return 'asyncio'
17+
18+
19+
@pytest.fixture(scope='package', autouse=True)
20+
async def function_fixture(anyio_backend):
21+
auth_data = {
22+
'url': f'http://{settings.UVICORN_HOST}:{settings.UVICORN_PORT}{settings.TOKEN_URL}',
23+
'headers': {'accept': 'application/json', 'Content-Type': 'application/x-www-form-urlencoded'},
24+
'data': {'username': 'test', 'password': 'test'},
25+
}
26+
async with AsyncClient() as client:
27+
response = await client.post(**auth_data)
28+
token = response.json()['access_token']
29+
test_token = await redis_client.get('test_token')
30+
if not test_token:
31+
await redis_client.set('test_token', token, ex=86400)

backend/app/test/test_auth.py

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
#!/usr/bin/env python3
2+
# -*- coding: utf-8 -*-
3+
import sys
4+
5+
import pytest
6+
from faker import Faker
7+
from httpx import AsyncClient
8+
9+
sys.path.append('../../')
10+
11+
from backend.app.core.conf import settings # noqa: E402
12+
from backend.app.main import app # noqa: E402
13+
from backend.app.common.redis import redis_client # noqa: E402
14+
15+
16+
class TestAuth:
17+
pytestmark = pytest.mark.anyio
18+
faker = Faker(locale='zh_CN')
19+
users_api_base_url = f'http://{settings.UVICORN_HOST}:{settings.UVICORN_PORT}/v1/auth/users'
20+
21+
@property
22+
async def get_token(self):
23+
token = await redis_client.get('test_token')
24+
return token
25+
26+
async def test_login(self):
27+
async with AsyncClient(
28+
app=app, headers={'accept': 'application/json', 'Content-Type': 'application/x-www-form-urlencoded'}
29+
) as client:
30+
response = await client.post(
31+
url=f'{self.users_api_base_url}/login', data={'username': '1', 'password': '1'}
32+
)
33+
assert response.status_code == 200
34+
assert response.json()['token_type'] == 'Bearer'
35+
36+
async def test_register(self):
37+
async with AsyncClient(
38+
app=app, headers={'accept': 'application/json', 'Content-Type': 'application/json'}
39+
) as client:
40+
response = await client.post(
41+
url=f'{self.users_api_base_url}/register',
42+
json={
43+
'username': f'{self.faker.user_name()}',
44+
'password': f'{self.faker.password()}',
45+
'email': f'{self.faker.email()}',
46+
},
47+
)
48+
assert response.status_code == 200
49+
r_json = response.json()
50+
assert r_json['code'] == 200
51+
assert r_json['msg'] == 'Success'
52+
53+
async def test_get_userinfo(self):
54+
async with AsyncClient(
55+
app=app, headers={'accept': 'application/json', 'Authorization': f'Bearer {await self.get_token}'}
56+
) as client:
57+
response = await client.get(url=f'{self.users_api_base_url}/1')
58+
assert response.status_code == 200
59+
r_json = response.json()
60+
assert r_json['code'] == 200
61+
assert r_json['msg'] == 'Success'
62+
63+
async def test_get_all_users(self):
64+
async with AsyncClient(
65+
app=app, headers={'accept': 'application/json', 'Authorization': f'Bearer {await self.get_token}'}
66+
) as client:
67+
response = await client.get(url=f'{self.users_api_base_url}?page=1&size=20')
68+
assert response.status_code == 200
69+
r_json = response.json()
70+
assert isinstance(r_json['data'], list)
71+
assert isinstance(r_json['links'], dict)
72+
assert isinstance(r_json['links']['self'], str)

requirements.txt

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,11 +12,14 @@ fast-captcha==0.1.3
1212
fastapi==0.95.0
1313
fastapi-pagination==0.12.1
1414
gunicorn==20.1.0
15+
httpx==0.23.0
1516
loguru==0.6.0
1617
passlib==1.7.4
1718
path==15.1.2
1819
pre-commit==3.2.2
1920
pydantic==1.10.5
21+
pytest==7.2.2
22+
pytest-pretty==1.2.0
2023
python-jose==3.3.0
2124
python-multipart==0.0.5
2225
redis==4.5.4

0 commit comments

Comments
 (0)