API mocking in cypress intercept - api

I am new to cypress.
Problem: I am not able to intercept url for API mocking, when there are multiple APIs are appearing in console-> network tab
Description: My requirement is as follows:
login a website, after getting the landing page,go to a particular webpage, select multiple test cases check boxes
open console-> network tab , and click run
watch multiple APIs are coming
I selected one API url among them. I want to mock this particular one.
'GET'method , url (say: https://externalAPIurl) are copied in the following code
//verify landing page is reached
cy.contains("this is landing page").should("exist");
//after login open testcase page
cy.visit(
"https://example.com/testcases"
);
//go to test suite tab test suite
cy.get("#testsuiteid")
.click();
//click test suite name
cy.contains("testsuitename").click();
// select all test cases
cy.get(".testcasecheckbox")
.click();
cy.intercept(
{
method: "GET",
url: "https://externalAPIurl",
},
{
headers: {
authorization:
"AABBXXYY",
},
},
{
statusCode: 200,
body: [
{
status: 200,
result: true,
combination: [
//same data...
],
},
],
}
);
cy.get("#run_button").click();
});
Where am I wrong?
I checked in postman, the URL, with Get method and Header-> Authorization key with proper Authorization key value (as collected from network console Headers) giving correct response, but the cy.intercept is throwing error
How to solve this?
Whenever in a website we click a button, multiple external API s are visible in console-> network. If I take any one of them -> check the URL, method, header and getting the same response in postman as in the network console, I should be able to mock the same request URL.
I tried the same when one single API is appearing in network console. It was fine. But when I select one among multiple the result is an error.
Please note: I have included the header authorization, may be the format is wrong. But if I give or do not give the authorization, the result is the same error.

If you want to intercept a 'GET' and stub the response with predefined data. I would first use dev tools network tab to capture the api response you want. Copy the response and save as a json file in your fixture folder (you can edit this file as you see fit to fake the data how you wish). From there you can do the following:
cy.fixture('apiResponse.json').as('fixture data')
.then( (data) =>{
const raw = JSON.stringify(data)
cy.request( {
method : 'GET',
url : 'api url here',
headers : {
authorization : 'AABBXXYY',
},
body : raw
})
.then( (response) => {
cy.log(response.body)
expect(`Response.status = ${response.status}`).to.eq('Response.status = 200')
})
})

Related

No Host in request URL for Grafana datasource plugin tutorial - Add authentication

I'm trying to follow the example for developing a datasource plugin from Grafana. Ultimately I want my plugin to use Oauth, but even with just the basic Grafana datasource proxy example I seem to be having issues.
I have updated my plugin.json, class and constructor.
I have setup this hard coded example.
in plugin.json
{
"path": "grafana",
"url": "https://github.com"
}
],
And a sample testDataSource()
async testDatasource() {
return getBackendSrv()
.datasourceRequest({
url: this.url + '/grafana/grafana',
method: 'GET',
})
.then(response => {
if (response.status === 200) {
return { status: 'success', message: 'Data source is working', title: 'Success' };
} else {
return { status: 'failure', message: 'Data source is not working: ' + response.status, title: 'Failure' };
}
});
}
When I try and save/test this datasource to call that method, I get in the frontend a
HTTP Error Bad Gateway
And in the logs
t=2021-09-17T14:31:22+0000 lvl=eror msg="Data proxy error" logger=data-proxy-log userId=1 orgId=1 uname=admin path=/api/datasources/proxy/9/grafana/grafana remote_addr=172.17.0.1 referer=http://localhost:3000/datasources/edit/9/ error="http: proxy error: http: no Host in request URL"
I would've expected the request to be routed to the datasource proxy and for that to make the request to github but it seems Grafana is making a request to /api/datasources/proxy/9/grafana/grafana and nothing is picking it up?
Looking up my datasource via API, there's nothing listed for URL.
You will need to render this in your ConfigEditor.tsx
<DataSourceHttpSettings
defaultUrl="http://localhost:8080"
dataSourceConfig={options}
onChange={onOptionsChange}
/>
Which will give you the basic form with URL, whitelist, auth options that you see on most plugins. The URL there I guess should match what you have in your routes.

Why does the browser ask me to log in with ASP.NET Core 3.1

I've created a website in ASP.NET Core 3.1, MVC, with API. There are 2 parts to the website. An classic static website (with a home, about, contact page etc) and a SPA app. You need to login to use the SPA application.
I believe my approach to auth is quite 'standard'. (There are no different permissions or roles).
The user logs in, and an HTTP Only cookie is created. They are redirected to the Web API part of the website
Any API calls to the C# Web Api, and the front end reviews the return status code (such as code 200 or 500 etc).
If the return is 401, it will assume the JWT has expired or has never been created. The front end then makes another call to the Web Api to retrieve a new Json Web Token. If the JWT is returned, the program attempts the original request again, with the valid JWT. Otherwise, it deals with the situation by alerting the user about the issue
The ajax code looks like
function toDatabase(type, url, data, successDelegate, failDelegate, errorDelegate, tryAgainIfUnathorized) {
$.ajax({
type: type.toUpperCase(),
url: url,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + bearerToken.get()
},
data: data,
dataType: "json",
success: function (response) {
successDelegate(response);
},
error: function (e) {
if (e.status === 401 && tryAgainIfUnathorized) {
const callback = function () {
toDatabase(type, url, data, successDelegate, failDelegate, errorDelegate, false, false);
};
bearerToken.refresh(callback);//try to get the updated token, then retry the original request
}
else {
if (e.status !== 200)
errorDelegate(e.statusText);
console.log("Error in ajaxCall.js. Expand for call stack:");
console.log(e);
}
}
});
This works fine on my local computer.
The problem is, seemingly randomly and not that often, on my production site, Google Chrome occasionally presents a log in dialog. My code does not create this dialog. I don't even know the javascript to create it :)
I don't understand. If I click cancel, then I can continue as I'd like (meaning I am authenticated).
I read up, and it seems that this happens because the browser detects the 401 and tries to be helpful!
I've tried to get round this issue by returning a 499 instead of a 401 but that caused even more headaches with this code
jwtBearerOptions.Events = new JwtBearerEvents
{
OnAuthenticationFailed = context =>
{
context.Response.OnStarting(() =>
{
context.Response.StatusCode = 499;
return Task.CompletedTask;
});
return Task.CompletedTask;
}
};
How do I prevent this dialog from showing (or is my approach to using JWT incorrect)

How to send an additional request to endpoint after each test case

I’m currently looking at Botium Box, and I’m wondering if it is possible to send an additional request to our endpoint after each test case? Let me give you some background information about how we set up the HTTP(S)/JSON connector in Botium Box and how we are sending information to our bot:
HTTP(S) endpoint:
https://MyChatBotsEndpoint.com/?userinput={{msg.messageText}}
HTTP method: POST
We also send cookies through the header template in the request builder. Like this:
{
"Cookie": "JSESSIONID={{context.sessionId}}"
}
The response is given back in JSON.
When a test ends (when it is successful but also when it fails), we need to send an additional request to our endpoint. The endpoint URL of that request should look like this:
https://MyChatBotsEndpoint.com/endsession
The header should include the cookie as described before.
Is there a way to achieve this in Botium?
Botium has many extension points to plug in your custom functionality. In this case, I guess the SIMPLEREST_STOP_HOOK is the best choice.
Write a small javascript file calling your endpoint, and register is with the SIMPLEREST_STOP_HOOK capability in botium.json. The context (session context from the HTTP/JSON connector) is part of the hook arguments.
in botium.json:
...
"SIMPLEREST_STOP_HOOK": "my-stop-hook.js"
...
my-stop-hook.js:
const request = require('request')
module.exports = ({ context }) => {
return new Promise((resolve, reject) => {
request({
method: 'GET',
uri: 'https://MyChatBotsEndpoint.com/endsession',
headers: {
Cookie: "JSESSIONID=" + context.sessionId
}
}, (err) => {
if (err) reject(err)
else resolve()
})
})
}

Requesting parameters are not sent over API in ionic 2

I am trying to send the the parameters using a post request but the parameters are not reaching to provide back the desired result and printing null as a result in console. here is my code
var headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded' );
let options = new RequestOptions({ headers: headers });
let postParams = {
acesscode: 'XXXXXXXXXXX',
productCode:'XXXXXXXXXX'
};
this.http.post("http://www.ebiebook.com/drmapi/v1/details", JSON.stringify(postParams), options)
.subscribe(data => {
console.log(data['_body']);
}, error => {
console.log(error);// Error getting the data
});
}
and the output screen is attached, It shows API is hitting well but the parameters data is unable to reach to provide the corresponding result. Please suggest.
This print you have attached does not show what is being sent by the request, instead it shows only the response your browser received from the server.
You better take a look at this thread here to see in this thread more about. You have to check the 'Headers' tab from Chrome's console -> Network.

Using the Rally API to pull user profile

I am trying to use the Rally web service API to get some data. Code as blow. On IE it will pop out a login window, after entry login name and password, I am about to get some data. But when I use chrome, it response 401, not sure what I missing. I know there is SDK available, but due to some limitation, not able to use it. Any suggestions please?
var url = https://rally1.rallydev.com/slm/webservice/v2.0/users;
$.ajax({
url: url,
type: 'GET',
heards: { zsessionid: apiKey },
success: function(json) {
console.log(JSON.stringify(json));
}
},
error: function( req, status, err ) { console.log( 'something went wrong', status, err );
}
});
I'd love to know more about why you can't use the SDK. Anyway, in this case your config likely needs headers instead of heards to pass the api key.