If statement inside cypress.io test - unit-testing

I'm new to testing and to cypress.io in particular, and I'm trying to test the registering flow in my app.
I want to check two scenarios -
If the user is trying to register with an existing username, an error message should be popping up
Else if proper inputs are inserted, the username is successfully registered
How can I do so in one test? Is there an option to use if statement with cypress?
Thanks a lot in advance.

You can do something like:
If(Cypress.$(‘error msg locator’).length > 0) {
//error msg displayed.Do something
}
else {
//success login.Do something
}

Related

I m inserting my data uthrough page item using request process it gives an error fetch more then one row please give me a solution

var a = $v('P1995_LUMBER');
if ((a = '1')) {
apex.submit({
request: "CREATE",
set: {
LUMBER: "P1995_LUMBER",
LST_NME: "P1995_LST_NME",
FST_NME: "P1995_FST_NME",
},
});
} else if (a != '1') {
apex.submit({
request: "Update",
set: {
LUMBER: "P1995_LUMBER",
LST_NME: "P1995_LST_NME",
FST_NME: "P1995_FST_NME",
},
});
} else {
alert("bang bang");
}
Couple of things:
JavaScript's equality check is either == or === (more details here). (a = '1') assign '1' to the variable.
It seems like you're not using the apex.submit process correctly. Typically, you would set the item's value
e.g.:
apex.page.submit({
request: "SAVE",
set: {
"P1_DEPTNO": 10,
"P1_EMPNO": 5433
}
} );
Although, by looking at your JavaScript code, I would say you don't even need to use JavaScript.
Whenever you submit a page, all items on it are automatically sent to the server-side. You can then reference them using bind variables. You could then simply have two process, one for the Create and one for the Update, each having the corresponding insert/update statement using the different items on your page.
Usually what you will see is a page with two buttons for Create/Edit. They will have a server-side condition so that only the correct one is displayed.
Try creating a Form type page (form with report) using the wizard, and you'll see how everything is done.
Without seeing the page and the code you're using it's hard to tell what your issue really is, more details would be required.
That code does not have any sql in it so it is impossible to diagnose why you are encountering a TOO_MANY_ROWS exception. Run the page in debug mode and check the debug data - it should show you what statement is throwing the exception. If you need more help, post a proper reproducible case, not a single snipped of code without any context.

Flutter/Dart - Suggestions for how to Troubleshoot a Future?

Though it was working previously, for some reason my code has now stopped working. Though it fetches the required json data, the build doesn't render. The error on my app page which is supposed to display a page view was;
type String is not a subtype of 'Map<String,dynamic>'
But after some tweaks, now the error is;
invalid arguments(s)
I think I may have narrowed it down to the Future;
FutureBuilder<List<SpeakContent>> futureStage() {
return new FutureBuilder<List<SpeakContent>>(
future: downloadJSON(),
builder: (context, snapshot) {
if (snapshot.hasData) {
print("Snapshot has data.");
List<SpeakContent> speakcrafts = snapshot.data;
return new CustomPageView(speakcrafts);
} else if (snapshot.hasError) {
return Text('${snapshot.error}');
}
return new CircularProgressIndicator();
},
);
}
Future<List<SpeakContent>> downloadJSON() async {
final jsonEndpoint =
"http://example.com/getContent.php?";
final response = await get(jsonEndpoint);
if (response.statusCode == 200) {
List speakcrafts = json.decode(response.body);
debugPrint(speakcrafts.toString());
return speakcrafts
.map((speakcraft) => new SpeakContent.fromJson(speakcraft))
.toList();
} else
throw Exception('We were not able to successfully download the json data.');
}
Although it doesn't throw an error, I've noticed that it doesn't print my test statement after the "if (snapshot.hasData)" line.
Shouldn't I see "Snapshot has data." appear in my Android Studio console?
Based on what you provided, this
type String is not a subtype of 'Map<String,dynamic>'
must be this:
return Text('${snapshot.error}');
which means that your downloadJSON() threw an exception. In that case, print('Snapshot has data.'); never executes and the next case that I quoted above is executed.
Please put a breakpoint in the body of downloadJSON(), run it line by line and see what's thrown where.
ALSO, you are making an irrelevant but big mistake here. Do not call downloadJSON() like this. This function is executed at every re-render, which can be many times. You are initiating a JSON download at every redraw of your widget. This may stack up your backend bills... I explain it in this talk in more detail: https://youtu.be/vPHxckiSmKY?t=4771
After performing the troubleshooting tips as suggested by Gazihan Alankus and scrimau, I've found the culprit which was a single null entry in the MYSQL Database. Scary... gotta find out how to prevent that problem in the future.

In Cypress, how do I check if a button has an attribute or not?

I want to put an if condition if an attribute exist on a button or else do some other things. How can I do it in Cypress?
I have done this till now but not working...
'''
if(cy.get('button[type="button"]').should('have.attr','disabled')==true){
doTaskA()
}else{
doTaskB()
}
'''
This fails the whole test and not just the condition.
Two ideas come to mind:
Maybe checkout the Cypress guide on conditional testing. They have a bit about element existence. You might be able to do something similar : https://docs.cypress.io/guides/core-concepts/conditional-testing.html#Element-existence
Or maybe, perform the condition check manually using jquery:
let $el = Cypress.$("myselector");
if ($el.attr("myattr") === "myvalue") {
do.A();
} else {
do.B();
}

Unit Test case in Grails with mocking the methods

I was trying to write a unit test case for the action 'passwordActive' in 'LoginController'. But i am not sure which all things to be mocked and how to do that.
def passwordActive={
log.error("Entering into Password Active")
println "Password Active -- Params = "+params
String contextPath = request.contextPath
String username = null
User user = null
try{
if (params.username != null && params.username.trim().length() > 0) {
username = params.username
user = User.findByUsername(username)
}
if (user == null) {
log.error("USER not found.")
flash.errorLogin = "Username is incorrect"
redirect(action:"auth")
return
}else if(user.password != params.password){
log.error("USER password is wrong..")
flash.errorLogin = "Please enter valid password.."
redirect(action:"auth")
return
}else if (!user.active) {
log.error("USER is inactive.")
flash.errorLogin = "User in Inactive"
redirect(action:"auth")
return
}
session["userid"] = user.id
String userRole = user.authority.authority
String url = contextPath + "/" + userRole
println "URL = "+url
redirect(url: url, method: 'post', params: params)
return
}
catch(Exception e){
println e.printStackTrace()
}
log.error("Exit into Password Active")
}
i want to write a test case where username does not exist. in that case flash message should be having the message "username incorrect" and i can assert it.
Here what all things should be mocked and how to do that. Could you please explain the working with a small example (preferably related with above code so that it would be easy for me to understand)
Writing your own security implementation is a terribly bad idea. I suggest you take a look at how the Spring Security plugin does it for educational purposes, then just use that plugin - it is mature, flexible and easy to set up.
For said educational purposes, let's see how we could mock above code using an approach that is loosely along the lines of how Spring Security does it: You would move the user lookup into a service/bean as controllers aren't meant to contain any 'business' logic. Say something like this:
class UserProviderService {
User findUser(String username) {
User.findByUsername(username)
}
}
In the controller you would injected it as a dependency (def userProviderService) on which you would then call your own function, e.g. userProviderService.findUser(username). During normal operation Grails would inject your UserProviderService into the controller while in unit tests you can mock it however you like (e.g. controller.userProviderService = [ findByUsername: { -> return null } ] if you for example wanted to test the controller response for an unknown user.
Similar for password comparison you would use a passwordService that would implement password hashing, comparison and so on and you could mock its response before every test. Note that this stuff is again not trivial if you care about security and very easy to mess up so again: don't do it yourself!
The way you structure your code determines how easy or hard it will be to test it. Sure you could mess with User.metaclass and override methods left and right, but that approach usually proves very fragile. By splitting up your code you can make your life easier! How to structure your code so it is testable is definitely something you learn by experience so keep thinking about it!

C2664 cannot convert parameter 1 from from User *const to User in Qt C++

I am new to C++ and Qt, but I have been playing around with it for a couple of days and I need to come up with a basic prototype of my product by Friday, so there is not much time to convert my 7 years of PHP knowledge into C++ knowledge, as I am sure that it takes a lifetime to master C++. I am getting stuck from time to time in the last couple of days due to non-existing knowledge about the small bits and bytes. At this time I have even no idea what to look for on the Internet.
First of all, I am using Qt as my framework to do a simple GUI network client that can talk to my PHP application. I wanted to create a very simple WebAPI class in this application and have the class "webapi". The scenario is very simple, the user starts the application and the applications checks if the user is logged in or not. If not, then it opens up a login dialog. After entering the information (username / password) into the dialog the user object is filled and the method "authenticate" is called.
The authenticate method then calls the fUser method in the webapi class to make a request to the server holding some information to authenticate the user against the server's database.
In code it looks like this:
Savor.cpp:
user = new User();
while ( user->isLoggedIn() != true )
{
LoginDialog loginWindow;
loginWindow.setModal(true);
int result = loginWindow.exec();
if ( result == QDialog::Accepted )
{
user->authenticate(loginWindow.getUsername(), loginWindow.getPassword());
if ( !user->isLoggedIn() )
{
loginWindow.setUsername(loginWindow.getUsername());
loginWindow.exec();
}
}
else
{
exit(1);//exit with code 1
}
}
User.cpp:
void User::authenticate(QString username, QString password)
{
qDebug() << username;
qDebug() << password;
if ( username != "" && password != "")
{
webapi wapi;
loggedIn = wapi.fUser(this);
}
else
{
loggedIn = false;
}
}
webapi.cpp:
/**
Represents the fUser method on the server,
it wants to get a user object
the user will need to be authenticated with this
then all infos about user are transfered (RSA Keypair etc)
* #brief webapi::fUser
* #param username
* #param password
* #return User
*/
bool webapi::fUser(User baseUser)
{
return true;
}
Now you can clearly see that I am not doing anything at the moment in the webapi::fUser method. In fact, I am not even returning what I would like to return. Instead of a boolean I would like to return a User object, actually the same that I got in the first place through the parameter. However, i get a copy constructor error when I do that. (In my savor.h file I have declared a private attribute as a pointer => User *user;)
So the question is, what am I doing wrong when I call the fUser method? Why can I not simply pass the user object itself to the method ? I have not got around to fully understand const, and pointers and when to use what.
With Qt creator I actually use the MS Visual C++ compiler which throws the error as in the title:
C2664 'webapi::fUser' : cannot convert paramter 1 from 'User *const' to 'User'
I have read http://msdn.microsoft.com/en-us/library/s5b150wd(v=vs.71).aspx this page explaining when this happens, the only solutions is the conversion of the object itself.
If thats the case I might approach the entire problem in the wrong way.
I am looking forward to your tips and help on this matter.
Thank you very much.
webapi::fuser takes a User by value, but you are passing it a User* here:
wapi.fUser(this);
Either pass a User:
wapi.fUser(*this);
or change webapi to take a pointer to User.