Я не вижу успеха в пользовательском интерфейсе Locust, в консоли нет ошибок, а журналы сервера показывают, что конечная точка отправляет правильный ответ.
Это код, который я использую:
import time
import grpc
from locust import User, task, between, events
import sys
import abcapi_pb2
import abcapi_pb2_grpc
class GrpcUser(User):
"""
Custom gRPC User class for Locust
"""
abstract = True # This User class won't be started by Locust directly
def __init__(self, environment):
super().__init__(environment)
self.client = self.create_client()
def create_client(self):
raise NotImplementedError("You must implement create_client in your gRPC User class")
class GrpcClient:
def __init__(self, host):
self.host = host
self.channel = grpc.insecure_channel(self.host)
self.stub = abcapi_pb2_grpc.abcapiIfStub(self.channel)
self.authenticate() # Authenticate immediately on client creation
def authenticate(self):
"""
Authenticate with the server using the Hello procedure
Called only once when the client is initialized
"""
try:
request = abcapi_pb2.HelloRequest(
name="Hello"
)
print("Authenticating with server...")
response = self.stub.Hello(request)
print("Authentication successful")
return True
except grpc.RpcError as e:
print(f"Authentication failed: RPC Error: {e.details()}")
return False
except Exception as e:
print(f"Authentication failed: {str(e)}")
return False
def load_data(self, request_data):
"""
Call the LoadData streaming endpoint and consume all responses
"""
try:
# Create the request object with the correct field types
request = abcapi_pb2.C_Request(
timestamp=int(request_data["timestamp"]),
series=int(request_data["series"]),
limit=int(request_data["limit"])
)
start_time = time.time()
response_count = 0
# Stream responses
for response in self.stub.LoadData(request):
response_count += 1
elapsed = time.time() - start_time
return True, elapsed, response_count, "Success"
except grpc.RpcError as e:
error_message = f"RPC Error: {e.details()}"
print(error_message)
return False, 0, 0, error_message
except Exception as e:
error_message = f"Error: {str(e)}"
print(error_message)
return False, 0, 0, error_message
class C_RequestUser(GrpcUser):
host = "localhost:50051"
#wait_time = between(1, 3) # Wait between 1-3 seconds between tasks
def create_client(self):
return GrpcClient(self.host)
@task
def load_data(self):
"""Task to call LoadData"""
request_data = {
"timestamp": 123,
"series": 0,
"limit": 2
}
name = "LoadData"
start_time = time.time()
success, elapsed, response_count, message = self.client.load_data(request_data)
# Report to Locust
total_time = int((time.time() - start_time) * 1000)
if success:
events.request.fire(
request_type="grpc",
name=name,
response_time=total_time,
response_length=response_count,
exception=None,
context={
"stream_count": response_count,
"stream_time": elapsed
}
)
print(f"Received {response_count} stream responses in {elapsed:.2f}s")
else:
events.request.fire(
request_type="grpc",
name=name,
response_time=total_time,
response_length=0,
exception=Exception(message),
context={}
)
Я попробовал сценарий ошибки и вижу журналы ошибок в пользовательском интерфейсе Locust, но почему-то Locust не может обработать успех. Ошибки нет, саранча просто ждет бесконечно.
Я попробовал добавить ожидание. Когда настроенное время ожидания заканчивается, я получаю ошибку тайм-аута.
То же самое работает правильно в ROBOT Framework
Я зашел в тупик и не могу найти решение.
Я хочу создать несколько пользователей, которые будут обращаться к конечной точке GRPC «load_data» через Locust и видеть результаты на Locust Пользовательский интерфейс.
Locust не регистрирует успех в случае, если конечная точка GRPC возвращает поток Ниже приведена моя настройка: [code]locust==2.33 python grpcio==1.70.0 grpcio-tools==1.62.1 protobuf==4.25.3 [/code] Я не вижу успеха в пользовательском интерфейсе Locust, в консоли нет ошибок, а журналы сервера показывают, что конечная точка отправляет правильный ответ. Это код, который я использую: [code]import time import grpc from locust import User, task, between, events import sys
import abcapi_pb2 import abcapi_pb2_grpc
class GrpcUser(User): """ Custom gRPC User class for Locust """ abstract = True # This User class won't be started by Locust directly
def authenticate(self): """ Authenticate with the server using the Hello procedure Called only once when the client is initialized """ try: request = abcapi_pb2.HelloRequest( name="Hello" )
print("Authenticating with server...") response = self.stub.Hello(request) print("Authentication successful") return True except grpc.RpcError as e: print(f"Authentication failed: RPC Error: {e.details()}") return False except Exception as e: print(f"Authentication failed: {str(e)}") return False
def load_data(self, request_data): """ Call the LoadData streaming endpoint and consume all responses """ try: # Create the request object with the correct field types request = abcapi_pb2.C_Request( timestamp=int(request_data["timestamp"]), series=int(request_data["series"]), limit=int(request_data["limit"]) )
start_time = time.time() response_count = 0 # Stream responses for response in self.stub.LoadData(request): response_count += 1
if success: events.request.fire( request_type="grpc", name=name, response_time=total_time, response_length=response_count, exception=None, context={ "stream_count": response_count, "stream_time": elapsed } ) print(f"Received {response_count} stream responses in {elapsed:.2f}s") else: events.request.fire( request_type="grpc", name=name, response_time=total_time, response_length=0, exception=Exception(message), context={} ) [/code] [list] [*]Я попробовал сценарий ошибки и вижу журналы ошибок в пользовательском интерфейсе Locust, но почему-то Locust не может обработать успех. Ошибки нет, саранча просто ждет бесконечно.
[*]Я попробовал добавить ожидание. Когда настроенное время ожидания заканчивается, я получаю ошибку тайм-аута.
[*]То же самое работает правильно в ROBOT Framework
[/list] Я зашел в тупик и не могу найти решение. Я хочу создать несколько пользователей, которые будут обращаться к конечной точке GRPC «load_data» через Locust и видеть результаты на Locust Пользовательский интерфейс.