Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[FormRecognizer] Created sample for mocking #18890

Merged
merged 7 commits into from
Feb 22, 2021
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
# Mock a client for testing using the Moq library

This sample illustrates how to use [Moq][moq] to create a unit test that mocks the response from a `FormRecognizerClient` method. For more examples of mocking, see [Moq samples][moq_samples].

## Define a method that uses FormRecognizerClient
To show the usage of mocks, define a method that will be tested with mocked objects. For this case, we are going to create a method that will verify whether the total price of a groceries list is expensive or not. We're not considering it expensive if the confidence of the recognized field is too low.
kinelski marked this conversation as resolved.
Show resolved Hide resolved
kinelski marked this conversation as resolved.
Show resolved Hide resolved

```C# Snippet:FormRecognizerMethodToTest
private static async Task<bool> IsExpensiveAsync(string modelId, Uri documentUri, FormRecognizerClient client)
{
RecognizeCustomFormsOperation operation = await client.StartRecognizeCustomFormsFromUriAsync(modelId, documentUri);

Response<RecognizedFormCollection> response = await operation.WaitForCompletionAsync();
RecognizedForm form = response.Value[0];

if (form.FormType == "groceries")
kinelski marked this conversation as resolved.
Show resolved Hide resolved
{
FormField totalPriceField = form.Fields["totalPrice"];
return totalPriceField.Confidence > 0.5f && totalPriceField.Value.AsFloat() > 100f;
kinelski marked this conversation as resolved.
Show resolved Hide resolved
}
else
{
return false;
}
}
```

## Create and setup mocks
To start, create a mock for the `FormRecognizerClient`. Most methods in this service make use of [Long-Running Operations][lros], so you'll likely need to create a mock operation as well.

```C# Snippet:FormRecognizerCreateMocks
var fakeModelId = Guid.NewGuid().ToString();
var fakeOperationId = $"{fakeModelId}/analyzeResults/{Guid.NewGuid()}";
var mockClient = new Mock<FormRecognizerClient>();
var mockOperation = new Mock<RecognizeCustomFormsOperation>(fakeOperationId, mockClient.Object);
maririos marked this conversation as resolved.
Show resolved Hide resolved
```

Then, set up the client methods that will be executed. In this case, we will call the `StartRecognizeCustomFormsFromUriAsync` method.

```C# Snippet:FormRecognizerSetUpClientMock
var fakeDocumentUri = new Uri("https://fake.document.uri");

mockClient.Setup(c => c.StartRecognizeCustomFormsFromUriAsync(fakeModelId, fakeDocumentUri,
It.IsAny<RecognizeCustomFormsOptions>(), It.IsAny<CancellationToken>()))
.Returns(Task.FromResult(mockOperation.Object));
```

If you're mocking an operation object, you will also need to set up the methods that will be called from it. In this sample, we only need to set `WaitForCompletionAsync`.

```C# Snippet:FormRecognizerSetUpOperationMock
var labelDataBox = FormRecognizerModelFactory.FieldBoundingBox(new List<PointF>()
{ new PointF(1f, 1f), new PointF(2f, 1f), new PointF(2f, 2f), new PointF(1f, 2f) });
var labelData = FormRecognizerModelFactory.FieldData(labelDataBox, 1, "Total price:", new List<FormElement>());

var valueDataBox = FormRecognizerModelFactory.FieldBoundingBox(new List<PointF>()
{ new PointF(4f, 1f), new PointF(5f, 1f), new PointF(5f, 2f), new PointF(4f, 2f) });
var valueData = FormRecognizerModelFactory.FieldData(valueDataBox, 1, "$150.00", new List<FormElement>());

var fieldValue = FormRecognizerModelFactory.FieldValueWithFloatValueType(150f);

var formField = FormRecognizerModelFactory.FormField("totalPrice", labelData, valueData, fieldValue, 0.85f);
var formPage = FormRecognizerModelFactory.FormPage(1, 8.5f, 11f, 0f, LengthUnit.Inch, new List<FormLine>(), new List<FormTable>());

var pageRange = FormRecognizerModelFactory.FormPageRange(1, 1);
var recognizedForm = FormRecognizerModelFactory.RecognizedForm("groceries", pageRange,
new Dictionary<string, FormField>() { { "totalPrice", formField } },
new List<FormPage>() { formPage });
var recognizedFormCollection = FormRecognizerModelFactory.RecognizedFormCollection(new List<RecognizedForm>() { recognizedForm });

Response<RecognizedFormCollection> operationResponse = Response.FromValue(recognizedFormCollection, Mock.Of<Response>());

mockOperation.Setup(op => op.WaitForCompletionAsync(It.IsAny<CancellationToken>()))
.Returns(new ValueTask<Response<RecognizedFormCollection>>(operationResponse));
```

To keep the set up simple, we suggest that you only add the properties required by your tests when building your models. In this case, we only needed the `FormType`, the field's `Confidence`, and the field's `Value`, while the other properties could be set to `null`, `default`, or empty.

## Use mocks
Now, to validate if the groceries are expensive without making a network call, use the `FormRecognizerClient` mock.

```C# Snippet:FormRecognizerUseMocks
bool result = await IsExpensiveAsync(fakeModelId, fakeDocumentUri, mockClient.Object);
Assert.IsTrue(result);
```

[moq]: https://github.com/Moq/moq4/
[moq_samples]: https://github.com/Azure/azure-sdk-for-net/tree/master/sdk/formrecognizer/Azure.AI.FormRecognizer/samples
kinelski marked this conversation as resolved.
Show resolved Hide resolved
[lros]: https://github.com/Azure/azure-sdk-for-net/tree/master/sdk/formrecognizer/Azure.AI.FormRecognizer#long-running-operations
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Threading;
using System.Threading.Tasks;
using Azure.AI.FormRecognizer.Models;
using Azure.AI.FormRecognizer.Training;
using Moq;
using NUnit.Framework;

namespace Azure.AI.FormRecognizer.Tests
{
public partial class FormRecognizerSamples
{
[Test]
public async Task RecognizeCustomFormsAsync()
{
#region Snippet:FormRecognizerCreateMocks
var fakeModelId = Guid.NewGuid().ToString();
var fakeOperationId = $"{fakeModelId}/analyzeResults/{Guid.NewGuid()}";
var mockClient = new Mock<FormRecognizerClient>();
var mockOperation = new Mock<RecognizeCustomFormsOperation>(fakeOperationId, mockClient.Object);
#endregion

#region Snippet:FormRecognizerSetUpClientMock
var fakeDocumentUri = new Uri("https://fake.document.uri");

mockClient.Setup(c => c.StartRecognizeCustomFormsFromUriAsync(fakeModelId, fakeDocumentUri,
It.IsAny<RecognizeCustomFormsOptions>(), It.IsAny<CancellationToken>()))
.Returns(Task.FromResult(mockOperation.Object));
#endregion

#region Snippet:FormRecognizerSetUpOperationMock
var labelDataBox = FormRecognizerModelFactory.FieldBoundingBox(new List<PointF>()
{ new PointF(1f, 1f), new PointF(2f, 1f), new PointF(2f, 2f), new PointF(1f, 2f) });
var labelData = FormRecognizerModelFactory.FieldData(labelDataBox, 1, "Total price:", new List<FormElement>());

var valueDataBox = FormRecognizerModelFactory.FieldBoundingBox(new List<PointF>()
{ new PointF(4f, 1f), new PointF(5f, 1f), new PointF(5f, 2f), new PointF(4f, 2f) });
var valueData = FormRecognizerModelFactory.FieldData(valueDataBox, 1, "$150.00", new List<FormElement>());

var fieldValue = FormRecognizerModelFactory.FieldValueWithFloatValueType(150f);

var formField = FormRecognizerModelFactory.FormField("totalPrice", labelData, valueData, fieldValue, 0.85f);
var formPage = FormRecognizerModelFactory.FormPage(1, 8.5f, 11f, 0f, LengthUnit.Inch, new List<FormLine>(), new List<FormTable>());

var pageRange = FormRecognizerModelFactory.FormPageRange(1, 1);
var recognizedForm = FormRecognizerModelFactory.RecognizedForm("groceries", pageRange,
kinelski marked this conversation as resolved.
Show resolved Hide resolved
new Dictionary<string, FormField>() { { "totalPrice", formField } },
new List<FormPage>() { formPage });
var recognizedFormCollection = FormRecognizerModelFactory.RecognizedFormCollection(new List<RecognizedForm>() { recognizedForm });

Response<RecognizedFormCollection> operationResponse = Response.FromValue(recognizedFormCollection, Mock.Of<Response>());

mockOperation.Setup(op => op.WaitForCompletionAsync(It.IsAny<CancellationToken>()))
.Returns(new ValueTask<Response<RecognizedFormCollection>>(operationResponse));
#endregion

#region Snippet:FormRecognizerUseMocks
bool result = await IsExpensiveAsync(fakeModelId, fakeDocumentUri, mockClient.Object);
Assert.IsTrue(result);
#endregion
}

#region Snippet:FormRecognizerMethodToTest
private static async Task<bool> IsExpensiveAsync(string modelId, Uri documentUri, FormRecognizerClient client)
{
RecognizeCustomFormsOperation operation = await client.StartRecognizeCustomFormsFromUriAsync(modelId, documentUri);

Response<RecognizedFormCollection> response = await operation.WaitForCompletionAsync();
RecognizedForm form = response.Value[0];

if (form.FormType == "groceries")
{
FormField totalPriceField = form.Fields["totalPrice"];
kinelski marked this conversation as resolved.
Show resolved Hide resolved
return totalPriceField.Confidence > 0.5f && totalPriceField.Value.AsFloat() > 100f;
kinelski marked this conversation as resolved.
Show resolved Hide resolved
}
else
{
return false;
}
}
#endregion

[Test]
public async Task GetCustomModelsAsync()
kinelski marked this conversation as resolved.
Show resolved Hide resolved
{
var fakeReadyModelId = Guid.NewGuid().ToString();
var fakeInvalidModelId = Guid.NewGuid().ToString();
var mockClient = new Mock<FormTrainingClient>();

var page = Page<CustomFormModelInfo>.FromValues(new[]
{
FormRecognizerModelFactory.CustomFormModelInfo(fakeReadyModelId,
DateTimeOffset.Parse("2020-01-01T00:00:00Z"), DateTimeOffset.Parse("2020-01-01T00:00:30Z"),
CustomFormModelStatus.Ready),
FormRecognizerModelFactory.CustomFormModelInfo(fakeInvalidModelId,
DateTimeOffset.Parse("2020-03-15T00:00:00Z"), DateTimeOffset.Parse("2020-03-15T00:00:10Z"),
CustomFormModelStatus.Invalid)
}, null, Mock.Of<Response>());

mockClient.Setup(c => c.GetCustomModelsAsync(It.IsAny<CancellationToken>()))
.Returns(AsyncPageable<CustomFormModelInfo>.FromPages(new[] { page }));

FormTrainingClient client = mockClient.Object;

// Get the IDs of all invalid models.

var invalidModelIds = new List<string>();

await foreach (CustomFormModelInfo modelInfo in client.GetCustomModelsAsync())
{
if (modelInfo.Status == CustomFormModelStatus.Invalid)
{
invalidModelIds.Add(modelInfo.ModelId);
}
}

Assert.AreEqual(1, invalidModelIds.Count);
Assert.AreEqual(fakeInvalidModelId, invalidModelIds[0]);
}
}
}