Cypress 11 Login beforeEach Via Post Issue - command

I have a login script written in the command file that I use as a beforeEach in each test spec file. This worked in Cypress 9, but I recently upgraded to Cypress 11 and now the session doesn't carry over into the test.
The command runs successfully, but when it goes to the test I'm not signed in, so it fails.
Cypress.Commands.add("login", () => {
cy.request({
method: 'POST',
url: '/Account/Login', // baseUrl is prepended to url
form: true, // indicates the body should be form urlencoded and sets Content-Type: application/x-www-form-urlencoded headers
body: {
UserName: Cypress.env('username'),
Password: Cypress.env('password'),
RememberMe: false,
FranchiseSelected: 1,
}
})
})
Screenshot:
Does anyone know what I'm missing to update this to work in Cypress 11?
I have made a login command that actually goes to the page and logs in, and that works, but I would really like for this POST command to work.

I'm not sure of the cause, but try wrapping the request in cy.session()
Cypress.Commands.add("login", () => {
cy.session('login', () => {
cy.request({...})
})
})
The session command acts like a cache for the session token. When you call the login command in beforeEach(), the first time calls the request but subsequent times just restore the token from cache.

Related

Apps Script Execution API 404 error with devMode: true

When requesting POST https://script.googleapis.com/v1/scripts/{script_id}:run with devMode: true I get a 404 error. I can run the script successfully with devMode: false.
Although other people (1, 2) have raised this issue, none of the other solutions work. I keep getting an HTTP 404 Not Found error whenever my request comes with devMode: true.
I have performed the following steps:
created a new Google account
created a Cloud project
set up an OAuth consent screen for the project
authorized the domain for the app (just in case)
created 'Desktop' OAuth2 credentials for this project with OAuth scopes listed below
enables Apps Script API on the project
created a standalone Apps Script using Google Drive ("Test 1")
set the Cloud Platform project ID for the script Test 1
deploy the script Test 1 as an API executable, with access to "Anyone"
obtain a valid access token with the exact same scopes listed below and used for the OAuth consent screen configuration in the Cloud project. The token is for the same account that owns the script and the cloud project.
After performing the above steps, running with devMode: false was successful, but when switching to devMode: true it failed.
The same happens when I set access to "Only Me".
To make clear the steps that I took, I provide a full flow of screenshots taken along the way (open image in new window to zoom in; the flows to top-to-bottom; the three columns from left to right are: Cloud console project flow; Apps Script flow; OAuth2 flow):
At the request of #ziganotschka I made a simpler copy of my Apps Script function:
function test() {
return 1;
}
And the appsscript.json manifest is:
{
"timeZone": "Asia/Jerusalem",
"dependencies": {
},
"exceptionLogging": "STACKDRIVER",
"runtimeVersion": "V8"
}
The code for obtaining the OAuth2 token and running the script, in Python:
##
# %%
import requests
import urllib
import json
client_id = '...'
client_secret = '...'
script_id = '...'
is_dev_mode = True # True or False
##
# %% Initiate OAuth2
url = 'https://accounts.google.com/o/oauth2/auth?' + urllib.parse.urlencode({
'client_id': client_id,
'redirect_uri': 'urn:ietf:wg:oauth:2.0:oob',
'response_type': 'code',
'scope': ' '.join([
'https://www.googleapis.com/auth/userinfo.email',
'https://www.googleapis.com/auth/userinfo.profile',
'openid',
'https://www.googleapis.com/auth/documents',
'https://www.googleapis.com/auth/drive',
'https://www.googleapis.com/auth/drive.scripts',
'https://www.googleapis.com/auth/script.external_request',
'https://www.googleapis.com/auth/script.projects',
'https://www.googleapis.com/auth/script.scriptapp',
'https://www.googleapis.com/auth/script.container.ui'
])
}, doseq=True)
print(url)
##
# %% Exchange authorization code with access and refresh tokens
print('Enter authorization token: ', end='')
authorization_code = input()
authorization_token_response = requests.post('https://accounts.google.com/o/oauth2/token', data={
'code': authorization_code,
'client_id': client_id,
'client_secret': client_secret,
'redirect_uri': 'urn:ietf:wg:oauth:2.0:oob',
'grant_type': 'authorization_code'
})
authorization_token_response.raise_for_status()
authorization_data = authorization_token_response.json()
access_token = authorization_data["access_token"]
refresh_token = authorization_data["refresh_token"]
##
# %%
response = requests.post(f'https://script.googleapis.com/v1/scripts/{script_id}:run',
data=json.dumps({
"function": "test",
"parameters": [],
"devMode": is_dev_mode
}),
headers={
'content-type': 'application/json',
'authorization': f'Bearer {access_token}'
}
)
response.raise_for_status()
print(response.content)
I get similar results for a curl call:
$ curl 'https://script.googleapis.com/v1/scripts/x...x:run' -X POST -H 'content-type: application/json' -d '{"function":"test","parameters":[],"devMode":true}' -H 'authorization: Bearer x...x' --silent
{
"error": {
"code": 404,
"message": "Requested entity was not found.",
"status": "NOT_FOUND"
}
}
I consider this as an issue report, as Google mention that they use Stack Overflow to field technical questions for Apps Script API. As well as a beacon to anyone who has been frustrated with this issue.
Any my question would be -- am doing anything wrong?
As an aside question: what's the difference between substituting script_id for the Current API ID (as suggested in 'How to Execute a function guide'; this identifier seems to be identical to the script Project key under File > Project properties) and the Script's Drive file ID (suggested everywhere else; this seems to be identical to Script ID)?

' ReferenceError: browser is not defined ' while running cucumber-js in protractor-cucumber

I am using protractor 5.2.2. and cucumber 3.2.0.I am getting an error "browser is not defined" when i am run cucumber-js.
Feature: Login page test
Scenario: Verify whether the user is able to navigating to the login page
When I go to "https://in.linkedin.com/"
and my step code is
var {defineSupportCode} = require('cucumber');
defineSupportCode(function ({ setDefaultTimeout, Given, When, Then }) {
setDefaultTimeout(60 * 1000);
When(/^I go to "(.*)"$/, function (url, callback) {
browser.get(url).then(callback);
});
)};
It looks like cucumber is not catching the global browser variable.
To run protractor script, you need to use command like protractor conf.js no matter which test framework(jasmine, cucumber) you used.
When use cmd protractor to start running, it will load browser into Nodejs runtime's global variable.
After protractor complete load browser into global, the package protractor-cucumber-framework will generate and execute another command line which will use cucumber-js to run cucumber feature files, but now in the Nodejs runtime, global variable has browser this property and its value is not null/undefined.
That's why we have to need more two packages: cucumber and protractor-cucumber-framework

Office.JS “This add-in is no longer available” error when creating a Word Document with context.application.createDocument()

I'm developing an add-in for Microsoft Word 2016 using office js version 16.0.8626.1000. I use a web service to retrieve a document in base64 format and then I create a new Word instance with that.
The problem is that whenever I run the add-in from my server (not from visual studio debugger) it opens the document but the add-in frame displays an error
First Instance:
Second Instance:
This doesn't happen if I run the add-in from visual studio debugger, it opens the new instance without the frame.
This is my code
Office.initialize = function (reason) {
// Checks for the DOM to load using the jQuery ready function.
$(document).ready(function () {
$('#get').click(function () {
openWord();
});
});
}
This how I retrieve the document (without real url):
function openWord() {
getDocumentAsBase64(function (data) {
Word.run(function (context) {
var myNewDoc = context.application.createDocument(data);
context.load(myNewDoc);
return context.sync()
.then(function () {
myNewDoc.open();
context.sync();
})
.catch(function (myError) {
//otherwise we handle the exception here!
updateStatus(myError.message);
})
}).catch(function (myError) {
updateStatus(myError.message);
});
});
}
function getDocumentAsBase64(callback) {
$.ajax({
url: 'http://myurltomydocument.com/getFile',
data: "{}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (response) {
callback(response.d);
},
error: function (response) {
updateStatus(response.d);
}
});
}
EDIT -- 8/12/2017
This is the manifest that I'm currently using if anyone wants to replicate the problem with Office 2016
I don't read Spanish, but the error mentions Visual Studio. I think Office is still trying to run a version that was sideloaded with Visual Studio and it's telling you that it can't do that. The problem might be the manifest. I notice that it still has the string ~remoteAppUrl in many places. When you are debugging with VS, this string is automatically replaced with the localhost URL, but you need to manually change all these to your web service's domain and sideload the new manifest when you are going to run it from the web service.
EDIT 12/11/17:
If that doesn't fix it, try clearing the Office cache. Details are at: Clear the Office cache
Edit 12/19/17:
Try this:
Go on File->Info->Check for Issues -> Inspect Document -> Inspect.
Then on Task Pane Add-ins click Remove All
Finally I found the solution to this problem.
First I downloaded Office 2016 Administrative Template Files.
When you run it, it will extract a bunch of files and folders.
Enter admx folder and copy the whole content to C:\Windows\PolicyDefinitions.
Do a gpupdate /force under CMD (or Powershell) as an administrator.
Run gpedit.msc and find the Administrative Template for Office 2016 then Updates (PC configuration >> Administrative Template >> Microsoft Office 2016 >> Updates >> Update Channel) and set the Update Channel to Montly Channel.
I'm on Version 1711 (compilation 8730.2127 click and run) and everything is working good now.
EDIT 9/1/2018:
The error started showing up again. The only thing I did was attaching the runtime logging to debug my add-in manifest. This is still unsolved.

Retrieve custom variable from a successful jenkins job run via REST api call

I would like to retrieve a custom variable from a successful last stable build jenkins job. I was able to retrieve the build number using curl on this link using Execute Shell. It's an internal server. https://jenkinsci.internalsvr/view/webapps/job/common-tools/lastStableBuild/buildNumber
Now, I'd like to do the same for a custom variable using curl. But I know that I may need to save the value of the custom variable but not sure how and to where.
So this is how I got it to work
I have this code in our dsl.groovy file
....
parameters {
stringParam('CUSTOM_VAR1', '', 'Custom Variable')
stringParam('CUSTOM_VAR2', '', 'Custom Variable')
}
shellCommands = sprintf('''#/bin/bash
echo "CUSTOM_VAR1=\${%s}" > env.properties
echo "CUSTOM_VAR2=\${%s}" >> env.properties
''', ['CUSTOM_VARIABLE1','CUSTOM_VARIABLE1'])
shell(shellCommands)
// This is extremely important
environmentVariables {
propertiesFile('env.properties')
}
// This allowed me to retrieve env.properties via http call from browser or curl.
publishers {
archiveArtifacts {
pattern('env.properties')
}
}
So if I need to access it, the http url should be formed like this
curl https://our-internal-server/job/theNameOfTheJob/lastStableBuild/artifact/env.properties
You can do it with the API of the EnvInject plugin, either with:
curl <jenkins-host>/job/<job_name>/<buildNumber>/injectedEnvVars/export
curl <jenkins-host>/job/<job_name>/<buildNumber>/injectedEnvVars/api/python
More info here.

Python Screen Scraper works within Eclipse, but not from command line

I'm writing a simple screen scraping script using python 2.7 with Eclipse PyDev. When running or debugging from within Eclipse everything works fine. However, when I run my program from the command line the server always returns a Response 500 error code. I've tried running the script and the compiled versions from the command line but get the same result -- Response 500. I've also tried some arbitrary things like adding a delay, repeated attempts, etc. but I do not know what Eclipse is doing that is different than python ran the command line.
First, where's a good place to start digging if I encounter something like this again?
Second, any ideas on how to get this working from the command line?
Code snippet below for reference
from requests import Request, Session
content_type = 'application/x-www-form-urlencoded'
headers2 = {"User-Agent" : 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)',
"Content-Type" : content_type,
"Referer" : url
}
url = loginPage
payload = {"email" : username, "password" : password}
req = Request ('POST', url, data=payload, headers=headers2)
prepped = req.prepare()
s = Session()
resp = s.send(prepped)
print resp # Response 200 (good) from both within Eclipse and from cmd
resp = s.get(targetPage)
print resp # Response 200 (good) from Eclipse, Response 500 (generic web error) from cmd
s.get (logOutPage)
s.close()
Got an answer from somebody. Thanks go to user Justinsaccount from reddit.
First, I was using batch files to save typing and not directly using the command line.
Secondly, when printing out the parameters from inside the program and then comparing the eclipse version versus the .bat version, the .bat version was short a few characters which was the give away.
One of the parameters was a url that had a space character: http://somewhere.com/some page.
In strict URL, this turns into: http://somewhere.com/some%20page
When run from the command line http://somewhere.com/some%20page
works just fine. However, in a batch file the % needed to be escaped so what I got was: http://somewhere.com/some0page
which is why the server through an error -- that page didn't exist. What I needed to do was escape the % character: http://somewhere.com/some%%20page. After that change things worked just fine.