Unit and Integration Test for Azure Function with ServiceBusTrigger - unit-testing

I have an Azure Function which is triggered by an Azure Service Bus Queue.
The function is below.
How this Run method can be unit tested?
And how an integration test can be done by starting with AddContact trigger, checking the logic in the method and the data being sent to a blob using the output binding?
public static class AddContactFunction
{
[FunctionName("AddContactFunction")]
public static void Run([ServiceBusTrigger("AddContact", Connection = "AddContactFunctionConnectionString")]string myQueueItem, ILogger log)
{
log.LogInformation($"C# ServiceBus queue trigger function processed message: {myQueueItem}");
}
}

I had the exact same doubts.
Adding Unit Tests is not too complicated, at the end of the day, its a function, so all we got to do is to call the Azure Function with the correct string, for parameter string myQueueItem.
Adding Integration tests needs some additional ground work. In the Github project, the author uses the TestFunctionHost class from Azure/azure-functions-host project.
I tried following this strategy, but the amount of code needed to setup all these is uncomfortably high for my liking. Not a lot of it is well documented, and some of the stuff needs developers to use Azure App Services myGet feed.
I wanted a simpler approach, and thankfully I found one.
Azure Functions is built on top of the Azure WebJobs SDK package, and leverages its JobHost class to run. So in our integration tests, all we need to do, is to setup this Host, and tell it where to look for the Azure Functions to load and run.
IHost host = new HostBuilder()
.ConfigureWebJobs()
.ConfigureDefaultTestHost<CLASS_CONTAINING_THE_AZURE_FUNCTIONS>(webjobsBuilder => {
webjobsBuilder.AddAzureStorage();
webjobsBuilder.AddServiceBus();
})
.ConfigureServices(services => {
services.AddSingleton<INameResolver>(resolver);
})
.Build();
using (host) {
await host.StartAsync();
// ..
}
...
Once this is done, we can send messages to ServiceBus and our Azure Functions will get triggered. Once can even set breakpoints in the Functions getting tested and debug issues!
I have blogged about the whole process here and I have also created a github repository at this link, to showcase test driven development with Azure Functions.

How this Run method can be unit tested?
The method is a static public method. You can unit test it by invoking the static method AddContactFunction.Run(/* parameters /*); You will not need a Service Bus namespace or a message for that matter as your function expects to receive a string from the SDK. Which you can provide and verify the logic works as expected.
And how an integration test can be done by starting with AddContact trigger, checking the logic in the method and the data being sent to a blob using the output binding?
This would be a much more sophisticated scenario. This would require to run Functions runtime and generate a real Service Bus message to trigger the functions as well as validate that the blob was written. There's no integration/end-to-end testing framework that is shipped with Functions and you'd need to come up with something custom. Azure Functions Core Tools could be helpful to achieve that.

Related

How to build request handler class in lambda function for a Springboot CRUD Application?

I am trying to invoke a lambda function by the new feature - function URL"S https://docs.aws.amazon.com/lambda/latest/dg/lambda-urls.html using which I don't require any trigger events.
I am able to get the output for a simple java application using the above approach written in documentation by using Java as runtimeEnvironment and passing Jar file from my local machine.
Now, I want to test lambda functionality by same concept but for Springboot-Application which has restful endpoints for GET,POST,PUT,DELETE for different crud operations connecting with MySql db. The problem I am facing is how to tell handler class that to route to these endpoints and trigger lambda functions.
Any help/suggestions appreciated here. Thanks in Advance !
It probably won't work with this URL's feature but it allows handling Lambda events similar to standard Spring web requests.
You can check this one: https://github.com/MelonProjectCom/lambda-http-router
Example usage:
#PathPostMapping("/example/test")
public String example(#Body String body) {
return "Hello World! - body: " + body;
}

Browser Automation Testing with Selenium Web Driver in AWS Code Build

I want to Automate and integrate the the Selenium web driver tests that we developed for a website in AWS code build environment. We want to run these tests automated, in the AWS Code-Build and then Release (AWS Code-Deploy) if all good.
For example, We wrote all of our test cases using node. Let's assume that I have a basic test case like below
npm install selenium-webdriver In a file called google_test.js
const webdriver = require('selenium-webdriver'),
By = webdriver.By,
until = webdriver.until;
const driver = new webdriver.Builder()
.forBrowser('firefox')
.build();
driver.get('http://www.google.com');
driver.findElement(By.name('q')).sendKeys('webdriver');
driver.sleep(1000).then(function() {
driver.findElement(By.name('q')).sendKeys(webdriver.Key.TAB);
});
driver.findElement(By.name('btnK')).click();
driver.sleep(2000).then(function() {
driver.getTitle().then(function(title) {
if(title === 'webdriver - Google Search') {
console.log('Test passed');
} else {
console.log('Test failed');
}
driver.quit();
});
});
Then as you would expect We run this test in the command line,
node google_test
This works fine and great in a manual environment,
however, our challenge is to automate this and deploy automatically if tests were successful,
I wonder how we can archive this in a the AWS code-build setup. Even after doing all the research Im still confused on what is the best way to achieve this, Many suggests many different ways all looks very hacky and unreliable,
Problems/Questions
Since in an Automated AWS code build enr. We dont have browser access, so how can we actually see the output to see if the tests were successful?
What is the way/How we can detect the tests ran correctly to proceed to the next step of code-deploy? what signals can be generated and how?
If this is not possible, what is the recommended way of doing this?

Unable to unit test cloud_firestore live

I'm currently trying to write a unit test that verifies a certain number of documents exist.
This is what I have so far
test('Login with no account', () async {
Firestore _firestore = Firestore.instance;
final QuerySnapshot result = await _firestore
.collection(UserFirestoreField.Collection)
.where(UserFirestoreField.EmailAddress, isEqualTo: 'email#example.com')
.where(UserFirestoreField.Password, isEqualTo: 'wrongpassword')
.getDocuments();
final List<DocumentSnapshot> docs = result.documents;
print(docs);
});
The error I'm getting is
package:flutter/src/services/platform_channel.dart 314:7
MethodChannel.invokeMethod
MissingPluginException(No implementation found for method
Query#getDocuments on channel plugins.flutter.io/cloud_firestore)
I have the android emulator running with my app started.
Every guide I've seen talks about mocking a database, I want to actually check the real database.
Any way to do this in dart/flutter?
Thanks!
In Flutter, unit and widget tests run on your host machine which does not have the native part of your firebase plugin. This is why you are getting this error.
You really should mock the database in tests but if you really want to test your app as close to how it is run by a user you would run an integration test on an emulator.
You can also use a dart based Firebase plugin or use the Firebase REST API.
You can find more about this here: https://flutter.dev/docs/testing
You could JsonDecode into a local map and test the map.

How to have a run time config file for aurelia app built with webpacks 4

I have a application built with aurelia and bundled with webpacks. I have a variables in a typescript file. When i do a producation build, I just want to change those variables when I deploy at various servers.
Example apiRoot= http://10.10.0.1/RESTSERVICES/---> when deployed at one server
when deployed at another server I what apiRoot do be different.
But I don't want to build the code multiple times to deploy at various locations.
For this reason I'm looking a run time config file for aurelia application built with webpacks. Thanks in Advance
I think what you are asking is potentially similar to the Q here Aureliajs Waiting For Data on App Constructor.
In that question, I gave suggestion on how to do it in different ways, which is copy-pasted below:
Aurelia provides many ways to handle asynchronous flow. If your custom element is a routed component, then you can leverage activate lifecycle to return a promise and initialize the http service asynchronously.
Otherwise, you can use CompositionTransaction to halt the process further, before you are done with initialization. You can see a preliminary example at https://tungphamblog.wordpress.com/2016/08/15/aurelia-customelement-async/
You can also leverage async nature of configure function in bootstrapping an Aurelia application to do initialization there:
export function configure(aurelia) {
...
await aurelia.container.get(HttpServiceInitializer).initialize();
}

Testing Receive Activities in WF4 State Machine

I'm trying to test my WF4 State Machine workflow. A few of the transitions are triggered by Receive activities and, based on the data in the message, make the the appropriate transition. Right now I'm using the WorkflowApplicationTest to run my tests, but am only able to test my timeout pathing, since any other transitions are triggered by this receive. I've looked at using the XamlInjector to mock the Receive, but it looks like it only works with custom activities. I also tried making a custom Receive activity so that I could mock that, but couldn't figure out everything I needed to do to make my custom receive work or find any info on creating custom Receive activities.
Is there a simple solution that I am overlooking on how to test this? And if a custom Receive is the only way to be able to use the XamlInjector, how do I write one?
I am using the Visual Studio test framework for my unit tests.
I've got just the thing for you. See How do I Mock Receive and Send activities?