We have application that used Pretender to provide fixtures for tests. Now we're trying to migrate to ember-cli-mirage. We cannot migrate all the fixtures at once. So what is basically happening there is that we are starting our own Pretender server and ember-cli-mirage is starting it's own. Whic renders following warning:
You created a second Pretender instance while there was already one running. Running two Pretender servers at once will lead to unexpected results and will be removed entirely in a future major version.Please call .shutdown() on your instances when you no longer need them to respond.
Since it is just a warning, it should not be an issue for the transient period. Problem is that once Mirage is loaded into our application, old Pretender routes stops responding. I guess that's what "... will lead to unexpected results" is referring to.
Any chance to run ember-cli-mirage alongside manually created Pretender routes? Or just to use Mirage server and inject those routes there?
I would use Mirage's server and then load up your Pretender routes inside of it. (Mirage's server is really just an object that news up a Pretender instance). If folks see mirage folder they'd probably expect the routes to be defined there. Also, Mirage cleans up its Pretender instance during testing.
In mirage/config.js you could import your existing Pretender routes and call them there. Mirage has sugar on top of Pretender but you can always access the underlying pretender instance via this.pretender within the config function:
// mirage/config.js
import setupYourOldRoutes from 'somewhere';
export default function() {
this.get('users'); // new Mirage shorthand
setupYourOldRoutes(this.pretender);
}
So setupYourOldRoutes could be a function that takes a pretender instance and then defines all your existing route handlers using it.
Based on #samselikoff answer I found a solution for my case. We already have one central point, that is handling creation of pretender instance. So the fix was just to pass Mirage's Pretender instead of creating new one:
// somewhere.js
export default function () {
// initPretender: function () {
// this.pretender = new Pretender();
// }
initPretender: function (pretender) {
this.pretender = pretender;
},
getPretender: function () {
return this.pretender;
}
}
// mirage/config.js
import pretenderWrapper from 'somewhere';
export default function() {
this.get('users'); // new Mirage shorthand
pretenderWrapper.initPretender(this.pretender);
}
Tricky part was to make sure that initPretender() is called before any of our legacy code tries to call getPretender(). I think usually that is not a trouble. In our case we patched tests/helpers/start-app.js so that some fixtures were injected in every test. And that caused calling getPretender() too early.
Related
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.
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();
}
I am currently working on a Service Fabric project, where in one of our reliable actors we make calls to a SOAP service. For these calls we read a couple of parameters from the Actor's Settings.xml and also - the SOAP endpoint address and binding information from the App.config file (actually the latter is done implicitly by the generated service proxy class for the SOAP service).
Now I am trying to get the unit testing work with xUnit + ServiceFabric.Mocks. To test an Actor specific method I go through:
1) Creating a "MockCodePackageActivationContext"
2) Creating a "StatefulServiceContext" using the instance of the activation context in step 1.
3) Instantiate the Actor with the code below
MyActor target = new MyActor(
new ActorService(
context: serviceContext,
actorTypeInfo: ActorTypeInformation.Get(typeof(MyActor)),
stateManagerFactory: (actorBase, stateProvider) => new MockActorStateManager()
),
new ActorId(Guid.NewGuid())
);
4) I call target.MyMethod() which breaks due to inability to read config info either from the Settings.xml or the App.config file
I made a test where target.MyMethod_Test() does not read anything from config and it was successful.
Anyone who stumbled upon similar thing? How did you solve it?
You could create a separate class that provides configuration data. Create an interface for it and then inject it in the Actor constructor, in Program Main. (Passing the service context into the new class for example.)
Also create a mock implementation of the interface and pass that one to the Actor for testing purposes.
Considering this example: http://emberjs.jsbin.com/hecewi/1/edit?html,js,output
The docs state that an action will be searched for on the controller first (which works in the example e.g. by pasting the actions hash into the IndexController), then on the current route and then along its parent routes until it hits ApplicationRoute. I'd expect the testCamel action in the example to be triggered then, but instead there is an error about the route did not get handled. How to do it right?
The code to trigger an action is indeed correct. It's just an unfortunate chosen example. Since your route will initialize the controller, the route itself is probably not completely initialized by the time the action is sent. If you, for example, schedule the action to be triggered in the following run loop, it works perfect:
http://emberjs.jsbin.com/yaseva/1/edit
I'm trying to figure out how to shut down an instance of Express. Basically, I want the inverse of the .listen(port) call - how do I get an Express server to STOP listening, release the port, and shutdown cleanly?
I know this seems like it might be a strange query, so here's the context; maybe there's another way to approach this and I'm thinking about it the wrong way. I'm trying to setup a testing framework for my socket.io/nodejs app. It's a single-page app, so in my testing scripts (I'm using Mocha, but that doesn't really matter) I want to be able to start up the server, run tests against it, and then shut the server down. I can get around this by assuming that either the server is turned on before the test starts or by having one of the tests start the server and having every subsequent test assume it's up, but that's really messy. I would much prefer to have each test file start a server instance with the appropriate settings and then shut that instance down when the tests are over. That means there's no weird dependencies to running the test and everything is clean. It also means I can do startup/shutdown testing.
So, any advice about how to do this? I've thought about manually triggering exceptions to bring it down, but that seems messy. I've dug through Express docs and source, but can't seem to find any method that will shut down the server. There might also be something in socket.io for this, but since the socket server is just attached to the Express server, I think this needs to happen at the express layer.
Things have changed because the express server no longer inherits from the node http server. Fortunately, app.listen returns the server instance.
var server = app.listen(3000);
// listen for an event
var handler = function() {
server.close();
};
Use app.close(). Full example:
var app = require('express').createServer();
app.get('/', function(req, res){
res.send('hello world');
});
app.get('/quit', function(req,res) {
res.send('closing..');
app.close();
});
app.listen(3000);
Call app.close() inside the callback when tests have ended. But remember that the process is still running(though it is not listening anymore).
If after this, you need to end the process, then call process.exit(0).
Links:
app.close: http://nodejs.org/docs/latest/api/http.html#server.close (same applies for)
process.exit:
http://nodejs.org/docs/latest/api/process.html#process.exit
//... some stuff
var server = app.listen(3000);
server.close();
I have answered a variation of "how to terminate a HTTP server" many times on different node.js support channels. Unfortunately, I couldn't recommend any of the existing libraries because they are lacking in one or another way. I have since put together a package that (I believe) is handling all the cases expected of graceful HTTP server termination.
https://github.com/gajus/http-terminator
The main benefit of http-terminator is that:
it does not monkey-patch Node.js API
it immediately destroys all sockets without an attached HTTP request
it allows graceful timeout to sockets with ongoing HTTP requests
it properly handles HTTPS connections
it informs connections using keep-alive that server is shutting down by setting a connection: close header
it does not terminate the Node.js process
Usage with Express.js:
import express from 'express';
import {
createHttpTerminator,
} from 'http-terminator';
const app = express();
const server = app.listen();
const httpTerminator = createHttpTerminator({
server,
});
await httpTerminator.terminate();
More recent version of express support this solution:
const server = app.listen(port);
const shutdown = () => {
server.close();
}
You can easily do this by writing a bash script to start the server, run the tests, and stop the server. This has the advantage of allowing you to alias to that script to run all your tests quickly and easily.
I use such scripts for my entire continuous deployment process. You should look at Jon Rohan's Dead Simple Git Workflow for some insight on this.