grpc-dotnet icon indicating copy to clipboard operation
grpc-dotnet copied to clipboard

ServerCallContext should be mockable for testing

Open buehler opened this issue 7 years ago • 9 comments

Hey there

When working with this (awesome) package, I found an issue when I want to test my services. Since I'm not really able to start the grpc api within kestrel (with the aspnetcore.mvc.testing package) and have a real server started up, I tried to start with unit testing.

So for unit testing, I'm taking the services, and instantiate them with mocked elements "injected". Now I would like to call my service and see if the function returns the correct (may be parsed or otherwise modified) output from the business logic.

But since I'm accessing the http context (for authentication and header information) I'm not able to do so. Even with: https://github.com/grpc/grpc/blob/master/src/csharp/Grpc.Core.Testing/TestServerCallContext.cs#L34

Are there any plans for a similar create method so that this context could be mocked?

And as a follow up: how do you integration test your applications? I tried to use the the guide from https://docs.microsoft.com/en-us/aspnet/core/test/integration-tests?view=aspnetcore-3.0 to actually fire up a test kestrel. But when I do, I've got grpc client that can actually connect to this instance.

Thanks for any advices

Chris

buehler avatar Jun 18 '19 11:06 buehler

And as a follow up: how do you integration test your applications? I tried to use the the guide from docs.microsoft.com/en-us/aspnet/core/test/integration-tests?view=aspnetcore-3.0 to actually fire up a test kestrel. But when I do, I've got grpc client that can actually connect to this instance.

Take the HttpClient that you get from this code var client = _factory.CreateClient(); pass it to Grpc.Net.Client's GrpcClient.Create<YourGrpcClient>(client).

JamesNK avatar Jun 19 '19 01:06 JamesNK

But since I'm accessing the http context (for authentication and header information) I'm not able to do so.

Are you doing that with serverCallContext.GetHttpContext()? You could replace the method with IHttpContextAccessor and inject the context into the service constructor.

Alternatively headers are available on ServerCallContext - https://grpc.github.io/grpc/csharp/api/Grpc.Core.ServerCallContext.html#Grpc_Core_ServerCallContext_RequestHeaders

JamesNK avatar Jun 19 '19 01:06 JamesNK

And as a follow up: how do you integration test your applications? I tried to use the the guide from docs.microsoft.com/en-us/aspnet/core/test/integration-tests?view=aspnetcore-3.0 to actually fire up a test kestrel. But when I do, I've got grpc client that can actually connect to this instance.

Take the HttpClient that you get from this code var client = _factory.CreateClient(); pass it to Grpc.Net.Client's GrpcClient.Create<YourGrpcClient>(client).

Thank you! I'm going to try that. So that should resolve the issue with integration tests.

buehler avatar Jun 19 '19 06:06 buehler

But since I'm accessing the http context (for authentication and header information) I'm not able to do so.

Are you doing that with serverCallContext.GetHttpContext()? You could replace the method with IHttpContextAccessor and inject the context into the service constructor.

Alternatively headers are available on ServerCallContext - https://grpc.github.io/grpc/csharp/api/Grpc.Core.ServerCallContext.html#Grpc_Core_ServerCallContext_RequestHeaders

Yes, by now, I'm using the GetHttpContext() extension method. The headers are no problem, Those could be read from the normal server call context. But the actual authenticated user is the problem.

I'm going to try that and give you feedback. Thanks for the hint.

buehler avatar Jun 19 '19 06:06 buehler

I think this has been answered

JamesNK avatar Jun 21 '19 04:06 JamesNK

Just finished testing. It works perfectly.. Thank you very much!

buehler avatar Jun 21 '19 06:06 buehler

And as a follow up: how do you integration test your applications? I tried to use the the guide from docs.microsoft.com/en-us/aspnet/core/test/integration-tests?view=aspnetcore-3.0 to actually fire up a test kestrel. But when I do, I've got grpc client that can actually connect to this instance.

Take the HttpClient that you get from this code var client = _factory.CreateClient(); pass it to Grpc.Net.Client's GrpcClient.Create<YourGrpcClient>(client).

GrpcClient does not exist any more. How do you do this now?

npuc85 avatar Sep 25 '19 19:09 npuc85

You can pass HttpClient like so:

var channel = GrpcChannel.ForAddress("address",
    new GrpcChannelOptions { HttpClient = httpClient });

JamesNK avatar Sep 25 '19 20:09 JamesNK

TestServerCallContext and TestCalls from Grpc.Core.Testing still work but they are part of Grpc.Core...

Could we maybe port them?

Here's some sample code I use to integrate between a service and a client by providing a mock CallInvoker.

sealed class SwarmMockCallInvoker : CallInvoker
{
	readonly Func<SwarmControllerService> controllerService;
	readonly Func<SwarmNodeService> nodeService;
	readonly Func<SwarmSharedService> sharedService;

	readonly Func<bool> throwUnavailableException;

	public SwarmMockCallInvoker(Func<SwarmControllerService> controllerService, Func<SwarmSharedService> sharedService, Func<bool> throwUnavailableException)
	{
		this.controllerService = controllerService ?? throw new ArgumentNullException(nameof(controllerService));
		this.sharedService = sharedService ?? throw new ArgumentNullException(nameof(sharedService));
		this.throwUnavailableException = throwUnavailableException ?? throw new ArgumentNullException(nameof(throwUnavailableException));
	}

	public SwarmMockCallInvoker(Func<SwarmNodeService> nodeService, Func<SwarmSharedService> sharedService, Func<bool> throwUnavailableException)
	{
		this.nodeService = nodeService ?? throw new ArgumentNullException(nameof(nodeService));
		this.sharedService = sharedService ?? throw new ArgumentNullException(nameof(sharedService));
		this.throwUnavailableException = throwUnavailableException ?? throw new ArgumentNullException(nameof(throwUnavailableException));
	}

	public override AsyncClientStreamingCall<TRequest, TResponse> AsyncClientStreamingCall<TRequest, TResponse>(Method<TRequest, TResponse> method, string host, CallOptions options)
		=> throw new NotSupportedException();

	public override AsyncDuplexStreamingCall<TRequest, TResponse> AsyncDuplexStreamingCall<TRequest, TResponse>(Method<TRequest, TResponse> method, string host, CallOptions options)
		=> throw new NotSupportedException();

	public override AsyncServerStreamingCall<TResponse> AsyncServerStreamingCall<TRequest, TResponse>(Method<TRequest, TResponse> method, string host, CallOptions options, TRequest request)
		=> throw new NotSupportedException();

	public override AsyncUnaryCall<TResponse> AsyncUnaryCall<TRequest, TResponse>(Method<TRequest, TResponse> method, string host, CallOptions options, TRequest request)
	{
		var serviceName = method.ServiceName;

		var headersResult = new TaskCompletionSource<Metadata>();

		var callContext = TestServerCallContext.Create(
			serviceName,
			"doesn't matter",
			options.Deadline ?? default,
			options.Headers,
			options.CancellationToken,
			"also doesn't matter",
			null,
			null,
			headers =>
			{
				headersResult.SetResult(headers);
				return Task.CompletedTask;
			},
			null,
			null);

		object invokeTarget;
		if (serviceName == GrpcSwarmControllerService.Descriptor.FullName)
			invokeTarget = controllerService?.Invoke();
		else if (serviceName == GrpcSwarmNodeService.Descriptor.FullName)
			invokeTarget = nodeService?.Invoke();
		else if (serviceName == GrpcSwarmSharedService.Descriptor.FullName)
			invokeTarget = sharedService?.Invoke();
		else
		{
			Assert.Fail($"Unsupported gRPC method call: {serviceName}");
			invokeTarget = null;
		}

		if (invokeTarget == null)
			Assert.Fail($"Call to {serviceName} not targeting the correct service!");

		if (throwUnavailableException())
			throw new RpcException(new Status(StatusCode.Unavailable, "Testing machine said so"));

		var responseTask = (Task<TResponse>)invokeTarget.GetType().GetMethod(method.Name).Invoke(invokeTarget, [request, callContext]);

		var call = TestCalls.AsyncUnaryCall(responseTask, headersResult.Task, () => callContext.Status, () => callContext.ResponseTrailers, () => { });

		return call;
	}

	public override TResponse BlockingUnaryCall<TRequest, TResponse>(Method<TRequest, TResponse> method, string host, CallOptions options, TRequest request)
		=> throw new NotSupportedException();
}

Cyberboss avatar Apr 16 '25 18:04 Cyberboss