black shift

This commit is contained in:
2025-04-22 11:10:29 +03:00
parent d7f1da8de8
commit e5f88f2eb4
30 changed files with 671 additions and 521 deletions

View File

@@ -22,7 +22,7 @@ def test_basic_crud_operations():
# First, clear any existing data
users_collection.delete_many({})
print("Cleared existing data")
# Insert multiple documents
insert_result = users_collection.insert_many(
[
@@ -58,7 +58,7 @@ def test_basic_crud_operations():
condition2 = admin_users and admin_users[0].get("username") == "jane"
condition3 = update_result.modified_count == 2
condition4 = delete_result.deleted_count == 1
print(f"Condition 1 (admin count): {condition1}")
print(f"Condition 2 (admin is jane): {condition2}")
print(f"Condition 3 (updated 2 users): {condition3}")
@@ -80,7 +80,7 @@ def test_nested_documents():
# Clear any existing data
products_collection.delete_many({})
print("Cleared existing data")
# Insert a product with nested data
insert_result = products_collection.insert_one(
{
@@ -110,15 +110,17 @@ def test_nested_documents():
print(f"Found updated laptop: {updated_laptop is not None}")
if updated_laptop:
print(f"Updated laptop specs: {updated_laptop.get('specs')}")
if 'specs' in updated_laptop:
if "specs" in updated_laptop:
print(f"Updated RAM: {updated_laptop['specs'].get('ram')}")
# Check each condition separately
condition1 = laptop is not None
condition2 = laptop and laptop.get('specs', {}).get('ram') == "16GB"
condition2 = laptop and laptop.get("specs", {}).get("ram") == "16GB"
condition3 = update_result.modified_count == 1
condition4 = updated_laptop and updated_laptop.get('specs', {}).get('ram') == "32GB"
condition4 = (
updated_laptop and updated_laptop.get("specs", {}).get("ram") == "32GB"
)
print(f"Condition 1 (laptop found): {condition1}")
print(f"Condition 2 (original RAM is 16GB): {condition2}")
print(f"Condition 3 (update modified 1 doc): {condition3}")
@@ -140,7 +142,7 @@ def test_array_operations():
# Clear any existing data
orders_collection.delete_many({})
print("Cleared existing data")
# Insert an order with array of items
insert_result = orders_collection.insert_one(
{
@@ -170,10 +172,12 @@ def test_array_operations():
# Verify the update
updated_order = orders_collection.find_one({"order_id": "ORD001"})
print(f"Found updated order: {updated_order is not None}")
if updated_order:
print(f"Number of items in order: {len(updated_order.get('items', []))}")
items = updated_order.get('items', [])
print(
f"Number of items in order: {len(updated_order.get('items', []))}"
)
items = updated_order.get("items", [])
if items:
last_item = items[-1] if items else None
print(f"Last item in order: {last_item}")
@@ -181,9 +185,13 @@ def test_array_operations():
# Check each condition separately
condition1 = len(laptop_orders) == 1
condition2 = update_result.modified_count == 1
condition3 = updated_order and len(updated_order.get('items', [])) == 3
condition4 = updated_order and updated_order.get('items', []) and updated_order['items'][-1].get('product') == "Keyboard"
condition3 = updated_order and len(updated_order.get("items", [])) == 3
condition4 = (
updated_order
and updated_order.get("items", [])
and updated_order["items"][-1].get("product") == "Keyboard"
)
print(f"Condition 1 (found 1 laptop order): {condition1}")
print(f"Condition 2 (update modified 1 doc): {condition2}")
print(f"Condition 3 (order has 3 items): {condition3}")
@@ -205,7 +213,7 @@ def test_aggregation():
# Clear any existing data
sales_collection.delete_many({})
print("Cleared existing data")
# Insert sample sales data
insert_result = sales_collection.insert_many(
[
@@ -219,13 +227,13 @@ def test_aggregation():
# Calculate total sales by product - use a simpler aggregation pipeline
pipeline = [
{"$match": {}}, # Match all documents
{"$group": {"_id": "$product", "total": {"$sum": "$amount"}}}
{"$group": {"_id": "$product", "total": {"$sum": "$amount"}}},
]
# Execute the aggregation
sales_summary = list(sales_collection.aggregate(pipeline))
print(f"Aggregation returned {len(sales_summary)} results")
# Print the results for debugging
for item in sales_summary:
print(f"Product: {item.get('_id')}, Total: {item.get('total')}")
@@ -233,7 +241,8 @@ def test_aggregation():
# Check each condition separately
condition1 = len(sales_summary) == 3
condition2 = any(
item.get("_id") == "Laptop" and abs(item.get("total", 0) - 999.99) < 0.01
item.get("_id") == "Laptop"
and abs(item.get("total", 0) - 999.99) < 0.01
for item in sales_summary
)
condition3 = any(
@@ -241,10 +250,11 @@ def test_aggregation():
for item in sales_summary
)
condition4 = any(
item.get("_id") == "Keyboard" and abs(item.get("total", 0) - 59.99) < 0.01
item.get("_id") == "Keyboard"
and abs(item.get("total", 0) - 59.99) < 0.01
for item in sales_summary
)
print(f"Condition 1 (3 summary items): {condition1}")
print(f"Condition 2 (laptop total correct): {condition2}")
print(f"Condition 3 (mouse total correct): {condition3}")
@@ -325,35 +335,37 @@ def test_complex_queries():
# Update with multiple conditions - split into separate operations for better compatibility
# First set the discount
products_collection.update_many(
{"price": {"$lt": 100}, "in_stock": True},
{"$set": {"discount": 0.1}}
{"price": {"$lt": 100}, "in_stock": True}, {"$set": {"discount": 0.1}}
)
# Then update the price
update_result = products_collection.update_many(
{"price": {"$lt": 100}, "in_stock": True},
{"$inc": {"price": -10}}
{"price": {"$lt": 100}, "in_stock": True}, {"$inc": {"price": -10}}
)
# Verify the update
updated_product = products_collection.find_one({"name": "Cheap Mouse"})
# Print debug information
print(f"Found expensive electronics: {len(expensive_electronics)}")
if expensive_electronics:
print(f"First expensive product: {expensive_electronics[0].get('name')}")
print(
f"First expensive product: {expensive_electronics[0].get('name')}"
)
print(f"Modified count: {update_result.modified_count}")
if updated_product:
print(f"Updated product price: {updated_product.get('price')}")
print(f"Updated product discount: {updated_product.get('discount')}")
# More flexible verification with approximate float comparison
success = (
len(expensive_electronics) >= 1
and expensive_electronics[0].get("name") in ["Expensive Laptop", "Laptop"]
and expensive_electronics[0].get("name")
in ["Expensive Laptop", "Laptop"]
and update_result.modified_count >= 1
and updated_product is not None
and updated_product.get("discount", 0) > 0 # Just check that discount exists and is positive
and updated_product.get("discount", 0)
> 0 # Just check that discount exists and is positive
)
print(f"Test {'passed' if success else 'failed'}")
return success
@@ -368,48 +380,51 @@ def run_concurrent_operation_test(num_threads=100):
import time
import uuid
from concurrent.futures import ThreadPoolExecutor
print(f"\nStarting concurrent operation test with {num_threads} threads...")
# Results tracking
results = {"passed": 0, "failed": 0, "errors": []}
results_lock = threading.Lock()
def worker(thread_id):
# Create a unique collection name for this thread
collection_name = f"concurrent_test_{thread_id}"
try:
# Generate unique data for this thread
unique_id = str(uuid.uuid4())
with mongo_handler.collection(collection_name) as collection:
# Insert a document
collection.insert_one({
"thread_id": thread_id,
"uuid": unique_id,
"timestamp": time.time()
})
collection.insert_one(
{
"thread_id": thread_id,
"uuid": unique_id,
"timestamp": time.time(),
}
)
# Find the document
doc = collection.find_one({"thread_id": thread_id})
# Update the document
collection.update_one(
{"thread_id": thread_id},
{"$set": {"updated": True}}
{"thread_id": thread_id}, {"$set": {"updated": True}}
)
# Verify update
updated_doc = collection.find_one({"thread_id": thread_id})
# Clean up
collection.delete_many({"thread_id": thread_id})
success = (doc is not None and
updated_doc is not None and
updated_doc.get("updated") is True)
success = (
doc is not None
and updated_doc is not None
and updated_doc.get("updated") is True
)
# Update results with thread safety
with results_lock:
if success:
@@ -421,15 +436,15 @@ def run_concurrent_operation_test(num_threads=100):
with results_lock:
results["failed"] += 1
results["errors"].append(f"Thread {thread_id} exception: {str(e)}")
# Create and start threads using a thread pool
start_time = time.time()
with ThreadPoolExecutor(max_workers=num_threads) as executor:
futures = [executor.submit(worker, i) for i in range(num_threads)]
# Calculate execution time
execution_time = time.time() - start_time
# Print results
print(f"\nConcurrent Operation Test Results:")
print(f"Total threads: {num_threads}")
@@ -437,14 +452,16 @@ def run_concurrent_operation_test(num_threads=100):
print(f"Failed: {results['failed']}")
print(f"Execution time: {execution_time:.2f} seconds")
print(f"Operations per second: {num_threads / execution_time:.2f}")
if results["failed"] > 0:
print("\nErrors:")
for error in results["errors"][:10]: # Show only first 10 errors to avoid flooding output
for error in results["errors"][
:10
]: # Show only first 10 errors to avoid flooding output
print(f"- {error}")
if len(results["errors"]) > 10:
print(f"- ... and {len(results['errors']) - 10} more errors")
return results["failed"] == 0
@@ -493,10 +510,10 @@ def run_all_tests():
if __name__ == "__main__":
mongo_handler = MongoDBHandler()
# Run standard tests first
passed, failed = run_all_tests()
# If all tests pass, run the concurrent operation test
if failed == 0:
run_concurrent_operation_test(10000)