I had a requirement in Cypress. Where in, I want to change dns of request and fire the request and want to restore the previous dns servers. I see there is "dns" library in Javascript used for this. But am not able to integrate the same in cypress. I included var dns = require("dns") in plugins/index.file. But still am not able to use the Dns library in Cypress. Do anyone have any idea on this?
Code plugins/index.js:
module.exports = (on, config) => {
var dns = require('dns')
on('before:browser:launch', (browser, launchOptions) => {
})
}
test.spec.js:
//const dns = require('dns') [Tested this as the declaration in index file dint work]
describe('', () => {
it('test1', () => {
let origdns = dns.get();
dns.setServers(['dns-ip1', 'dns-ip2', 'dns-ip3'])
cy.request({
method: 'GET',
url: 'https://www.google.com/'
})
dns.setServers(origdns);
When I used this my Cypress thrown error as dns is not defined/dns.get()/dns.getServers() is not a method.
Related
Description:
In graphql gateway i would like to know the services available in docker so that i can stitch the schema from other graphql services. All the applications are running in a docker. docker compose file is used to start all the applications.
Docker engine does provide a REST api to list all the services.
Inside docker compose we should also mount volume
volume
- /var/run/docker.sock:/var/run/docker.sock
Problem:
I used npm library http and i was able to get the result
const result = http.request(
{
socketPath: "/var/run/docker.sock",
path: "/containers/json",
},
(response) => {
res.setEncoding("utf8");
res.on("data", (data) => console.log(data));
res.on("error", (data) => console.error(data));
}
);
result.end();
I am not able to get all the docker services using axios. I also find that even-though axios has socketPath attribute it do not have a path attribute along with it.
I used the following code will using axios:
const axiosResult = await axios({
socketPath: "/var/run/docker.sock",
url: "/containers/json",
method: "GET",
});
I tried most using a different url: http://unix:/var/run/docker.sock/v1.30/containers/json
When using Axios the code has to modified as such to get the result
const { data } = await axios.get("http://unix:/containers/json", {
socketPath: "/var/run/docker.sock",
});
console.log(data);
New to Typescript and still getting used to Microsoft Azure so please excuse the basic question.
I have created an Enterprise Application which should be able to log into the Graph API and read a user profile. I have the client id/secret , tenant id but I need to know how to initialise this client within TypeScript.
Am i supposed to initialise a GraphClient or is there a a generic Client I can use?
A link to a tutorial/example or documentation on how to do this would be amazing.
For context I want to be able to write one function to initialise the client and subsequently write the query- all the docs talk about multiple files which I cannot utilise because I am writing this as a third party integration.
I have found this but it seems very complex and I can't really follow it.
Is there a typescript equivalent of
client_credential = ClientSecretCredential(tenant_id, client_id, client_secret)
client = GraphClient(credential=self.client_credential,
scopes=['https://graph.microsoft.com/.default']
)
This is the way I've managed to do it. I'm bounded by using an extremely old version of the microsoft graph module unfortunately.
const qs = require('qs');
const MicrosoftGraphClient = require('#microsoft/microsoft-graph-client#1.0.0');
const axios = require('axios#0.27.2');
const getToken = async () => {
try{
const response = await axios.post(
`https://login.microsoftonline.com/${tenantId}/oauth2/v2.0/token`,
qs.stringify(
{
client_id : clientId,
client_secret: clientSecret,
scope: 'https://graph.microsoft.com/.default',
grant_type: 'client_credentials'
}
))
let tokenSet = response.data;
return tokenSet.access_token;
} catch (error){
console.log(error)
};
}
var client = MicrosoftGraphClient.Client.init({
authProvider: async (done) => {
const token = await getToken()
done(null, token);
}
});
I'm not sure how to log / see the actual request that is being made.
I can look at this code below and assume that it's http://myendpoint.com?my/path?param=value, however with more complex code and variables in other places, how can I tell what exactly is getting called via API.get?
The main reason I ask is because I don't think my query parameters are being appended to my request, and I'm hoping to confirm.
const apiName = 'http://myendpoint.com'
const path = '/my/path'
const myInit = {
queryStringParameters: {
param: 'value'
}
}
API.get(apiName, path, myInit)
.then((response) => {
console.log('> > > PLEASE TELL ME HOW TO LOG THE REQUEST < < <')
resolve(response)
},
(err) => {
console.log('err resp', err)
resolve(err)
})
Edit: FYI this is in a REACT NATIVE project, so things like the Chrome Network tab are of no use unfortunately.
Okay, I actually think I figured this out, and it boiled down to two different things:
1. ADDING THE AMPLIFY LOGGER:
I found there is an Amplify logger via:
https://github.com/aws/aws-amplify/blob/master/media/logger_guide.md
So I added:
Amplify.Logger.LOG_LEVEL = 'DEBUG'
and now when I am debugging in VS Code I'm seeing the request URL being logged.
2. REALIZING 'queryStringParameters' ISN'T ACTUALLY SUPPORTED: .
I was looking through the Amplify GitHub repo issues and found out that queryStringParameters isn't actually supported yet, which is fun.
URL to issue: https://github.com/aws/aws-amplify/issues/127 .
So instead I appended all my query parameters onto the path, and that works:
const apiName = 'http://myendpoint.com'
const path = `/my/path?param=${value}`
API.get(apiName, path)
.then((response) => {
resolve(response)
},
(err) => {
console.log('err resp', err)
resolve(err)
})
I am now seeing the request URL logged, and seeing the parameters as a part of the request.
I use the following lib to connect to the cloud controller
https://github.com/prosociallearnEU/cf-nodejs-client
const endpoint = "https://api.mycompany.com/";
const username = "myuser";
const password = "mypass";
const CloudController = new (require("cf-client")).CloudController(endpoint);
const UsersUAA = new (require("cf-client")).UsersUAA;
const Apps = new (require("cf-client")).Apps(endpoint);
CloudController.getInfo().then((result) => {
UsersUAA.setEndPoint(result.authorization_endpoint);
return UsersUAA.login(username, password);
}).then((result) => {
Apps.setToken(result);
return Apps.getApps();
}).then((result) => {
console.log(result);
}).catch((reason) => {
console.error("Error: " + reason);
});
I try to run it against our API and its not working and Im not getting no error message in the console, what it can be ?
where does the space/org is handled here ? since when I connect from the cli it ask me to which space/org I want to connect...
Im able to login via the CLI, just from the code I cant, any idea what is missing here?
The issue it when I run it I dont get any error that can help to understand what is the root cause
I cloned the original git repository and modified some methods to support proxy. Please note that I modified just some methods to get the sample code working, but a complete refactor of the package is needed.
Basically what you have to do is to add a proxy parameter before calling the request method (this is done throughout the package, so several modifications are needed), for example this is for one of the methods in the Organization.js file:
getSummary (guid) {
const url = `${this.API_URL}/v2/organizations/${guid}/summary`;
const proxy = `${this.API_PROXY}`;
const options = {
method: "GET",
url: url,
proxy: proxy,
headers: {
Authorization: `${this.UAA_TOKEN.token_type} ${this.UAA_TOKEN.access_token}`
}
};
return this.REST.request(options, this.HttpStatus.OK, true);
}
You can find my changes in the git repository below:
https://github.com/adasilva70/cf-nodejs-client.git
I have also created a new sample below. This sample lists all organizations for a user, gets the first organization returned and lists its spaces. You can modify the code to provide a similar functionality that cf login provides (allow you to select an organization then a space).
const endpoint = "https://api.mycompany.com/";
const username = "youruser";
const password = "yourpassword";
const proxy = "http://proxy.mycompany.com:8080";
const CloudController = new (require("cf-nodejs-client")).CloudController(endpoint, proxy);
const UsersUAA = new (require("cf-nodejs-client")).UsersUAA;
const Apps = new (require("cf-nodejs-client")).Apps(endpoint, proxy);
const Orgs = new (require("cf-nodejs-client")).Organizations(endpoint, proxy);
CloudController.getInfo().then((result) => {
console.log(result);
UsersUAA.setEndPoint(result.authorization_endpoint, proxy);
return UsersUAA.login(username, password);
}).then((result) => {
//Apps.setToken(result);
//return Apps.getApps();
Orgs.setToken(result);
return Orgs.getOrganizations();
}).then((result) => {
console.log(result);
org_guid = result.resources[1].metadata.guid;
return Orgs.getSummary(org_guid);
}).then((result) => {
console.log(result);
}).catch((reason) => {
console.error("Error: " + reason);
});
I have done just minor tests to make sure the sample works, so use carefully. Also, the changes will only work for a case where proxy is needed now.
The first thing that strikes me on the library's github site is the warning:
Note: This package is not ready for a production App yet.
It also seems that the project is not being maintained as there are a number of tickets ooened that are quite a few months old that don't have a response.
Anyway, to figure out why the library is not working and producing no error message, I would check out the library source code and add some console logging statements, probably starting with the HttpUtils. For example:
requestWithDefaults(options, function (error, response, body) {
console.log("requestWithDefaults error: ", error)
console.log("requestWithDefaults response: ", response)
console.log("requestWithDefaults body: ", body)
...
}
Alternatively, you could try debugging the code by adding breakpoints to the requestWithDefaults and other key places in the library, using the nodejs debugger.
You could also try debugging the network calls similar to this how to monitor the network on node.js similar to chrome/firefox developer tools?
To understand how to use the library, I would take a look into the tests folder and look for a test that is similar to your use case. There are a reasonable amount if tests that look useful in the test/lib/model/cloudcontroller folder.
As for the question about spaces, I have found an example where you can pass in a space guid to return apps for that space guid.
CloudFoundrySpaces.getSpaceApps(space_guid, filter).then( ... )
I'm assuming the call you are using App.getApps() will return Apps for all spaces/organizations.
I need to mock client side HTTP requests. I'm using isomorphic-fetch in the client side and I'm using mocha and nock for testing and mocking. All my client requests are based on relative path. Due to this I'm unable to provide host name for the nock. Is there a work around.
Client side:
fetch('/foo') //hostname: http://localhost:8080
.then(res => res.json())
.then(data => console.log(data))
.catch(e => console.log(e))
Test suite
nock('/')
.get('/foo')
.reply(200, {data: "hello"})
This is failing as I'm not giving the proper hostname for the nock. Am I doing something wrong?
For anyone interested: In my react/webpack project I solved this by prepending the fetch url with 'http://localhost' when NODE_ENV is set to 'test'.
example:
const testing = process.env.NODE_ENV === 'test';
const apiUrl = `${testing ? 'http://localhost' : ''}/api`;
function getStuffFromApi() {
return fetch(apiUrl, ...)
}
This way, in my test I can always use nock like so:
nock('http://localhost')
.get('/api')
.reply(200, {data: 'hello'})
NOTE: When running my tests, NODE_ENV gets set to 'test'
Found a workaround for this. Have a _ajax-setup.js in your test folder
import $ from 'jquery'
$(document).ajaxSend((event, jqxhr, settings) => {
settings.url = 'http://0.0.0.0' + settings.url;
})
The thing to note is that this file has to run First and Only Once. Having it as a file runs only once and _ before it makes it alphabetically first.
Later you can test your code with
nock('http://0.0.0.0')
.get('/foo')
.reply(200, {data: "hello"})
I just asked a similar question on Nock's repository. Apparently this is not supported: https://github.com/pgte/nock/issues/431
For axios I added following to my test file. This helped overcome this limitation.
axios.defaults.baseURL='http://localhost:4000/';
Please note that this is a global variable.
With this the actual code can live with relative URL and there is no need to check testing flag in it.
kudresov's reply to liorbauer's issue describes a Jest-specific workaround.
Put this into __mocks__/isomorphic-fetch.js:
const fetch = require.requireActual('isomorphic-fetch');
module.exports = (url, config) => {
return fetch('https://localhost' + url, config);
};
Jest then automatically replaces all requires (or imports) for this node module.
In other test frameworks you could use something like rewire