Currently i am trying to refactor a API without breaking changes. trying to migrate it from something like host:port/foo/bar to host:port/barand im wondering if in Scalatra multiple routes are supported on a single action. I am trying it like:
get("/foo/bar", "/bar") {
Ok(200)
}
its returning with a empty response on either endpoint with a response code of 0 so i'm kind of puzzled. Is this supported in Scalatra?
I know in spring it'd look something like: https://stackoverflow.com/a/5517486/4682816 but i am curious if there is something in Scalatra
Scalatra supports multiple transformers for a action, but it means the action in called if all transformers are matched. This is used to add additional conditions to the routing.
In your case, a request path can't match both "/foo/bar" and "/bar", so I guess the action is never called.
You can do it instead as follows:
get("/foo/bar"){
bar()
}
get("/bar"){
bar()
}
private def bar() = {
Ok(200)
}
or you can use regular expression:
get("^(/bar)|(/foo/bar)$".r){
Ok(200)
}
Related
I have a camel route that reaches out to a URL and does some processing with the results:
from("direct:doURL")
.routeId("urlRouteId")
.to("http://host:port/path")
.process(e -> {
//Do Stuff
});
I can run unit test on that route without making an actual call to the URL by intercepting the call in my unit test like follows:
AdviceWith.adviceWith(context, "urlRouteId", a ->
a.interceptSendToEndpoint("http://host:port/path").skipSendToOriginalEndpoint().to("mock:test")
);
I’m updating that route to use .serviceCall() instead to look up the actual URL of the service, something like this:
from("direct:doService")
.routeId("servcieRouteId")
.serviceCall("myService/path")
.process(e -> {
//Do Stuff
});
This works great, but I don’t know how to do a similar unit test on this route. Is there some sort of LoadBalancerClient I can use for testing? What is the standard way to unit test routes with service calls? I've been googling around for awhile and haven't had much luck, any ideas?
Thanks
You can give serviceCall endpoint an id and then use weaveById.
from("direct:doURL")
.routeId("urlRouteId")
.serviceCall("foo").id("serviceCall")
.log(LoggingLevel.INFO, "body ${body}");
AdviceWith.adviceWith(context(), "urlRouteId", a -> {
a.weaveById("serviceCall")
.replace()
.setHeader(Exchange.HTTP_RESPONSE_CODE).constant(200)
.setBody().simple("Hello from service");
});
Alternatively if service is a bean in camel registry then you could probably override bindToRegistry method and use Mockito to create a mock service.
Also instead of using interceptSendToEndpoint it would likely be much simpler to just use weaveByToUri("http*").replace() instead.
Example generic method for replacing http-endpoints
private void replaceHttpEndpointWithSimpleResponse(String routeId, String simpleResponse) throws Exception {
AdviceWith.adviceWith(context(), routeId, a -> {
a.weaveByToUri("http*")
.replace()
.setHeader(Exchange.HTTP_RESPONSE_CODE).constant(200)
.setBody().simple(simpleResponse);
});
}
I was looking at the documentation at: https://pub.dartlang.org/packages/mockito and was trying to understand it more. It seems that in the examples, the function stubs were accepting strings, but was kind of confused as to how I was going to implement my Mocked Services.
I was curious how I would do it. The services I have is pretty simple and straight forward.
class Group{}
class GroupService {}
class MockGroupService extends Mock implements GroupService {}
final mockProviders = [new Provider(MockGroupService, useExisting: GroupService];
So you can see I am using Angular dart.
I was creating a sample group in my Test file.
group("service tests", (){
MockGroupService _mock;
testBed.addProviders([mockProviders]);
setUp(() async {
fixture = await testBed.create();
_mock = new MockGroupService();
//This is where I was going to create some stubbs for the methods
when(_mock.add()).thenReturn((){
return null; //return the object.
});
//create additional when statements for edit, delete, etc.
});
});
So what i was thinking is that there would be an argument passed into add (or 2).... how would I properly code that in the when statement, and how do those 2 arguments reflect in the then statement?
Essentially, I was wanting to do a test with a complex class.. and pass it into add. Then it would just process it accordingly and return it.
Do i pass into the arguments something akin to: (using pseudocode)
when(_mock.add(argThat(hasType(Group)))).thenReturn((Group arg)=> arg);
or something similar? hasType isnt function, so im not 100% sure how to approach this design. Ideally, Im trying create the Group in the test, and then pass it into the add function accordingly. It just seems that the examples were showing Strings.
Yes mockito allows objects to be passed you can see examples in the test.
It is a bit hard to follow but you can see here that it uses deep equality to check if arguments are equal if no matchers are specified.
The second part of your question is a bit more complex. If you want to use the values that were passed into your mock as part of your response then you need to use thenAnswer. It provides you with an Invocation of what was just called. From that object you can get and return any arguments that were used in the method call.
So for your add example if you know what is being passing in and have complete access to it I would write:
Group a = new Group();
when(_mock.add(a)).thenReturn(a);
If the Group object is being created by something else I would write:
when(_mock.add(argThat(new isInstanceOf<Group>()))
.thenAnswer((invocation)=>invocation.positionalArguments[0]);
Or if you don't really care about checking for the type. Depending on what checks you are using for your test the type might already be checked for you.
when(_mock.add(any)).thenAnswer(
(invocation)=>invocation.positionalArguments[0]);
Or if you are using Dart 2.0:
when(_mock.add(typed(any))).thenAnswer(
(invocation)=>invocation.positionalArguments[0]);
I'm using grails plugin multi-tenant-single-db. Within that context I need to write a spock test in which we temporarily remove the tenant restrictions. Location is my Tenant, so my method looks like this:
def loadOjectDetails(){
Location.withoutTenantRestriction{
// code here to retrieve specific items to the object to be loaded
render( template: "_loadDetails", model:[ ... ]
}
}
The method runs as expected, but trying to put method under test coverage the error output suggests that:
groovy.lang.MissingMethodException: No signature of method: com.myPackage.myController.Location.withoutTenantRestriction() is applicable for argument types:
and a stacktrace that stems on from there.
Do I need to Stub this? The withoutTenantRestriction is a wrapper around my entire method logic.
UPDATE:
The test code looks like this:
given:
params.id = 3002
currentUser = Mock(User)
criteriaSetup()
controller.getSalesOrder >> salesOrders[2]
when:
controller.loadOrderManageDetails()
then:
(1.._) controller.springSecurityService.getCurrentUser() >> currentUser
expect:
view == 'orderMange/orderManageDetail'
model.orderInstance == salesOrders[2]
Yes! You should be stubbing it as is created at run time not compile time.
You could stub it like below:
Your_Domain.metaClass.withoutTenantRestriction{Closure closure ->
closure.call()
}
This way your regular code will work in test cases. Also,as in withoutTenantRestriction it basically starts a new hibernate session, which doesn't matter much as now you have stubbed the closure, you could perform desired action in place of calling closure.call() only.
Also, same could be applied to withThisTenant.
In integration tests you don't need to stub it as is loading the whole environment.
Hope it helps!!
I want to execute an action every time a mock function is called. I tried implementing this using ACTION_P. See the code below:
ACTION_P(CompleteRegistrationWithStatus, status)
{
arg1->registrationCompleted(status);
}
And the expectation goes like:
EXPECT_CALL(*mockObj, register(_)).WillOnce(CompleteRegistrationWithStatus(success));
Problem is, I had to use the same expectation multiple times, just different status. So I needed to put the expectation inside a member function of the test fixture to avoid code redundancy. But the function cannot access the ACTION_P I defined since it is not a member of the fixture.
I tried searching for ACTIONs that are fixture members, like that of MATCHERs, but to no avail.
Any suggestions for a possible solution or alternative? Any form of help is much appreciated. TIA!
I'm not sure that I understand the need to put the expectation in a member function of the fixture, but you should be able to get the behavior you want using InSequence:
{
InSequence s;
EXPECT_CALL(*mockObj, register(_))
.WillOnce(CompleteRegistrationWithStatus(success));
EXPECT_CALL(*mockObj, register(_))
.WillOnce(CompleteRegistrationWithStatus(failure));
}
I added some razor views and use a request filter to check browser version and switch between desktop and mobile views. But when a exception occurs, especially validation exception, it seems the framework return immediately and never touched any custom code. I tried request/response filter, service exception handler, none got executed. It seems to ignore view/template specified in URL query string as well.
Is there way to set view/template during exception? Thanks
The first question is how are you handling validation exceptions?
the most common procedure to perform this kind of task is by using the fluentValidation, the response can return a message for more than one validation at the time, all the validations are against DTOs and you´ll need to implement an AbstractValidator, the first thing you need to do is to register the validators that belons to your applciation like the following:
Plugins.Add(new ValidationFeature());
container.RegisterValidators(typeof(CredentialsAuthValidator).Assembly);
I´m valdiating in this case that the Auth username and password should not be Empty, take a look to the following example:
public class CredentialsAuthValidator : AbstractValidator<ServiceStack.ServiceInterface.Auth.Auth>
{
public CredentialsAuthValidator()
{
RuleSet(ApplyTo.Post, () =>
{
RuleFor(x => x.UserName).NotNull().WithMessage("Username Required").When(x => x.provider == "Credentials");
RuleFor(x => x.Password).NotNull().WithMessage("Password Required").When(x => x.provider == "Credentials");
}
);
}
}
if some of the validation fails you´ll get a responseStatus from the server with the errorCode and the messages.
You can configure a custom httpHandlers in the case you would like to have a handler for specific scenarios or a global error handler, this can be performed in your serviceHost configuration, something like this:
GlobalHtmlErrorHttpHandler = new RazorHandler("/views/error"),
CustomHttpHandlers =
{
{HttpStatusCode.NotFound, new RazorHandler("/views/notfound")},
{HttpStatusCode.Unauthorized, new RazorHandler("/views/login")},
{HttpStatusCode.Forbidden, new RazorHandler("/views/forbidden")},
}
Thanks for the help from Pedro, and especially mythz from ServiceStack. Now I think I start to understand my problems.
ServiceStack is first and foremost a service framework and Razor is just another view over the same result. But I was a little hesitate with a full on client side solution and keep falling back to familiar territory and looking for some kind of code-behind feature. That seems to be the root of lots of my struggles.
After some more research, this is what I come up so far.
ServiceStack for service, of course.
Razor view to build the basic layout and the main page for each major feature
Build a json script tag from model to hold initial data, like in SS's HTML Report
Jquery and Eldarion ajax for all subsequent in-page processing
Handlebars for javascript templating
Verifyjs for validation
So far look promising. Pages are lot smaller in size, running super smooth and mostly pure json flying over the wire.
Still a work in progress, all suggestions welcome.
ViewSwitch works when I changed to use Request Filter instead. Got the correct layout and all the references, etc. Although they have to share the same error page, but there's not much formatting in there.