How to set failed in POSTMAN Collection runner via script - if-statement

How can I set a "FAILED" via script? I have a IF and in this if I want to check is X compare to Y. If not I want to get an "FAILED". For now I get an "FAILED" in my console but the test is "PASS". I already searched other sites but found nothing about this. Hope u now what I mean.
if(pm.iterationData.get("ProfileSeries") == response.ProfileSeries){
console.log("expProfileSeries " + pm.iterationData.get("ProfileSeries") + " = "+ response.ProfileSeries);
}
else{
console.log("FAILED");
}

Add pm.test with relevant pm.expect:
pm.test('ProfileSeries should be equal', function () {
pm.expect(pm.iterationData.get("ProfileSeries")).to.equal(response.ProfileSeries);
});

Related

Using of if-else in Cypress test

Just learning how to write conditional tests using JS in Cypress. Write sample test as per Cypress.io
Test I trying to run:
describe ('sample tests', () => {
it('conditional test', () => {
cy.visit('https://example.cypress.io/commands/actions');
if (cy.get('input[placeholder*="Email"]')) => {
cy.type('email-1#mail.com')
} else {
cy.visit('https://www.google.com/')
}
})
})
Displayed error:
Error: Webpack Compilation Error
./cypress/e2e/4-home-page/test4.cy.js
Module build failed (from C:/Users/userName/AppData/Local/Cypress/Cache/12.3.0/Cypress/resources/app/node_modules/babel-loader/lib/index.js):
SyntaxError: C:\Users\userName\Desktop\Cypressinstall\cypress\e2e\4-home-page\test4.cy.js: Unexpected token (7:51)
5 | it('conditional test', () => {
6 | cy.visit('https://example.cypress.io/commands/actions');
> 7 | if (cy.get('input[placeholder*="Email"]')) => {
| ^
8 | cy.type('email-1#mail.com')
9 | } else {
10 | cy.visit('https://www.google.com/')
What I tried:
I moved "=>" in different location but Cypress display that "No tests found".
Expected behavior:
Cypress must run test without error, using condition if-else.
Understanding the use of "=>" is essential here and it has nothing to do with cypress.
The "=>" belongs to Javascript arrow functions
This is used to introduce shorter functions.
Now let's understand the then() method, reading this document
With the above, you should be able to understand how to use these principles correctly.
More to note:
If an element doesn't exist conditionally, we cannot use cy.get for that element (will trigger No Such Element Exception). Use
cy.get("body).then($body => {
//cy.get("body") returns the dom element which we can capture
with "then"
//Check if element exists
if($body.find("input[placeholder*=\"Email\"]").length > 0){
cy.get("input[placeholder*=\"Email\"]").type("email-1#mail.com");
}
else{
cy.visit('https://www.google.com/')
}
})
To learn more on cypress if conditions read the Cypress Documentations
Hope this helps!
As far as I understand you, the purpose in your given example is to verify if the element (email field) exists and if so, type there a value. In this case you'd better use conditional testing the following way and verify if the field is visible:
const emailField = 'input[placeholder*="Email"]';
cy.get('body').then(($email) => {
if ($email(emailField).is(':visible')) {
cy.type('email-1#mail.com')
}
else {
// Anything to do here
}
});
Or you can just check that element exist (if it's hidden for any reason):
const emailField = 'input[placeholder*="Email"]';
cy.get('body').then(($parent) => {
if ($parent.find(emailField).length > 0) {
cy.type('email-1#mail.com')
}
else {
// Anything to do here
}
});
Instead of cy.get('body').then... you can use any DOM element which is higher in the hierarchy than your desired element.

get serviceInstanceName and serviceKeyName for cloud foundry user provider serves by using cloudFoundryOperations

im trying to get the Credentials of UPS in cloud foundry:
using:
Mono<ServiceKey> serviceKey = (Mono<ServiceKey>) cloudFoundryOperations
.services()
.getServiceKey(
GetServiceKeyRequest.builder()
.serviceKeyName("digital_cassandra")
.serviceInstanceName("2a5aa377-e992-4f88-9f85-d9cec5c3bea9")
.build())
.subscribe();
serviceKey.map(serviceKey1 -> {
System.out.println(serviceKey1.getCredentials().toString());
return serviceKey1.getCredentials().get(0);
});
but nothing printed.
how to fet the serviceKeyName and serviceInstanceName by cloudFoundryOperations?
i need to print all the serviceKeyName and serviceInstanceName in my space.
.serviceInstanceName("2a5aa377-e992-4f88-9f85-d9cec5c3bea9")
It should be the actual name, not the guid. Like "my-key" or whatever you called your key.
but nothing printed. how to fet the serviceKeyName and serviceInstanceName by cloudFoundryOperations?
If you just want to print to the console, try something like this:
cloudFoundryOperations
.services()
.getServiceKey(GetServiceKeyRequest.builder()
.serviceInstanceName("reservation-db")
.serviceKeyName("cf-mysql")
.build())
.doOnNext(key -> {
System.out.println("Key:");
System.out.println(" " + key.getName() + " (" + key.getId() + ")");
key.getCredentials().forEach((k, v) -> {
System.out.println(" " + k + " => " + v);
});
})
.block();
The GetServiceKeyRequest determines which service key is looked up. The doOnNext call allows you to inspect but not consume the key, which works fine to print it out. Then the example calls .block() to wait for the results, which is fine cause this is just an example. You wouldn't want to do that in your actual code though. You'd probably want one of the subscribe() variants (you could swap subscribe() for doOnNext() too, just depends on what you're code is doing).
i need to print all the serviceKeyName and serviceInstanceName in my space.
To get all the keys for all the service instances:
cloudFoundryOperations
.services()
.listInstances()
.doOnNext(si -> {
System.out.println(" " + si.getName() + " (" + si.getId() + ")");
})
.flatMap((ServiceInstanceSummary si) -> {
return ops
.services()
.listServiceKeys(ListServiceKeysRequest.builder()
.serviceInstanceName(si.getName())
.build())
.doOnNext(key -> {
System.out.println("Key:");
System.out.println(" " + key.getName() + " (" + key.getId() + ")");
key.getCredentials().forEach((k, v) -> {
System.out.println(" " + k + " => " + v);
});
});
})
.blockLast();
This one is enumerating all the service instances, printing the name/id, then using flatMap to go out and get the service keys for each service instance. It then merges them all into one Flux<ServiceKey>. The doOnNext() is just for printing. You don't necessarily have to do that. You could consume the result in a number of ways, like collect it into a list or subscribe to it, this just works nicely for an example. Use what works best for your code.

Calling a Web Service (containg multiple pages) does not load all the pages (without an added sleep delay)

My question is about a strange behavious I notice both on my iPhone device and the codenameone simulator (NetBeans).
I invoke the following code below which calls a google web service to provide a list of food places around a GPS coordinate:
The web service that is called is as follows (KEY OBSCURED):
https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=40.714353,-74.00597299999998&radius=200&types=food&key=XXXXXXXXXXXXXXXXXXXXXXX
Each result contains the next page token and thus, the second call (for the subsequent page) is as follows:
https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=40.714353,-74.00597299999998&radius=200&types=food&key=XXXXXXXXXXXXXXXXXXXXXXX&pagetoken=YYYYYYYYYYYYYYYYYY
public static byte[] getWSResponseData(String urlString, boolean usePost)
{
ConnectionRequest r = new ConnectionRequest();
r.setUrl(urlString);
r.setPost(usePost);
InfiniteProgress prog = new InfiniteProgress();
Dialog dlg = prog.showInifiniteBlocking();
r.setDisposeOnCompletion(dlg);
NetworkManager.getInstance().addToQueueAndWait(r);
try
{
Thread.sleep(2000);
}
catch (InterruptedException ex)
{
}
byte[] responseData = r.getResponseData();
return responseData;
}
public static void getLocationsList(double lat, double lng)
{
boolean done = false;
while (!done)
{
byte[] responseData = getWSResponseData(finalURL,false);
result = Result.fromContent(parser.parseJSON(new InputStreamReader(new ByteArrayInputStream(responseData))));
String venueNames[] = result.getAsStringArray("/results/name");
nextToken = result.getAsString("/next_page_token");
if ( nextToken == null || nextToken.equals(""))
done = true;
else
finalURL = completeURL + "&pagetoken=" + nextToken;
}
.....
}
This code works fine with the sleep timer, but when I remove the Thread.sleep, only the first page gets called.
Any help would be appreciated.
Using the debugger does not help as this is a timing issue and the issue does not occur when using the debugger.
Also when I put some print statements into the code
while (!done)
{
String nextToken = null;
**System.out.println(finalURL);**
...
}
System.out.println("Total Number of entries returned: " + itemCount);
I get the following output:
First Run (WITHOUT SLEEP):
https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=40.714353,-74.00597299999998&radius=200&types=food&key=XXXXXXXX
https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=40.714353,-74.00597299999998&radius=200&types=food&key=XXXXXXXX&pagetoken=CqQCF...
Total Number of entries returned: 20
Using the network monitor I see that the response to the second WS call returns:
{
"html_attributions" : [],
"results" : [],
"status" : "INVALID_REQUEST"
}
Which is strange as when I cut and paste the WS URL into my browser, it works fine...
Second Run (WITH SLEEP):
https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=40.714353,-74.00597299999998&radius=200&types=food&key=XXXXXXXXX
https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=40.714353,-74.00597299999998&radius=200&types=food&key=XXXXXXXXX&pagetoken=CqQCFQEAA...
https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=40.714353,-74.00597299999998&radius=200&types=food&key=XXXXXXXXX&pagetoken=CsQDtQEAA...
Total Number of entries returned: 60
Well it seems to be a google API issue as indicated here:
Paging on Google Places API returns status INVALID_REQUEST
I still could not get it to work by changing the WS URL with a random parameter as they suggested, but I will keep trying and post something here if I get it to work. For now I will just keep a 2 second delay between the calls which seems to work.
Well gave up on using the google WS for this and switched to Yelp, works very well:
https://api.yelp.com/v3/businesses/search?.....

Caffe C++ save network caffemodel file

I have successfully built and trained an audioCaffe demo, but the demo doesn't save the network.
I have found documentation for saving the network in Python in MatLab, but I can't find any documentation on C++.
I would think there would be a similar function like net.save("file.caffemodel") but I tried that and it didn't work.
In the train function in caffe.cpp I tried this:
if (FLAGS_snapshot.size()) {
LOG(INFO) << "Resuming from " << FLAGS_snapshot;
solver.Solve(FLAGS_snapshot);
} else if (FLAGS_weights.size()) {
LOG(INFO) << "Finetuning from " << FLAGS_weights;
solver.net()->CopyTrainedLayersFrom(FLAGS_weights);
solver.Solve();
} else {
solver.Solve();
}
solver.save("file.caffemodel")
But I got a no method exists error
Any ideas?
Please try this...
caffe::NetParameter net_param;
net_->ToProto(&net_param);
caffe::WriteProtoToBinaryFile(net_param, caffe_model_path);
You should look at Snapshot() and SnapshotToBinaryProto() - src/caffe/solver.cpp.
Caller code is in Solver::Step:
// Save a snapshot if needed.
if ((param_.snapshot()
&& iter_ % param_.snapshot() == 0
&& Caffe::root_solver()) ||
(request == SolverAction::SNAPSHOT)) {
Snapshot();
}

Sahi: _include in if statements

I'm trying to run the following code as a sahi script:
_include("initialScript.sah");
_include("secondScript.sah");
function currentTime(){
var $current = new Date();
var $hours = $current.getHours();
var $minutes = $current.getMinutes();
if ($minutes < 10){
$minutes = "0" + minutes;
}
if($hours > 11){
_log("It is " + $hours + ":" + $minutes + " PM");
}
else {
_log("It is " + $hours + ":" + $minutes + " AM");
}
if($hours >= 8 || $hours =< 20) {
_include("aScript.sah");
_include("anotherScript.sah");
...
}
else {
//do nothing and continue below
}
}
_include("yetMoreScripts.sah");
...
Simply put, I have a block of various scripts, followed by a check of the current time.
If it isn't between 8am and 8pm, the included block of scripts is skipped and the others below are executed. The _logs tell me that getting the time appears to work as intended.
Yet whenever I attempt to run the script as is, I get an immediate failure and completely unrelated Syntax Errors (such as on an _include way further down that is not faulty at all). Taking the _includes out of the if Statement seems to make the errors stop. For all I know this should work but just doesn't. Does anybody have experience with something similar and could give me a hint as to where I made a mistake?
as far as I can tell, this should work. A simple test:
test1.sah:
_log("ok");
test2.sah:
if (true) {
_include("test1.sah");
}
When I run this from the Sahi Controller, I get an "ok" logged. Maybe recreate this test and check if you get the same results.
Maybe it's the ";" missing after your includes?
Are you passing dynamic values to include? like _include($path)?