Sails JS request validations through policies - sails.js

We're working on Sails JS to build an API, which will serve only JSON responses. Can i store all request validation rules in policies. So that my main app logic (controller) would look clean.
Pros: Application logic would be clean.
Cons: Will end up creating lot of policies.
Is there any other better way to keep code clean & maintain validation rules separately?
For validations we can use libraries like express-validator.

Not sure if this is the best way to do it, but you could create a helper that does your validations. The helper could have each type of validation as its inputs, and accept arrays for each. So in your controller, you would call the helper like:
var errorObject = sails.helpers.validate.with({
alphanumeric: [inputs.userName, inputs.displayName],
isEmail: [inputs.userEmail],
...
...
})
Then your helper could take each of those inputs and loop through the arrays doing the validation checks. If a validation error occurs, return the meat of an error object. If not, return an empty object. That way in your controller you can do something like this:
if(errorObject){throw errorObject}
You would still have to include all of the exits you would want in each controller though.

Related

Citrusframework - Java action - Get result

Besides REST-API Calls, I need to call my own Java-Class, which basically does something, which I want to confirm later in the test via REST-API-Calls.
When calling my Java-Class, there is an expected behavior: It may fail or not fail, depending on the actual Test-Case.
Is there any chance to code this expectation this into my test-class:
java("com.org.xyz.App").method("run").methodArgs(args).build();
As this is the Main-Class, which should be executed later in a automated fashion, I would prefer to validate the Return-Code.
However, I'm looking for any possible way (Exception-Assertion, Stdout-Check, ..) to verify the status of the program.
As you are using the Java DSL to write test cases I would suggest to go with custom test action implementation and/or initializing your custom class directly in the test method and call the method as you would do with any other API.
You can wrap the custom code in a custom AbstractTestAction implementation as you then have access to the TestContext and your custom code is integrated into the test action sequence.
The java("com.org.xyz.App").method("run").methodArgs(args) API is just for compliance to the XML DSL where you do not have the opportunity to initialize own Java class instances. Way too complicated for your requirement in my opinion.

JSF Validation of whole form with optional fields and a lot of dependencies

Just wanted to ask for the best way to solve my problem:
I got a form with multiple inputs/selects and also buttons to add new objects to the databean behind the form. Now my problem is the validation. E.g.: in one of those selects i chose an option. If this option is selected the user has to add a specific type of an object to the large databean behind the form. That's done by selecting values in two further selects. As soon as those are selected (they are submitted onchange by ajax) the user generates a new object by hitting an "Add" button.
On submit those added object (consisting of two values) must have a specific enum type depending on the first selected value and so on..
Now this all (and a lot more) should be validated and error/info messages should be added to the view.
Now my question: whats the best way to achieve this? The error message has to be at a specific place in the view.
I thought of multiple hidden input fields and using the validate attribute to call validation methods of the underlying bean (cause bean values are needed too). And then rendering an error message right at the position of the hidden field. Is this a good solution? Working with the validator attribute and validating the whole form would lead to error messages in areas where the user hasn't made any input yet, right? I would like to avoid that and just validate the current area. Is that possible by using one bean? Otherwise i would have to use multiple validators with a lot of attributes, or use the beanManager to get my underlying bean?
The JSF validation is done per component, not per form. This is by design (and it has a good purposes). There is a lot of misunderstanding on this point and many teams make the mistake of shoehorning their business logic validation into component validation, just because the word "validation" sounds right to them.
The validation you need is different - it's a business level validation. You don't really validate state of a single component, but rather coherence of the data, which is behind the components. You can still use the message framework to display the errors where you want them.
The clean and "proper" way to do it in JSF will be to:
skip the JSF component validation (because it's designed for different case than yours); you want all the values from the component to be put into your backing beans;
put anywhere you need an error message displayed;
write validation logic in your action method. You can use Bean Validation Framework or write the logic by hand;
if no errors are found, the action method performs an action;
on error, depending on the error, display a message in a proper place (using the component id);
if any error occured, don't perform the action and return from the action method.
The action method should look somewhat like this (this is not a copy-paste example, it's just to give you an idea of the flow):
public void doSomething() {
boolean valid = true;
if (startData.after(expiryDate)) {
FacesContext.getCurrentInstance().addMessage("expiryDate", new FacesMessage("Expiry date should come after creation date"));
valid = false;
}
// other checks
// checks could also make use of BVF validator - but then it's better to switch the BFV validation for the whole form
// (if you don't, then any single field validation will disable error checking for the business validation, which
// will look strange for your users)
if (!valid) {
// if we returned immediately upon detecting an error, we would only display the first one.
return;
}
// do the real stuff
}

Should I simulate FE request in Functional Testing in TYPO3?

I'm trying to understand concepts of Functional Testing in a scope of TYPO3 and overall.
My intention is to test Controller of my extension. For simplicity let's imagine, that it has only two methods: listAction() and addAction($object).
I've checked some Core tests and one of them was EnableFieldsTest from Extbase, which does following: loads some special crafted extension, simulates FE (via special JsonRenderer.ts), which calls listAction() of that extension and the output (specail JSON) is examined then.
So, I decided to do same with my Controller, simulated FE, which called my listAction(). The only difference is that my extension doesn't use JSON View, but usual Fluid, which produces HTML.
To make it work as expected I need either:
Make significant changes in my extension, so it outputs JSON in Testing context, but this seems kinda hacky for me.
Do not use provided HasRecordConstraint from the Core, but simply examine HTML, that was output with assertContains(), which also seems hacky.
Create customized version of my extension, which outputs expected JSON and use it only as Fixture. But this makes such test useless at all.
Therefore I'm stuck at this point and need to understand:
Is it right to simulate FE request, like I do, or I'm now out of Functional Testing concept?
In case I want to test object creation via addAction($object) and ensure, that f.e. a request to a REST service is made, should I stub that Service or I can catch a call somehow different?
Since TYPO3 8, acceptance tests are integrated which are more the thing you want to have.
Use functional tests to call the action and check the return value of that but don't use a frontend
Use acceptance tests to call the frontend and check the HTML output of your plugin.
The best would be to check out the acceptance tests of the core.

Which one is the correct approach for form validation ? Colander's Schema validation or Deform's form validation?

I have just started using Pyramid for one of my projects and I have a case where in I need to validate a form field input, by taking that form field value and making a web-service call to assert the value's correctness. Like for example there is a field called your bank's CUSTOMER-ID. I need to take that(alone) as input and validate at the server level by making a web-service call (like http://someotherdomain/validate_customer_id/?customer_id=<input_value>)lets say.
I am using Colander for form schema management and Deform for all form validation logic. I am confused about where I need to place my validation logic for the CUSTOMER-ID case. Is it at MySchema().bind(customer_id=<input_value>) (which has a deferred validator that queries the web-service) or something at the form.validate(request.POST.items()) ? If I take the deferred validator's path, then MySchema().bind is raising colander.Invalid error for incorrect CUSTOMER-ID. Thats fine. But that error is not at the form level but at the schema level. So how would I tell the user about this in a sane way ?
I have good experience with Django forms so I was expecting something like clean method. A form error like form['customer_id'].error is what I am expecting at the template level. Is it possible with Pyramid's Deform or with Colander ?
So I think the big problem you're having is understanding the separation of concerns of Colander and Deform. Colander is what people like to call a general schema validation library. Which means we define a schema, where each node has a particular data type and some nodes might be required/optional. Colander is then able to validate that schema, and tell us whether or no the data we passed to colander conforms to that schema. As an example, in my web apps, I am often building apis that accept GET/POST params that need to be validated. So in Pyramid, let's say I have this scenario:
request.POST = {
'post_id': 1,
'author_id': 1,
'unnecessary_attr': 'stuff'
}
I can then validate it like so:
# schema
schema = SchemaNode(Mapping(),
SchemaNode(Integer(), name='post_id'),
SchemaNode(Integer(), name='author_id'))
schema.deserialize(request.POST)
And it will error if it can't conform the data to the specified schema. So you can see, colander can actually be used to validate ANY set of data, whether that comes from POST/GET/JSON data. Deform on the other hand is a form library, and helps you create/validate forms. It uses colander for all of the validation needs and as you can see it pretty much just completely delegates validation to colander. So to answer your question, you would do all of your validation stuff in colander, and deform would mostly handle the rendering of your forms.
To see a vivid pyramid example application and deform in action look at todopyramid as a part of IndyPy Python Web Shootout. A todo application was implemented in pyramid, django, flask and bottle. I studied the pyramid example - it is well written, shows deform schema validation and uses bootstrap to show validation messages.
Find more pyramid tutorials here:

Does Core Data automatically validate new values when they are set?

In this question, someone asked how to write a validation method for Core Data. I did that, and it looks cool. But one thing doesn't happen: The validation. I can easily set any "bad" value and this method doesn't get called automatically. What's the concept behind this? Must I always first call the validation method before setting any value? So would I write setter methods which call the appropriate validation method first?
And if yes, what's the point of following a strict convention in how to write the validation method signature? I guess there's also some automatic way of validation, then. How to activate this?
Validation is not "automatic" especially on iOS. On the desktop you will have the UI elements handling the call to validation. On iOS you should be calling validateValue:forKey:error: with the appropriate key and dealing with the error should there be one. The reason for this is the lack of a standard error display on iOS and the overhead of validating all values.
Note this comment in the documentation:
If you do implement custom validation methods, you should typically not invoke them directly. Instead you should call validateValue:forKey:error: with the appropriate key. This ensures that any constraints defined in the managed object model are also applied.