Testing Best Practices possibly with regard to Gherkin but probably not - testing

A coworker and I are having an argument about the proper way to test. I'll lay them out as neutrally as I can, and won't give my opinion in this post.
This is written in gherkin. Substitute whatever pseudocode you want to.
Given I am a registered user
When I submit my credentials
Then I can login
Case one:
Given I am a registered user
(instantiates the user,
stores the user to scenario-global memory,
adds the user to the db with an API endpoint
stores the API endpoint result to scenario-global memory [200, "Success message"])
When I submit my credentials
(test the result of the previous step [200],
fills the credential field(s),
clicks submit, stores the result to scenario-global memory [200, "Success message"])
Then I can login
(tests the results of the previous step)
Case two:
Given I am a registered user
(instantiates the user,
stores the user in scenario-global memory,
adds the user to the db, tests the result of the db command)
When I submit my credentials
(fills the UI credential field(s),
clicks submit)
Then I can login
(perform some operation that only a logged-in user could do [see the my profile button/call some api endpoint])
​
The contention is whether or not the Then step can rely on the result from a previous operation.

It depends. First of all, as a tester, i would never directly write something to DB, instead i register the user in UI for UI testing or call endpoints to cover API testing scenarios.
Also, IMO, not every step is responsible for testing its own step, otherwise there is no need for 'Then' Gherkin syntax. This way of writing user stories makes it more understandable to non-technical but business people very clearly about the scenario under test.
For both cases above, i vote for case one and your co-worker's suggestion.

Overall, one should aim for declarative BDD scenarios, when trying to cover the features from end-user perspective. Pushing your how down is vital part of it. Employing Back door manipulation is great, but ask youself this - does your end user (or stakeholder) really care about technicalities?
adds the user to the db with an API endpoint
is something that is best used, when the register user flow is covered at least once through the UI. Mixing APIs and UI in the scenarios, can lead to a mess and maintenance issues. A proper DSL should handle that for you.
As to
each step is responsible for testing its own results. It is not responsible for what happened in the past or what is about to happen in the future
Cucumber-ish frameworks do use DI of context/state, exactly for this - share steps execution run in the current World instance.

Related

Are login/register commands or queries in CQRS

So for the login, since it doesn't really make anything new in the database but rather just returns if we've logged in, and possibly some user data, should it be a command or query?
And as for the register, since it creates a new user, should it be a command then? What if i want to return the users data or a jwt?
Should i run my commands and once the client receives a response run a query right after them?
As with most design related questions, I’d answer this one with ‘it depends’. I have seen both solutions implemented in different situations.
The main question you’d need to ask is whether you consider a user logging in as a state change of the system or not. Note that whether it changes state in de database isn’t relevant. The system is more than the database.
Log in as a command
For some systems, it’s important to know which users had been logged in and when, from where, etc. One example I had seen was a medical system that needed to record which doctor logged in when and where, and which medical records had been accessed. Also, logging in on one machine would stop tbe session on another. A reliable trace of these actions was essential to the application. As such, log in was implemented as a command which generated events that were stored in the Event Store. Projections kept the current logged in state for each user.
Log in as a query
Most systems I have seen, however, simple beed to know whether any given credentials can ve mapped to a user account. If that is the case, a token is generated containing the ‘proof’ of authentication. The system itself doesn’t really care who is logged in. It’s just that each request needs to be validated by checking the ‘proof’. In this case, logging in is a query.

Should integration test bypass login natural processes in order don't retest same login functionality for many times

Let's say I'm testing a web service and I have a couple of scenarios requires user to be authenticated:
Scenario #1: Customer sign-up
Scenario #2: Customer sign-in
Scenario #3: Customer change name
Scenario #4: Customer update image
Should all the tests go through all login steps like:
1) Go to register page
2) Enter new user information
3) Activate account
4) Go to login page
5) Enter login and password
6) Press the Login button
7) Check if I authenticated as a customer
Or I can just test it once and implement endpoint which quickly creates a user and log it in.
So if I have that kind of endpoint that means I can skip retesting the same things all the time and just have short scenarios #3 and #4 implementation. But in this case, I have a less natural environment.
Please tell me about the best practices that you use in real projects.
Few best practices:
use the testing pyramid integration > ui (tests are much slower on UI, automate in the UI only the necessary things to have main flows covered)
for the UI use fast methods for the setup (so yes, web services, test login only once)
if possible keep some test data trough the builds (for example to make sure a new build that might change data structure does not affect basic functionality, e.g. login)
tests should be atomic (not depend on each other)
do some cleanup from time to time to remove duplicate test code and to improve the framework(speed, stability)
You shouldn't copy and paste the "log in" scenario to all of the other scenarios, but having an account and being logged in are prerequisites for the other use cases. From a behavior driven development perspective this will translate to one or more Given steps that simulate or actually perform those steps:
Scenario: Customer change name
# Calls web service or database to create new user
Given "Bob" is a registered user
# Calls web service or database to make account active
And "Bob" has an active account
# Opens browser, navigates to login page, fills out login form and submits it
And the user is logged in as "Bob"
# Steps specific to changing name and asserting it has changed
When the user changes their name to "Samuel"
Then the user's name is "Samuel"

How to handle yodlee MFA?

There's almost no documentation on anything in yodlee. I have managed to correctly handle getLoginForm by just inspecting the JSON objects returned by different sites until I was able to handle all such forms.
What I don't understand is how to get the MFA fields, what makes them different, and how I submit them differently from the regular login form fields.
I'm new to the system, can anyone with some experience explain this to me?
MFA fields are security questions/tokens/images asked as a follow up from the typical login/password (although you'll soon learn there is nothing typical in the obscure world of bank authentication).
You get the MFA fields by calling getMFAResponse (once you've gotten an ItemID from your addItemForContentService1 call) - http://developer.yodlee.com/Indy_FinApp/Aggregation_Services_Guide/REST_API_Reference/getMFAResponse
Which you then use to build another form, and take that input and submit it with putMFARequest - http://developer.yodlee.com/Indy_FinApp/Aggregation_Services_Guide/REST_API_Reference/putMFARequest

User Auth in EventSourcing applications

I'm looking into crafting an app with DDD+CQRS+EventSourcing, and I have some trouble figuring out how to do user auth.
Users are intrinsically part of my domain, as they are responsible for clients. I'm using ASP.NET MVC 4, and I was looking to just use the SimpleMembership. Since logging in and authorising users is a synchronous operation, how is this tackled in an eventually consistent architecture?
Will I have to roll my own auth system where I keep denormalized auth tables on the read side? How to handle the security of this? Will I end up storing password hashes in both my event store and my view tables?
So many questions, if anyone can shed some light, I would be very thankful :)
tldr; How do you do User Auth in EventSource-applications?
Not every "Domain" or business component has to use DDD or CQRS. In most cases, user information is really cruddy, so you can usually not use DDD for that. Other domains don't really depend on the actual user. There's usually a correlation id (UserId) that gets shared by the various domains.
If using messaging in your system, one option is to register and manage users without CQRS, then send a command (RegisterUser { UserId } ). This would publish an event User Registered. Other domains can listen to this event to kick-off any workflows or ARs that are needed.
For our MVC CQRS app, we originally started off keeping all the user related information in the domain, and, like somebody mentioned, there was a RegisterUserCommand and a UserRegisteredEvent. After storing the user information in the domain, that event got published and picked up on the read side, which also created a user and generated all the password hashes, etc. We then done the authentication on the read side: the controller would make a call out to a 'read model authentication service' to authenticate against.
Later on down the road, we ended up completely refactoring this. It turned out that we needed access to the user related information to build in security for authorising our commands, which we done on the command processing side (our app is a distributed app that sends 'fire and forget' asynchronous commands to a queue, with an autonomous listener on the other side). The security component then needed a reference to our domain to go and get the user profile, which led to cumbersome referencing issues.
We decided to put the user security stuff into a separate database that we considered to be more of a central component, rather than belonging to the domain or read model. We still maintain user profile related information in the domain and read models (e.g. job title, twitter account URL etc.), but all the security related stuff, like password hashes, are stored in this central database. That's then accessible with a service, that's available to both MVC and the command authoriser.
We didn't actually have to change anything in the UI for this refactor, as we just called the service to register the users from the register user command handler. If you're going to do it that way, you need to be careful here to make your user service related operations idempotent. This is so that you can give your commands the opportunity to be retried without side effects, because you're updating 2 sources of information (the ES and the user database).
Finally, you could of course use the membership providers for this central component, but there can be pitfalls with that. We ended up just writing our own - it's pretty simple to do. That article links to this, which provides a good example of how to implement it.
You should consider creating separate entities like: visitor (just visited your site), user (registered), customer (bought something), etc. Try to split your system in this way, even if it causes a little bit of data redundancy. Disk space is not an issue but ability to modify different components of the system independently is usually very critical.
People create denormalized auth tables only for the purpose of scaling and only if your auth read side is a performance bottleneck. If not - usual 3rd normal form is a way to go.
In SimpleMembership scenario all tables created by SimpleMembership can be viewed as snapshot of "user" aggregate. And yes, they will duplicate some data in your event store.
You may have events like: UserCreated, UserUpdated, UserAssignedToRole, etc.
And don't be tricked by the name of that membership provider. It's not so simple and usually has lots of things that you can easily live without (depends on your domain). So, maybe you can use something like this: https://gist.github.com/Kayli/fe73769f19fdff40c3a7

OOP Design: Where should reusable validation be?

I've got a wizard which needs to validate if a user is logged in and then at the end validate that all the details they have entered are correct.
The issue is I'm not sure where to put the validation logic.
At the moment I have a BuyMembership class which has validation on the Buy() method.
However this won't be called at the beginning of the wizard where I need to validate whether the user is unique and is eligible for buying a membership.
For this validation I've created a BuyMembershipValidation class which validates if the user is eligible.
The issue now is that I have to pass a different parameter object to the BuyMembershipValidation and the BuyMembership classes. This means the data is split.
Is there a better way of doing it. Should I only load part of the information into the BuyMembership class for the initial validation and then load the rest after?
Update:
I need to validate when they enter the wizard (check if they are logged in already) and if they aren't then they will register as a new user otherwise I have to check if they have the right settings to buy membership as all users can't buy a membership. That's why I need two sets of validation. One for whether they're eligible and another for the actual data they enter to register. However I would like to recheck that they are eligible when they make the final transaction just in case they somehow made it past the first wizard step or if the web service (where I'm doing the logic) is called from somewhere else at a later point.
Another Update:
I've added an answer with my decision.
TIA,
Jonathan.
You're actually talking about three very different things here, and like Allain said, you need to think along the lines of single-responsibility to do this right, OOP-like.
Authentication: making sure a user is known
Authorization: making sure a user can access certain logic in your application
Validation: making sure the data a user inputs is valid/safe/what's expected or needed
A validator is typically tasked with validating user supplied information, not authorization. The single responsibility principle dictates that in your case they should definitely be handed by two objects.
Passing different parameter objects is fine, but but I think the authorization one shouldn't really be passed in to the BuyMembership object, it sounds like something that should be handled externally to it.
My 2 cents.
User authentication is a broad topic. It really depends on what type of application you are building. If it is a web application, I would recommend using one of the standard methods for authentication: NTLM / kerberos
As to when to validate, I don't see any problem with holding off on the validation until the actual Buy method is called. As long as during the steps in the wizard, you are not releasing any information to them and are only collecting data from a form. The main time when you need to be concerned about authentication is when you are actually placing an order or releasing information to the user that should be locked away in a database somewhere.
If you provide more details to what you are trying to do, I will refine my answer to help you a bit more. It's a rather broad question though, so this is the best I can come up with for now.
I've decided to go with just the one class. The reason is that there is common logic / behaviour in the IsEligible and Buy methods. One determines if the inputs meet the eligibility requirements and the other validates that all the details needed to buy the membership are valid. I don't really see this as authentication related. The authentication is done in a separate web control and I just check the Identity.IsAuthenticated and Username to see if they are logged in. I then check their username and if they are eligible to buy then I let them continue, otherwise show an error message. In terms of input validation I already have validation controls on my webpage but the validation I'm concerned with here is server side business logic validation. For that reason I think it should be in the business logic class. Not some validation class separate from the logic that performs the payment. This may just be my way of looking at it but I think this fits well with the BDD ideas of keeping validation inside the entity that holds the data.