Download tests/test_multiprocess_state.py from lhc-lab/AI-Colab: direct link, hf CLI and curl.
- Browser
- Download file 3.08 kB
-
https://huggingface.co/datasets/lhc-lab/AI-Colab/resolve/main/tests/test_multiprocess_state.py
- Command line
-
hf download hf://datasets/lhc-lab/AI-Colab/tests/test_multiprocess_state.py
-
curl -L -o test_multiprocess_state.py https://huggingface.co/datasets/lhc-lab/AI-Colab/resolve/main/tests/test_multiprocess_state.py
3.08 kB
| """ | |
| tests/test_multiprocess_state.py | |
| Тест для проверки работы SharedState в многопроцессной среде. | |
| """ | |
| import multiprocessing | |
| import time | |
| import os | |
| import sys | |
| import json | |
| from pathlib import Path | |
| # Добавляем корень проекта в sys.path | |
| sys.path.append(str(Path(__file__).parent.parent.parent)) # Поднимаемся выше, так как корень - D:\gemini | |
| from core.shared_state import SharedState | |
| def worker_test(worker_id, state_file): | |
| """Тестовый воркер, который записывает данные в состояние.""" | |
| print(f"Worker {worker_id} started (PID: {os.getpid()})") | |
| # Каждый воркер инициализирует свой экземпляр SharedState, указывая на тот же файл | |
| shared_state = SharedState(state_file) | |
| try: | |
| # Имитируем работу | |
| time.sleep(worker_id * 0.1) | |
| # Запись | |
| key = f"test_workers.worker_{worker_id}" | |
| data = { | |
| "pid": os.getpid(), | |
| "time": time.time(), | |
| "status": "OK" | |
| } | |
| success = shared_state.set(key, data) | |
| if success: | |
| print(f"Worker {worker_id} successfully wrote data") | |
| else: | |
| print(f"Worker {worker_id} FAILED to write data") | |
| except Exception as e: | |
| print(f"Worker {worker_id} error: {e}") | |
| def run_multiprocess_test(): | |
| """Запуск теста в нескольких процессах.""" | |
| state_file = "shared_state_test.json" | |
| # Удаляем старый файл если есть | |
| if Path(state_file).exists(): | |
| Path(state_file).unlink() | |
| if Path(state_file + ".lock").exists(): | |
| Path(state_file + ".lock").unlink() | |
| num_workers = 5 | |
| processes = [] | |
| print(f"Starting {num_workers} test workers...") | |
| for i in range(num_workers): | |
| p = multiprocessing.Process( | |
| target=worker_test, | |
| args=(i, state_file) | |
| ) | |
| processes.append(p) | |
| p.start() | |
| # Ждем завершения | |
| for p in processes: | |
| p.join() | |
| print("All workers completed") | |
| # Финальная проверка состояния | |
| shared_state = SharedState(state_file) | |
| final_state = shared_state.get_all() | |
| print("\nFinal shared state (test_workers):") | |
| workers_data = final_state.get("test_workers", {}) | |
| print(json.dumps(workers_data, indent=2)) | |
| if len(workers_data) == num_workers: | |
| print("\nSUCCESS: All workers successfully synchronized state!") | |
| else: | |
| print(f"\nFAILURE: Expected {num_workers} entries, found {len(workers_data)}") | |
| # Очистка | |
| try: | |
| if Path(state_file).exists(): | |
| Path(state_file).unlink() | |
| if Path(state_file + ".lock").exists(): | |
| Path(state_file + ".lock").unlink() | |
| except: | |
| pass | |
| if __name__ == '__main__': | |
| run_multiprocess_test() | |