Initial commit

This commit is contained in:
John Wang
2023-05-15 08:51:32 +08:00
commit db896255d6
744 changed files with 56028 additions and 0 deletions

0
api/tests/__init__.py Normal file
View File

50
api/tests/conftest.py Normal file
View File

@@ -0,0 +1,50 @@
# -*- coding:utf-8 -*-
import pytest
import flask_migrate
from app import create_app
from extensions.ext_database import db
@pytest.fixture(scope='module')
def test_client():
# Create a Flask app configured for testing
from config import TestConfig
flask_app = create_app(TestConfig())
flask_app.config.from_object('config.TestingConfig')
# Create a test client using the Flask application configured for testing
with flask_app.test_client() as testing_client:
# Establish an application context
with flask_app.app_context():
yield testing_client # this is where the testing happens!
@pytest.fixture(scope='module')
def init_database(test_client):
# Initialize the database
with test_client.application.app_context():
flask_migrate.upgrade()
yield # this is where the testing happens!
# Clean up the database
with test_client.application.app_context():
flask_migrate.downgrade()
@pytest.fixture(scope='module')
def db_session(test_client):
with test_client.application.app_context():
yield db.session
@pytest.fixture(scope='function')
def login_default_user(test_client):
# todo
yield # this is where the testing happens!
test_client.get('/logout', follow_redirects=True)

View File

View File

@@ -0,0 +1,75 @@
import json
import pytest
from flask import url_for
from models.model import Account
# Sample user data for testing
sample_user_data = {
'name': 'Test User',
'email': 'test@example.com',
'interface_language': 'en-US',
'interface_theme': 'light',
'timezone': 'America/New_York',
'password': 'testpassword',
'new_password': 'newtestpassword',
'repeat_new_password': 'newtestpassword'
}
# Create a test user and log them in
@pytest.fixture(scope='function')
def logged_in_user(client, session):
# Create test user and add them to the database
# Replace this with your actual User model and any required fields
# todo refer to api.controllers.setup.SetupApi.post() to create a user
db_user_data = sample_user_data.copy()
db_user_data['password_salt'] = 'testpasswordsalt'
del db_user_data['new_password']
del db_user_data['repeat_new_password']
test_user = Account(**db_user_data)
session.add(test_user)
session.commit()
# Log in the test user
client.post(url_for('console.loginapi'), data={'email': sample_user_data['email'], 'password': sample_user_data['password']})
return test_user
def test_account_profile(logged_in_user, client):
response = client.get(url_for('console.accountprofileapi'))
assert response.status_code == 200
assert json.loads(response.data)['name'] == sample_user_data['name']
def test_account_name(logged_in_user, client):
new_name = 'New Test User'
response = client.post(url_for('console.accountnameapi'), json={'name': new_name})
assert response.status_code == 200
assert json.loads(response.data)['name'] == new_name
def test_account_interface_language(logged_in_user, client):
new_language = 'zh-CN'
response = client.post(url_for('console.accountinterfacelanguageapi'), json={'interface_language': new_language})
assert response.status_code == 200
assert json.loads(response.data)['interface_language'] == new_language
def test_account_interface_theme(logged_in_user, client):
new_theme = 'dark'
response = client.post(url_for('console.accountinterfacethemeapi'), json={'interface_theme': new_theme})
assert response.status_code == 200
assert json.loads(response.data)['interface_theme'] == new_theme
def test_account_timezone(logged_in_user, client):
new_timezone = 'Asia/Shanghai'
response = client.post(url_for('console.accounttimezoneapi'), json={'timezone': new_timezone})
assert response.status_code == 200
assert json.loads(response.data)['timezone'] == new_timezone
def test_account_password(logged_in_user, client):
response = client.post(url_for('console.accountpasswordapi'), json={
'password': sample_user_data['password'],
'new_password': sample_user_data['new_password'],
'repeat_new_password': sample_user_data['repeat_new_password']
})
assert response.status_code == 200
assert json.loads(response.data)['result'] == 'success'

View File

@@ -0,0 +1,108 @@
import pytest
from app import create_app, db
from flask_login import current_user
from models.model import Account, TenantAccountJoin, Tenant
@pytest.fixture
def client(test_client, db_session):
app = create_app()
app.config["TESTING"] = True
with app.app_context():
db.create_all()
yield test_client
db.drop_all()
def test_login_api_post(client, db_session):
# create a tenant, account, and tenant account join
tenant = Tenant(name="Test Tenant", status="normal")
account = Account(email="test@test.com", name="Test User")
account.password_salt = "uQ7K0/0wUJ7VPhf3qBzwNQ=="
account.password = "A9YpfzjK7c/tOwzamrvpJg=="
db.session.add_all([tenant, account])
db.session.flush()
tenant_account_join = TenantAccountJoin(tenant_id=tenant.id, account_id=account.id, is_tenant_owner=True)
db.session.add(tenant_account_join)
db.session.commit()
# login with correct credentials
response = client.post("/login", json={
"email": "test@test.com",
"password": "Abc123456",
"remember_me": True
})
assert response.status_code == 200
assert response.json == {"result": "success"}
assert current_user == account
assert 'tenant_id' in client.session
assert client.session['tenant_id'] == tenant.id
# login with incorrect password
response = client.post("/login", json={
"email": "test@test.com",
"password": "wrong_password",
"remember_me": True
})
assert response.status_code == 401
# login with non-existent account
response = client.post("/login", json={
"email": "non_existent_account@test.com",
"password": "Abc123456",
"remember_me": True
})
assert response.status_code == 401
def test_logout_api_get(client, db_session):
# create a tenant, account, and tenant account join
tenant = Tenant(name="Test Tenant", status="normal")
account = Account(email="test@test.com", name="Test User")
db.session.add_all([tenant, account])
db.session.flush()
tenant_account_join = TenantAccountJoin(tenant_id=tenant.id, account_id=account.id, is_tenant_owner=True)
db.session.add(tenant_account_join)
db.session.commit()
# login and check if session variable and current_user are set
with client.session_transaction() as session:
session['tenant_id'] = tenant.id
client.post("/login", json={
"email": "test@test.com",
"password": "Abc123456",
"remember_me": True
})
assert current_user == account
assert 'tenant_id' in client.session
assert client.session['tenant_id'] == tenant.id
# logout and check if session variable and current_user are unset
response = client.get("/logout")
assert response.status_code == 200
assert current_user.is_authenticated is False
assert 'tenant_id' not in client.session
def test_reset_password_api_get(client, db_session):
# create a tenant, account, and tenant account join
tenant = Tenant(name="Test Tenant", status="normal")
account = Account(email="test@test.com", name="Test User")
db.session.add_all([tenant, account])
db.session.flush()
tenant_account_join = TenantAccountJoin(tenant_id=tenant.id, account_id=account.id, is_tenant_owner=True)
db.session.add(tenant_account_join)
db.session.commit()
# reset password in cloud edition
app = client.application
app.config["CLOUD_EDITION"] = True
response = client.get("/reset_password")
assert response.status_code == 200
assert response.json == {"result": "success"}
# reset password in non-cloud edition
app.config["CLOUD_EDITION"] = False
response = client.get("/reset_password")
assert response.status_code == 200
assert response.json == {"result": "success"}

View File

@@ -0,0 +1,80 @@
import os
import pytest
from models.model import Account, Tenant, TenantAccountJoin
def test_setup_api_get(test_client,db_session):
response = test_client.get("/setup")
assert response.status_code == 200
assert response.json == {"step": "not_start"}
# create a tenant and check again
tenant = Tenant(name="Test Tenant", status="normal")
db_session.add(tenant)
db_session.commit()
response = test_client.get("/setup")
assert response.status_code == 200
assert response.json == {"step": "step2"}
# create setup file and check again
response = test_client.get("/setup")
assert response.status_code == 200
assert response.json == {"step": "finished"}
def test_setup_api_post(test_client):
response = test_client.post("/setup", json={
"email": "test@test.com",
"name": "Test User",
"password": "Abc123456"
})
assert response.status_code == 200
assert response.json == {"result": "success", "next_step": "step2"}
# check if the tenant, account, and tenant account join records were created
tenant = Tenant.query.first()
assert tenant.name == "Test User's LLM Factory"
assert tenant.status == "normal"
assert tenant.encrypt_public_key
account = Account.query.first()
assert account.email == "test@test.com"
assert account.name == "Test User"
assert account.password_salt
assert account.password
assert TenantAccountJoin.query.filter_by(account_id=account.id, is_tenant_owner=True).count() == 1
# check if password is encrypted correctly
salt = account.password_salt.encode()
password_hashed = account.password.encode()
assert account.password == base64.b64encode(hash_password("Abc123456", salt)).decode()
def test_setup_step2_api_post(test_client,db_session):
# create a tenant, account, and setup file
tenant = Tenant(name="Test Tenant", status="normal")
account = Account(email="test@test.com", name="Test User")
db_session.add_all([tenant, account])
db_session.commit()
# try to set up with incorrect language
response = test_client.post("/setup/step2", json={
"interface_language": "invalid_language",
"timezone": "Asia/Shanghai"
})
assert response.status_code == 400
# set up successfully
response = test_client.post("/setup/step2", json={
"interface_language": "en",
"timezone": "Asia/Shanghai"
})
assert response.status_code == 200
assert response.json == {"result": "success", "next_step": "finished"}
# check if account was updated correctly
account = Account.query.first()
assert account.interface_language == "en"
assert account.timezone == "Asia/Shanghai"
assert account.interface_theme == "light"
assert account.last_login_ip == "127.0.0.1"

22
api/tests/test_factory.py Normal file
View File

@@ -0,0 +1,22 @@
# -*- coding:utf-8 -*-
import pytest
from app import create_app
def test_create_app():
# Test Default(CE) Config
app = create_app()
assert app.config['SECRET_KEY'] is not None
assert app.config['SQLALCHEMY_DATABASE_URI'] is not None
assert app.config['EDITION'] == "SELF_HOSTED"
# Test TestConfig
from config import TestConfig
test_app = create_app(TestConfig())
assert test_app.config['SECRET_KEY'] is not None
assert test_app.config['SQLALCHEMY_DATABASE_URI'] is not None
assert test_app.config['TESTING'] is True

View File

View File

View File

View File