Keep cookies between tests nightwatch selenium - selenium

I need to keep some cookies from test to test, I'm using Nightwatch and Selenium, I don't know how to get them for the current session o where to store them.
I've tried to create and set an account, but that doesn't seem to work either
"selenium" : {
"start_process" : false,
"server_path" : "",
"log_path" : "",
"host" : "127.0.0.1",
"port" : 4444,
"cli_args" : {
"webdriver.chrome.driver" : "",
"webdriver.ie.driver" : "",
"webdriver.firefox.profile" : "webdriver"
}
},
Any help is apreciated. Thanks

As of v0.9.14, setCookie does not persist cookies between tests. It looks like the client is created anew for each test.
What I've done is create a custom command that sets and caches the cookie value. This works well for maintaining* authentication state between tests since the custom commands are singletons. The actual authentication only happens once, then subsequent calls use setCookie with the cached session value.
Keep in mind that setCookie won't work until the client has navigated to the relevant domain.

How can we set cookies in Nightwatch. I was tried in Supertest it's works.
How to do in nightwatch.
Below is the code to work with superTest
var args = {
data: {
email: "xxxx",
password: "xxxx"
},
headers: {
"Content-Type": "application/json"
}
};
service.post("localhost", args, function(data, response) {
global.Cookies = response.headers['set-cookie'].pop().split(';')[0]
this.meServiceUrl = superTest.agent("localhost/users").get('');
// Set cookie to get saved user session
this.meServiceUrl.cookies = Cookies;
this.meServiceUrl.set('Accept', 'application/json')
.expect('Content-Type', /json/)
.expect(200)
.end(function(err, res) {
usersApiResponse = res.body
usersServiceResponse.push(usersApiResponse)
console.log(usersServiceResponse)
console.log(usersApiResponse.result.length)
});
});

Related

cypress request PATCH call for local stub server fails

I have a local stub server which has a PATCH request. When I call this local endpoint inside cypress, it fails.
My cypress code
Cypress.Commands.add('callLocalAPI', (id: string = '1') => {
const options = {
method: 'PATCH',
url: `${Cypress.env().baseUrl}test/api`,
// failOnStatusCode: false,
retryOnStatusCodeFailure: true,
log: true,
body: {
id,
},
}
// we need cy to visit the current URL so it grabs cookie
// for our request
cy.visit('/')
cy.request(options).then((response) => {
if (!String(response.body.id)) {
console.error(response)
throw Error(`Fail to get response with ${id}`)
}
})
})
then calling this custom cypress command
cy.callLocalAPI('2')
When I access this endpoint using postman (http://localhost:8882/test/api), I get the expected response with a status code of 200 so there is no issues with the mock server.
But when I run the cypress tests, I always get a 404.
Status: 404 - Not Found
Headers: {
"server": "stubby/5.0.0 node/v12.19.0 (darwin x64)",
"date": "Fri, 03 Sep 2021 03:36:49 GMT",
"connection": "keep-alive",
"keep-alive": "timeout=5",
"transfer-encoding": "chunked"
}
Try
const options = {
method: 'PATCH',
url: 'test/api',
...
From Cypress docs - request
If you make a cy.request() after visiting a page, Cypress assumes the url used for the cy.visit() is the host.
cy.visit('http://localhost:8080/app')
cy.request('users/1.json') // url is http://localhost:8080/users/1.json
It may simply be that this line is missing a path separator
url: `${Cypress.env().baseUrl}test/api`
Cypress.env().baseUrl
Note that the value for this string is
taken from the file cypress.env.json (not cypress.json)
{
"baseUrl": "http://localhost:8882/"
}
or overridden in the command line
cypress open --env baseUrl=http://localhost:8882/

Strapi / Nuxt - Can't find custom route

I've used this to setup auth in strapi and nuxt:
Auth with Strapi and Nuxt
I'm currently trying to retrieve the items specific to a authenticated user (already checked out this strapi - restrict user to fetch only data related to him). To do this I created a custom route in Strapi (/api/routine/config/routes.json):
{
"method": "GET",
"path": "/routines/me",
"handler": "Routine.me",
"config": {
"policies": []
}
}
and a custom controller (/api/controllers/Routine.js):
module.exports = {
me: async (ctx) => {
const user = ctx.state.user;
if (!user) {
return ctx.badRequest(null, [{ messages: [{ id: 'No authorization header was found' }] }]);
}
const data = await strapi.services.routine.find({user:user.id});
if(!data){
return ctx.notFound();
}
ctx.send(data);
},
};
I already gave permission through Strapi admin for authenticated users to access 'me'. When I hit the endpoint from Nuxt:
const routines = await axios.get(http://localhost:1337/routines/me)
I get this error:
GET http://localhost:1337/routines/me 404 (Not Found)
Why is the custom route not found? Am I using the wrong endpoint?
Maybe you have already solved it, but it seems like you forget to send the authentication header with the request.
const routines = await axios.get(
'http://localhost:1337/routines/me', {
headers: {
Authorization:
this.$auth.getToken('local'),
},
}
It was a fault in my Strapi routes config. Answer was provided through the amazingly helpful Strapi forums:
403 forbidden when calling custom controller from Nuxt
Here is the problem:
{
"method": "GET",
"path": "/routines/:id",
"handler": "routine.findOne",
"config": {
"policies": []
}
},
{
"method": "GET",
"path": "/routines/me",
"handler": "routine.me",
"config": {
"policies": []
}
So basically you are hitting the first route right now and it assumes that
me is actually an :id. Koa is making the verifications with regex so in this case it takes the first matched route. Move the route with /me above that one with /:id

Website login automation without XHR request

Background: I'm trying to automate local ISP login using simple request in python (without selenium, that's last resort as I'm trying to learn other ways too).
Upon inspecting website, submit button calls the validateForm() function.
function validateForm(){
var input=true;
var uname = "?"+document.login.Username.value+"+/#";
var pwd = "?"+document.login.Password.value+"+/#";
document.login.LoginName.value=encodeURIComponent(uname);
document.login.LoginPassword.value=encodeURIComponent(pwd);
if (input==true&&document.login.checker.checked)
toMem(this);
}
function toMem(a) {
newCookie('theName', document.login.Username.value); // add a new cookie as shown at left for every
newCookie('theEmail', document.login.Password.value); // field you wish to have the script remember
}
function newCookie(Username,value,days) {
var days = 30; // the number at the left reflects the number of days for the cookie to last
// modify it according to your needs
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString(); }
else var expires = "";
document.cookie = Username+"="+value+expires+"; path=/";
}
No where it is sending any request.
The website doesn't make any XHR request. I'm not able to grasp how they are making the login work. I found one request from 'other' tab of network (chrome dev tools). From where it is generating this request!!!
fetch("http://ip:port/Sristi3/SRISTI/loginUI.do2", {
"headers": {
"accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
"accept-language": "en-US,en;q=0.9,bn;q=0.8",
"cache-control": "no-cache",
"content-type": "application/x-www-form-urlencoded",
"pragma": "no-cache",
"upgrade-insecure-requests": "1"
},
"referrer": "http://ip:port/Sristi3/SRISTI/Login.jsp?",
"referrerPolicy": "no-referrer-when-downgrade",
"body": "Username=username&Password=password&LoginName=encodedusername&LoginPassword=encodedpass",
"method": "POST",
"mode": "cors",
"credentials": "include"
});
I tried to simply paste the request in console but this also does not make the login. Returned a promise with [[PromiseStatus]]: "rejected" and [[PromiseValue]]: TypeError: Failed to fetch, message: "Failed to fetch", stack: "TypeError: Failed to fetch". What and where to look for? Any help?

Unable to authenticate a user using #hapi/cookie 19.x.x

I've recently upgraded my project to use hapi 19.x.x along with that I have updated the project to use #hapi/cookie as opposed to the deprecated hap-auth-cookie however after successful authentication my application constantly tries to reauthenticate even after setting a session cookie with request.cookieAuth.set({ id : id})
When the application is redirected to the 'restricted page' using the redirectTo: property on the .auth.strategy('admin', 'cookie', {}) object.
I noticed that the state on the incoming request is {} empty when it shouldn't be
node -v // 12.16.2
Google Chrome
Version 80.0.3987.163 (Official Build) (64-bit)
package.json {
"dependencies": {
"#hapi/catbox-redis": "5.0.5",
"#hapi/cookie": "11.0.1",
"#hapi/h2o2": "9.0.1",
"#hapi/hapi": "19.1.1",
"#hapi/inert": "6.0.1",
"#hapi/joi": "17.1.1",
"#hapi/scooter": "6.0.0",
"#hapi/wreck": "17.0.0",
}
server.auth.strategy('admin', 'cookie', {
cookie: {
name: Server.cookieName,
password: auth_cookie_password,
isSecure: false,
ttl: Server.cacheCookieTtlMs
},
appendNext: true,
redirectTo: outboundUrl,
validateFunc: async (request: any, session: any) => {
// blah blah
}
{
method: ['GET', 'POST'],
path: '/login',
options: {
auth: false,
security: true
},
handler: async (request: any, h) => {
try {
const tokenSet = await authCallback();
const session = {
id: tokenSet.id,
}
request.cookieAuth.set(session);
const returnScript = `<script type="application/javascript" >(function() { setTimeout(function() {window.location = "http://localhost:3000"})})()</script>`;
return h.response(returnScript)
} catch (e) {
return h.response('Internal server error').code(500)
}
}
}
any help would be appreciated.
you have to set the cookie path to /
Cookies are only sent to the server when the URL of the request starts with the value of the cookie’s path. When you omit path, the default is the URL of the request that received the response with the Set-Cookie header. So, let’s say you omit path and your cookie is set on a URL like https://example.com/login (which is very common), then the cookie will only be sent on requests for subpaths like https://example.com/login/foo, which is almost never what you want.

405 error with JIRA REST API using node js

I am trying to create an automated JIRA ticket using the REST API but I keep getting a 405 error.
I am using the examples here: https://developer.atlassian.com/server/jira/platform/jira-rest-api-examples/
Also, when I visit the post URL directly I do not get any errors so I doubt it is a server issue. Any ideas?
var Client = require('node-rest-client').Client;
client = new Client();
// Provide user credentials, which will be used to log in to Jira.
var loginArgs = {
data: {
"username": "user",
"password": "pass"
},
headers: {
"Content-Type": "application/json"
}
};
client.post("https://jira.mydomain.com/rest/auth/1/session", loginArgs, function(data, response) {
if (response.statusCode == 200) {
//console.log('succesfully logged in, session:', data.session);
var session = data.session;
// Get the session information and store it in a cookie in the header
var args = {
headers: {
// Set the cookie from the session information
cookie: session.name + '=' + session.value,
"Content-Type": "application/json"
},
data: {
// I copied this from the tutorial
"fields": {
"project": {
"key": "REQ"
},
"summary": "REST ye merry gentlemen.",
"description": "Creating of an issue using project keys and issue type names using the REST API",
"issuetype": {
"name": "Request"
}
}
}
};
// Make the request return the search results, passing the header information including the cookie.
client.post("https://jira.mydomain.com/rest/api/2/issue/createmeta", args, function(searchResult, response) {
console.log('status code:', response.statusCode);
console.log('search result:', searchResult);
});
} else {
throw "Login failed :(";
}
});
I am expecting the Jira ticket of type REQ to be created with the details I added in the fields section.
I believe you are using the incorrect REST API; what you're currently doing is doing a POST to Get create issue meta which requires a GET method, hence, you're getting a 405. If you want to create an issue, kindly use Create issue (POST /rest/api/2/issue) instead.