new api service and logic implemented

This commit is contained in:
2025-01-23 22:27:25 +03:00
parent d91ecda9df
commit 32022ca521
245 changed files with 28004 additions and 0 deletions

46
Ztest/Dockerfile Normal file
View File

@@ -0,0 +1,46 @@
# Use Python 3.9 as base image
FROM python:3.9-slim
# Set environment variables
ENV PYTHONUNBUFFERED=1 \
PYTHONDONTWRITEBYTECODE=1 \
PIP_NO_CACHE_DIR=1 \
POETRY_VERSION=1.7.1 \
POETRY_HOME="/opt/poetry" \
POETRY_VIRTUALENVS_CREATE=false \
PYTHONPATH=/app
# Add Poetry to PATH
ENV PATH="$POETRY_HOME/bin:$PATH"
# Install system dependencies
RUN apt-get update \
&& apt-get install -y --no-install-recommends \
curl \
build-essential \
libpq-dev \
postgresql-client \
&& rm -rf /var/lib/apt/lists/*
# Install Poetry
RUN curl -sSL https://install.python-poetry.org | python3 -
# Set working directory
WORKDIR /app
# Copy project files
COPY pyproject.toml poetry.lock* ./
# Install dependencies
RUN poetry install --no-root --no-interaction --no-ansi
# Copy required directories
COPY Ztest/ ./Ztest/
COPY Services/ ./Services/
COPY AllConfigs/ ./AllConfigs/
COPY ApiLibrary/ ./ApiLibrary/
COPY ErrorHandlers/ ./ErrorHandlers/
# Set entrypoint for running tests
ENTRYPOINT ["poetry", "run", "pytest"]
CMD ["-v", "--cov=Services", "Ztest/"]

13
Ztest/fixtures.py Normal file
View File

@@ -0,0 +1,13 @@
"""Test fixtures and models."""
from sqlalchemy import Column, String
from Services.PostgresDb.Models.mixins import CrudCollection
class TestUser(CrudCollection):
"""Test user model for PostgreSQL tests."""
__tablename__ = "test_users"
username = Column(String, unique=True, index=True)
email = Column(String, unique=True, index=True)

13
Ztest/models.py Normal file
View File

@@ -0,0 +1,13 @@
"""Test models."""
from sqlalchemy import Column, String
from Services.PostgresDb.Models.mixins import CrudCollection
class UserModel(CrudCollection):
"""User model for PostgreSQL tests."""
__tablename__ = "test_users"
username = Column(String, unique=True, index=True)
email = Column(String, unique=True, index=True)

38
Ztest/test.py Normal file
View File

@@ -0,0 +1,38 @@
import secrets
import uuid
from Services.Redis import RedisActions, AccessToken
first_user = AccessToken(
accessToken=secrets.token_urlsafe(90),
userUUID=uuid.uuid4().__str__(),
)
second_user = AccessToken(
accessToken=secrets.token_urlsafe(90),
userUUID=uuid.uuid4().__str__(),
)
json_data = lambda uu_id, access: {
"uu_id": uu_id,
"access_token": access,
"user_type": 1,
"selected_company": None,
"selected_occupant": None,
"reachable_event_list_id": [],
}
set_response_first_json = json_data(first_user.userUUID, first_user.accessToken)
set_response_second_json = json_data(second_user.userUUID, second_user.accessToken)
set_response_first = RedisActions.set_json(
list_keys=first_user.to_list(),
value=set_response_first_json,
expires={"seconds": 140},
)
set_response_second = RedisActions.set_json(
list_keys=second_user.to_list(),
value=set_response_second_json,
expires={"seconds": 190},
)
search_keys = [None, "*a*"]
get_response = RedisActions.get_json(list_keys=search_keys)
print("get_response.all", get_response.as_dict()["data"].values())

104
Ztest/test_mongo.py Normal file
View File

@@ -0,0 +1,104 @@
"""Test MongoDB actions and models."""
import pytest
from pymongo import MongoClient
from Services.MongoDb.Models.actions import MongoActions
from Services.MongoDb.Models.action_models.domain import (
DomainData,
DomainDocumentCreate,
DomainDocumentUpdate,
)
from AllConfigs.NoSqlDatabase.configs import MongoConfig
@pytest.fixture
def mongo_client():
"""Create MongoDB test client."""
# Connect using configured credentials
client = MongoClient(MongoConfig.URL)
client.admin.command("ping") # Test connection
yield client
client.close()
@pytest.fixture
def mongo_actions(mongo_client):
"""Create MongoActions instance for testing."""
if not mongo_client:
pytest.skip("MongoDB connection not available")
actions = MongoActions(
client=mongo_client,
database=MongoConfig.DATABASE_NAME,
company_uuid="test_company",
storage_reason="domains",
)
yield actions
try:
# Cleanup after tests
if actions.collection is not None:
actions.collection.drop()
except Exception as e:
print(f"Failed to cleanup test collection: {e}")
def test_mongo_crud_operations(mongo_actions: MongoActions):
"""Test CRUD operations with MongoActions."""
# Create test data
domain_data = DomainData(
user_uu_id="test_user",
main_domain="example.com",
other_domains_list=["old.com"],
)
create_doc = DomainDocumentCreate(data=domain_data)
# Test create
result = mongo_actions.insert_one(create_doc.model_dump())
assert result.inserted_id is not None
# Test read
doc = mongo_actions.find_one({"data.main_domain": "example.com"})
assert doc is not None
assert doc["data"]["main_domain"] == "example.com"
# Test update
update_data = DomainData(
user_uu_id="test_user",
main_domain="new.com",
other_domains_list=["example.com", "old.com"],
)
update_doc = DomainDocumentUpdate(data=update_data)
result = mongo_actions.update_one(
{"_id": doc["_id"]}, {"$set": update_doc.model_dump()}
)
assert result.modified_count == 1
# Test delete
result = mongo_actions.delete_one({"_id": doc["_id"]})
assert result.deleted_count == 1
def test_mongo_aggregate(mongo_actions: MongoActions):
"""Test aggregate operations with MongoActions."""
# Insert test documents
docs = [
DomainDocumentCreate(
data=DomainData(user_uu_id="user1", main_domain=f"domain{i}.com")
).model_dump()
for i in range(3)
]
mongo_actions.insert_many(docs)
# Test aggregation
pipeline = [{"$group": {"_id": "$data.user_uu_id", "count": {"$sum": 1}}}]
result = mongo_actions.aggregate(pipeline)
result_list = list(result)
assert len(result_list) == 1
assert result_list[0]["count"] == 3
if __name__ == "__main__":
pytest.main([__file__, "-v"])

99
Ztest/test_postgres.py Normal file
View File

@@ -0,0 +1,99 @@
"""Test PostgreSQL database operations."""
import pytest
from sqlalchemy import create_engine, text
from sqlalchemy.orm import Session
from Services.PostgresDb.database import Base, get_db
from AllConfigs.SqlDatabase.configs import WagDatabase
from Ztest.models import UserModel
@pytest.fixture(scope="session")
def db_engine():
"""Create a test database engine."""
# Use the same database URL but with test database
test_db_url = WagDatabase.DATABASE_URL
engine = create_engine(test_db_url, echo=True)
# Create all tables
Base.metadata.create_all(bind=engine)
yield engine
# Drop all tables after tests
Base.metadata.drop_all(bind=engine)
@pytest.fixture
def db_session(db_engine):
"""Create a test database session."""
connection = db_engine.connect()
transaction = connection.begin()
session = Session(bind=connection)
yield session
# Rollback the transaction after each test
transaction.rollback()
connection.close()
session.close()
def test_create_user(db_session):
"""Test creating a user in the database."""
# Create user using CrudMixin methods
user = UserModel(username="testuser", email="test@example.com")
db_session.add(user)
db_session.commit()
# Verify user was created
db_user = db_session.query(UserModel).filter_by(username="testuser").first()
assert db_user is not None
assert db_user.email == "test@example.com"
assert db_user.created_at is not None
assert not db_user.deleted
assert db_user.active
def test_update_user(db_session):
"""Test updating a user in the database."""
# Create user
user = UserModel(username="updateuser", email="update@example.com")
db_session.add(user)
db_session.commit()
# Update user using CrudMixin methods
user.update(db=db_session, email="newemail@example.com")
db_session.commit()
# Verify update
updated_user = db_session.query(UserModel).filter_by(username="updateuser").first()
assert updated_user.email == "newemail@example.com"
assert updated_user.updated_at is not None
def test_soft_delete_user(db_session):
"""Test soft deleting a user from the database."""
# Create user
user = UserModel(username="deleteuser", email="delete@example.com")
db_session.add(user)
db_session.commit()
# Soft delete by updating deleted and active flags
user.update(db=db_session, deleted=True, active=False)
db_session.commit()
# Verify soft deletion
deleted_user = db_session.query(UserModel).filter_by(username="deleteuser").first()
assert deleted_user is not None
assert deleted_user.deleted
assert not deleted_user.active
def test_get_db_context_manager():
"""Test the get_db context manager."""
with get_db() as session:
# Verify we can execute a simple query
result = session.execute(text("SELECT 1"))
assert result.scalar() == 1