Artillery: How can I mark a test scenario as failed using artillery load test and show the same in some report? - artillery

I am working on some test requirement where I have to fail a load test scenario when p95>100ms. I have written below test snippet:
config:
target: "https://news.google.com"
# Responses have to be sent within 10 seconds or the request will be aborted
timeout: 10
ensure:
p95: 800
phases:
- duration: 10
arrivalRate: 1
scenarios:
- name: "Hit news google"
flow:
- get:
url: "/dssw.js_data?_reqid=34556&rt=j"
expect:
- statusCode: 300
- contentType: json
I want this test scenario to be visible in some kind of reports as how many test case has been failed and pass. Artillery generates the report only showing the performance stats but how to show the report as per the test performance assertion failed in some kind of report.

One option is to implement a hook in javascript that looks at the status code and if deems the status as failed returns an error trough the next function.
Example js hook function:
function exitOnFail(requestParams, response, context, ee, next) {
const statusCode = parseInt(response.statusCode);
if (statusCode > 399) {
next(new Error(`${requestParams.url} StatusCode: ${statusCode}`));
} else {
next();
}
}
and connecting the hook to the request:
config:
...
processor: './scriptfile.js'
...
scenarios:
- flow:
- get:
url: some/url
...
afterResponse: 'exitOnFail'

Related

Cypress cy.request returns 404

I am using Cypress with react and node express server. I am trying to build a test that starts by calling cy.request with post method in order to initialize the state of the app for this particular test, but the response is always 404 as the following
Error:
CypressError: cy.request() failed on:
mysite.net
The response we received from your web server was:
404: Not Found
This was considered a failure because the status code was not '2xx' or '3xx'.
If you do not want status codes to cause failures pass the option: 'failOnStatusCode: false'
The request does work in prod/dev (status 200) but in cypress it always returns 404 as mentioned. I also checked the data structure of the request and it seems ok.
I am using the same route for all, the only difference is the method I use:
dev/prod: standard fetch API call seats under an apiHandler function.
Cypress: cy.request() method
My code:
cy.request({
method: 'POST',
url: `auth/login/example-url`,
failOnStatusCode: false,
form: true,
body: {
arrival: '2021-12-01T17:23',
departure: '2021-12-01T15:23',
destination: 'New York',
origin: 'Washington DC',
},
})
Thanks ahead for your help:)
when Browser: send request header and response status code OK
Using cy.visit(): response status code Not Found
So the problem is the Request Headers, you better check it, and set Headers in cy.visit() to look like Browser Headers. you'll receive the status code OK.

test case execution is getting failed and it is throwing any error stack trace in command line

I created a testcase with Protractor-cucumber framework and I have used Grunt for execution of that test case. However, at the time of execution it failed and it's not providing any error stacktrace to know why it is failing.
I've searched Google and also reviewed other Stack Overflow solutions but I didn't find a solution for this.
Config File
exports.config = {
//seleniumAddress: 'http://localhost:4444/wd/hub',
getPageTimeout: 60000,
allScriptsTimeout: 500000,
directConnect:true,
framework: 'custom',
// path relative to the current config file
frameworkPath: require.resolve('C:\\...\\node_modules\\protractor-cucumber-framework'),
capabilities: {
'browserName': 'chrome'
},
ignoreUncaughtExceptions:true,
// Spec patterns are relative to this directory.
specs: [
'./learnFramework/utility/test.feature'
],
cucumberOpts: {
require: './learnFramework/TestCases/spec.js',
tags: false,
profile: false,
'no-source': true
},
onPrepare: function () {
browser.ignoreSynchronization=true;
browser.manage().window().maximize();
}
};
Spec File
module.exports=function(){
this.Given(/^Open the browser and Load the URL$/,async function(){
browser.get("https://google.com");
});
this.When(/^User entered the text in the search box$/,async function(){
browser.sleep(5000);
console.log(await browser.getTitle());
await element(By.name("q")).sendKeys("facebook");
browser.sleep(3000);
});
this.Then(/^click on search$/,async function(){
browser.action().sendKeys(protractor.Key.ENTER).perform();
browser.sleep(5000);
});
}
Error Log
Running "jshint:files" (jshint) task
>> 1 file lint free.
>
Running "protractor:singlerun" (protractor) task
[00:08:29] I/launcher - Running 1 instances of WebDriver
[00:08:29] I/direct - Using ChromeDriver directly...
>
DevTools listening on ws://127.0.0.1:50146/devtools/browser/5c09d68c-f3ff-43b2-b645-0b5c098c41d9
Feature: Title of your feature
>
I want to use this template for my feature file
>
Scenario: Title of your scenario
✓ Given Open the browser and Load the URL
✖ When User entered the text in the search box
- And click on search
>
Failures:
>
[00:09:03] I/launcher - 0 instance(s) of WebDriver still running
[00:09:03] I/launcher - chrome #01 failed 1 test(s)
[00:09:03] I/launcher - overall: 1 failed spec(s)
[00:09:03] E/launcher - Process exited with error code 1
>>>
>>> Test failed but keep the grunt process alive.
>
Done.
If you observe the error log "When" step has failed but there is no error stacktrace in the command line to find why it failed.
My expectation is that it should show the error stacktrace for why it has failed.
You need to use await on your browser actions otherwise it performs the actions synchronously.
e.g
await browser.get("https://google.com");

Can't get any response back while calling service through frisbyJS

The code I am using is:
var frisby = require('frisby');
frisby.create('Get paf data')
.get('https://services.....')
.expectStatus(200)
.expectHeaderContains('content-type', 'application/json')
.toss();
The error I get while running it from CLI using
jasmine-node EndpointTest_spec.js
The error I get is:
Error: Expected 500 to equal 200
Error: Header 'content-type' not present in HTTP response
So do I need to first load my website and call services through my application and then run frisby ?
But then it defeats the purpose of just making a quick check for all the endpoints used in application without running it.
You are calling request with https:// which may be secure server so use
{ strictSSL: false} in your get method .get('https://services.....',{ strictSSL: false}). It will solve your problem.
var frisby = require('frisby');
frisby.create('Get paf data')
.get('https://services.....',{ strictSSL: false})
.expectStatus(200)
.expectHeaderContains('content-type', 'application/json')
.toss();

angular-sails websocket url undefined ( ws://www.undefined)

I am using sails 0.10.5 and in angular frontend with angular-sails .
It gives an error like below on server side Whenever an api call by $sails.get
In My FrontEnd side controller code :
io.sails.url = 'http://localhost:1337';
io.socket.get('http://localhost:1337/admin/v1/user/subscribe', function (body, response) {
console.log('Sails responded with: ', body);
console.log('with headers: ', response.headers);
console.log('and with status code: ', response.statusCode);
});
and console is
Sails responded with: Object {}
app.js:167 with headers: Object {}
app.js:168 and with status code: 200
But in backend side sails console gives error like this
debug: --------------------------------------------------------
debug: :: Fri Dec 19 2014 10:44:25 GMT+0530 (India Standard Time)
debug: Environment : development
debug: Port : 1337
debug: --------------------------------------------------------
error: Error:
res.redirect() :: [socket.io] ::
Cannot redirect socket to invalid location :: 'ws://www.undefinedhttp://localhost:1337/admin/v1/user/subscribe'
at Object.Err.invalidRedirect (C:\wamp\www\i-phone\i-phone\node_modules\sails\lib\hooks\sockets\lib\interpreter\interpret.js:33:14)
at ResStream.doRedirect (C:\wamp\www\i-phone\i-phone\node_modules\sails\lib\hooks\sockets\lib\interpreter\interpret.js:310:31)
at C:\wamp\www\i-phone\i-phone\node_modules\sails\lib\hooks\sockets\lib\interpreter\saveSessionAndThen.js:23:7
at C:\wamp\www\i-phone\i-phone\node_modules\sails\lib\hooks\session\index.js:59:17
My route file is like this :
'get /admin/v1/user/subscribe': 'UserController.subscribe',
And in UserController.js :
subscribe: function (req, res) {
console.log('aaaaaaaaaaaaaaaaaaaa')
User.find().exec(function(err,users){
// subscribing this socket to User model classroom
User.subscribe(req.socket);
// subscribing this socket to User model instance room
User.subscribe(req.socket,users);
console.log('subscribe')
})
}
For setting up Socket connection with server:
Include sails.io.js in index.html.
Create a global variable for io.sails.url and you'll need to tell the Sails socket client what URL to connect to:
io.sails.url = 'http://localhost:1337';
Put this anywhere before you start making socket calls; the library is smart enough to wait until its connected before trying to make the calls.
To Check if Socket is connected,
io.socket.get('http://localhost:1337/data', function (body, response) {
console.log('Sails responded with: ', body);
console.log('with headers: ', sailsResponseObject.headers);
console.log('and with status code: ', sailsResponseObject.statusCode);
});
You should be able to see in the console whether or not the socket connected by looking for the "io.socket connected successfully." message.
The above code was about setting up socket connection as you requested.
Regarding your problem, Can you please provide some Code
The controller action you posted is clearly not being run (you would see the aaaaaaaaaaaaaaaaaaaa log in your console). Some other code is running and is calling res.redirect with invalid arguments. My first guess would be that you have a policy configured in config/policies.js that is attached to the UserController.subscribe action.
It was little silly mistake.
In my route.js , I am redirecting non WWW request to WWW request .
And socket request start with ws:// tag , thats why it is being also redirect to www.undefined
It is solved by a small condition
if(!req.isSocket){
// redirect logic
}else{
next();
}

when running protractor with phantomjs browser, only able to run tests once

test code:
describe('mysite', function(){
var init_url = 'http://localhost/mySite/#/home';
beforeEach(function(){
// driver = new webdriver.Builder().
// withCapabilities(webdriver.Capabilities.phantomjs()).build();
})
it('should click on toolbox and do stuff', function(){
browser.get(init_url);
browser.waitForAngular();
browser.getCurrentUrl().then(function(url){
console.log('current_url', url);
expect(init_url).toEqual(init_url);
})
expect(true).toBe(true);
browser.sleep(2000);
})
result 1st time run,
Using the selenium server at http://localhost:9515
data Zoom Pad
class active
mysite
should click on toolbox and do stuff
Finished in 3.94 seconds
1 test, 4 assertions, 0 failures
2nd time run, without any interruption, just up arrow and enter:
Stacktrace:
Error: Error while running testForAngular: Error Message => 'Detected a pag
e unload event; asynchronous script execution does not work across page loads.'
caused by Request => {"headers":{"Accept":"application/json; charset=utf-8","Co
nnection":"keep-alive","Content-Length":"689","Content-Type":"application/json;c
harset=UTF-8","Host":"localhost:9515"},"httpVersion":"1.1","method":"POST","post
":"{\"script\":\"return (function () {\\n var attempts = arguments[0];\\n var
callback = arguments[arguments.length - 1];\\n var check = function(n) {\\n
try {\\n if (window.angular && window.angular.resumeBootstrap) {\\n
callback([true, null]);\\n } else if (n < 1) {\\n if (window.angular
) {\\n callback([false, 'angular never provided resumeBootstrap']);\\n
} else {\\n callback([false, 'retries looking for angular exceed
third time
1) mysite should click on toolbox and do stuff
Message:
Error: ECONNREFUSED connect ECONNREFUSED
Stacktrace:
Error: ECONNREFUSED connect ECONNREFUSED
at ClientRequest.<anonymous> (K:\Users\Congwen\AppData\Roaming\npm\node_modu
les\protractor\node_modules\selenium-webdriver\http\index.js:127:16)
at ClientRequest.EventEmitter.emit (events.js:95:17)
at Socket.socketErrorListener (http.js:1547:9)
at Socket.EventEmitter.emit (events.js:95:17)
at net.js:441:14
and on third time the phantomjs webserver is down, and needs to be reconnected, and afterwards it goes back to result 1:
any clues?
config file used:
exports.config = {
seleniumAddress: 'http://localhost:9515',
specs: [
'./ptor-tests/mysite-test.js'
],
capabilities: {
browserName: 'phantomjs',
version: '',
platform: 'ANY'
},
//baseUrl: 'http://testapp.example.com/index.html',
rootElement: 'body',
allScriptsTimeout: 11000,
onPrepare: function () {},
jasmineNodeOpts: {
onComplete: function () {},
isVerbose: true,
showColors: true,
includeStackTrace: true,
defaultTimeoutInterval: 30000
}
};
also I noticed that sometimes there's no step 2 needed and it will go directly to ECONNECT error, and sometimes it gets stuck in step 2 for a number of tests and eventually will terminate phantomjs server.
This is an issue with Protractor that was resolved in version 0.17 and made better in 0.18.
It's a bug with a long tail, but the TL;DR is that Protractor's .get(url) function actually uses client-side JavaScript to make the location change; this is to ensure it properly bootstraps. An unfortunate side effect of that design is that for some reason, PhantomJS takes a few seconds to navigate over properly.
The bug was resolved by adding a longer timeout to the .get function.
Github Issue: https://github.com/angular/protractor/issues/85
Relevant changelog entries:
v0.18
(10aec0f) fix(pageload): increase wait timeout
The 300 ms wait caused problems when testing IE on Sauce Labs. It seems way too short. "browser.get()" invariably timed out. Increasing it solved our problem.
v0.17
(a0bd84b) fix(pageload): add a wait during protractor.get() to solve unload issues
Some systems would not wait for the browser unload event to finish before beginning the asynchronous script execution.
Closes #406. Closes #85.
I've run your test locally (with a different page, but otherwise the same code):
Happy testing!

Resources