Swagger ExpressJS return No operations defined in spec - express

Hello I'm trying to use swagger to my express server but return 'No operations defined in spec!' I already watch like 5 different videos but still has no luck how to fix this

Configurations looks correct only some adjustments in definition and options should work, Here are the code you should re-arrange,
You should write yaml double spaced instead of Tab,
/**
* #swagger
* /api/v1/friends:
* get:
* tags:
* - "Healthcheck"
* summary: summary of your api endpoint.
* description: description of your api endpoint.
* responses:
* 200:
* description: List of topics.
*/
Pass swagger options with these configurations do change values based on your application, validate file path if specified accurately, Most values are optional see docs for more details
const swaggerOptions = {
openapi: '3.0.0',
swaggerDefinition: {
info: {
title: 'Friends API',
version: '1.0.0',
description: 'Friends api endpoints',
servers: ['https://your-api-serverhosturl.com'],
},
produces: ['application/json'],
},
apis: ['../modules/friends/*.routes.js'],
};
const swaggerDocs = swaggerJsDoc(swaggerOptions);
app.use('/api/api-docs', swaggerUI.serve, swaggerUI.setup(swaggerDocs));
Navigate to http://yourhost:port/api/api-docs

Related

WebDriverIO: browser.pause does not working

I have used browser.sleep in protractor to hold the execution for a particular amount of time. In similar way I have tried the browser.pause in WebDriverIO. But it is not pausing for the given amount of time.
Even for browser pause I referred the WebDriverIO official documentation, there also the same thing is given
Step Definition Code:
Given(/^Verify the title of Salesforce web page$/,function(){
browser.url('https://login.salesforce.com/');
browser.pause(10000);
});
I use async mode in the configuration
WebDriverIO Version: ^5.22.4
wdio.config.js
exports.config = {
//
// ====================
// Runner Configuration
// ====================
//
// WebdriverIO allows it to run your tests in arbitrary locations (e.g. locally or
// on a remote machine).
runner: 'local',
//
// Override default path ('/wd/hub') for chromedriver service.
path: '/',
//
// ==================
// Specify Test Files
// ==================
// Define which test specs should run. The pattern is relative to the directory
// from which `wdio` was called. Notice that, if you are calling `wdio` from an
// NPM script (see https://docs.npmjs.com/cli/run-script) then the current working
// directory is where your package.json resides, so `wdio` will be called from there.
//
specs: [
'./test/features/*.feature'
],
// Patterns to exclude.
exclude: [
// 'path/to/excluded/files'
],
//
// ============
// Capabilities
// ============
// Define your capabilities here. WebdriverIO can run multiple capabilities at the same
// time. Depending on the number of capabilities, WebdriverIO launches several test
// sessions. Within your capabilities you can overwrite the spec and exclude options in
// order to group specific specs to a specific capability.
//
// First, you can define how many instances should be started at the same time. Let's
// say you have 3 different capabilities (Chrome, Firefox, and Safari) and you have
// set maxInstances to 1; wdio will spawn 3 processes. Therefore, if you have 10 spec
// files and you set maxInstances to 10, all spec files will get tested at the same time
// and 30 processes will get spawned. The property handles how many capabilities
// from the same test should run tests.
//
maxInstances: 10,
//
// If you have trouble getting all important capabilities together, check out the
// Sauce Labs platform configurator - a great tool to configure your capabilities:
// https://docs.saucelabs.com/reference/platforms-configurator
//
capabilities: [{
// maxInstances can get overwritten per capability. So if you have an in-house Selenium
// grid with only 5 firefox instances available you can make sure that not more than
// 5 instances get started at a time.
maxInstances: 5,
//
browserName: 'chrome',
// If outputDir is provided WebdriverIO can capture driver session logs
// it is possible to configure which logTypes to include/exclude.
// excludeDriverLogs: ['*'], // pass '*' to exclude all driver session logs
// excludeDriverLogs: ['bugreport', 'server'],
}],
//
// ===================
// Test Configurations
// ===================
// Define all options that are relevant for the WebdriverIO instance here
//
// Level of logging verbosity: trace | debug | info | warn | error | silent
logLevel: 'info',
//
// Set specific log levels per logger
// loggers:
// - webdriver, webdriverio
// - #wdio/applitools-service, #wdio/browserstack-service, #wdio/devtools-service, #wdio/sauce-service
// - #wdio/mocha-framework, #wdio/jasmine-framework
// - #wdio/local-runner, #wdio/lambda-runner
// - #wdio/sumologic-reporter
// - #wdio/cli, #wdio/config, #wdio/sync, #wdio/utils
// Level of logging verbosity: trace | debug | info | warn | error | silent
// logLevels: {
// webdriver: 'info',
// '#wdio/applitools-service': 'info'
// },
//
// If you only want to run your tests until a specific amount of tests have failed use
// bail (default is 0 - don't bail, run all tests).
bail: 0,
//
// Set a base URL in order to shorten url command calls. If your `url` parameter starts
// with `/`, the base url gets prepended, not including the path portion of your baseUrl.
// If your `url` parameter starts without a scheme or `/` (like `some/path`), the base url
// gets prepended directly.
baseUrl: 'https://login.salesforce.com/',
//
// Default timeout for all waitFor* commands.
waitforTimeout: 10000,
//
// Default timeout in milliseconds for request
// if browser driver or grid doesn't send response
connectionRetryTimeout: 90000,
//
// Default request retries count
connectionRetryCount: 0,
//
// Test runner services
// Services take over a specific job you don't want to take care of. They enhance
// your test setup with almost no effort. Unlike plugins, they don't add new
// commands. Instead, they hook themselves up into the test process.
services: ['chromedriver','firefox-profile'],
// Framework you want to run your specs with.
// The following are supported: Mocha, Jasmine, and Cucumber
// see also: https://webdriver.io/docs/frameworks.html
//
// Make sure you have the wdio adapter package for the specific framework installed
// before running any tests.
framework: 'cucumber',
//
// The number of times to retry the entire specfile when it fails as a whole
// specFileRetries: 1,
//
// Test reporter for stdout.
// The only one supported by default is 'dot'
// see also: https://webdriver.io/docs/dot-reporter.html
reporters: ['spec',['allure', {
outputDir: 'allure-results',
disableWebdriverStepsReporting: true,
disableWebdriverScreenshotsReporting: false,
useCucumberStepReporter:true
}]],
// If you are using Cucumber you need to specify the location of your step definitions.
cucumberOpts: {
require: ['./built/**/*.js'], // <string[]> (file/dir) require files before executing features
backtrace: false, // <boolean> show full backtrace for errors
requireModule: [], // <string[]> ("extension:module") require files with the given EXTENSION after requiring MODULE (repeatable)
dryRun: false, // <boolean> invoke formatters without executing steps
failFast: false, // <boolean> abort the run on first failure
format: ['pretty'], // <string[]> (type[:path]) specify the output format, optionally supply PATH to redirect formatter output (repeatable)
colors: true, // <boolean> disable colors in formatter output
snippets: true, // <boolean> hide step definition snippets for pending steps
source: true, // <boolean> hide source uris
profile: [], // <string[]> (name) specify the profile to use
strict: false, // <boolean> fail if there are any undefined or pending steps
tagExpression: '', // <string> (expression) only execute the features or scenarios with tags matching the expression
timeout: 60000, // <number> timeout for step definitions
ignoreUndefinedDefinitions: false, // <boolean> Enable this config to treat undefined definitions as warnings.
},
//
// =====
// Hooks
// =====
// WebdriverIO provides several hooks you can use to interfere with the test process in order to enhance
// it and to build services around it. You can either apply a single function or an array of
// methods to it. If one of them returns with a promise, WebdriverIO will wait until that promise got
// resolved to continue.
/**
* Gets executed once before all workers get launched.
* #param {Object} config wdio configuration object
* #param {Array.<Object>} capabilities list of capabilities details
*/
// onPrepare: function (config, capabilities) {
// },
/**
* Gets executed just before initialising the webdriver session and test framework. It allows you
* to manipulate configurations depending on the capability or spec.
* #param {Object} config wdio configuration object
* #param {Array.<Object>} capabilities list of capabilities details
* #param {Array.<String>} specs List of spec file paths that are to be run
*/
// beforeSession: function (config, capabilities, specs) {
// },
/**
* Gets executed before test execution begins. At this point you can access to all global
* variables like `browser`. It is the perfect place to define custom commands.
* #param {Array.<Object>} capabilities list of capabilities details
* #param {Array.<String>} specs List of spec file paths that are to be run
*/
before: function (_capabilities) {
// =================
// Assertion Library
// =================
const chai = require('chai');
global.expect = chai.expect;
global.assert = chai.assert;
global.should = chai.should();
require('ts-node').register({ files: true });
},
/**
* Runs before a WebdriverIO command gets executed.
* #param {String} commandName hook command name
* #param {Array} args arguments that command would receive
*/
// beforeCommand: function (commandName, args) {
// },
/**
* Runs before a Cucumber feature
*/
beforeFeature: function (uri, feature, scenarios) {
scenarioCounter = 0;
},
/**
* Runs before a Cucumber scenario
*/
// beforeScenario: function (uri, feature, scenario, sourceLocation) {
// },
/**
* Runs before a Cucumber step
*/
// beforeStep: function (uri, feature, stepData, context) {
// },
/**
* Runs after a Cucumber step
*/
afterStep: function (uri, feature, { error, result, duration, passed }, stepData, context) {
if (error !== undefined) {
browser.takeScreenshot();
}
},
/**
* Runs after a Cucumber scenario
*/
afterScenario: function (uri, feature, scenario, result, sourceLocation) {
scenarioCounter += 1;
addArgument('Scenario #', scenarioCounter);
},
/**
* Runs after a Cucumber feature
*/
// afterFeature: function (uri, feature, scenarios) {
// },
/**
* Runs after a WebdriverIO command gets executed
* #param {String} commandName hook command name
* #param {Array} args arguments that command would receive
* #param {Number} result 0 - command success, 1 - command error
* #param {Object} error error object if any
*/
// afterCommand: function (commandName, args, result, error) {
// },
/**
* Gets executed after all tests are done. You still have access to all global variables from
* the test.
* #param {Number} result 0 - test pass, 1 - test fail
* #param {Array.<Object>} capabilities list of capabilities details
* #param {Array.<String>} specs List of spec file paths that ran
*/
// after: function (result, capabilities, specs) {
// },
/**
* Gets executed right after terminating the webdriver session.
* #param {Object} config wdio configuration object
* #param {Array.<Object>} capabilities list of capabilities details
* #param {Array.<String>} specs List of spec file paths that ran
*/
// afterSession: function (config, capabilities, specs) {
// },
/**
* Gets executed after all workers got shut down and the process is about to exit. An error
* thrown in the onComplete hook will result in the test run failing.
* #param {Object} exitCode 0 - success, 1 - fail
* #param {Object} config wdio configuration object
* #param {Array.<Object>} capabilities list of capabilities details
* #param {<Object>} results object containing test results
*/
// onComplete: function(exitCode, config, capabilities, results) {
// },
/**
* Gets executed when a refresh happens.
* #param {String} oldSessionId session ID of the old session
* #param {String} newSessionId session ID of the new session
*/
//onReload: function(oldSessionId, newSessionId) {
//}
}
Since, it was an async mode in WebDriverIO, have to add the await in both of the lines as below.
Given(/^Verify the title of Salesforce web page$/, async function(){
await browser.url('https://login.salesforce.com/');
await browser.pause(10000);
});
Might be worthy trying async/await as below:
Given(/^Verify the title of Salesforce web page$/, async function(){
await browser.url('https://login.salesforce.com/');
await browser.pause(10000);
});
I hope it helps
In my case someone had globally activated fake timers (jest.useFakeTimers()).
For now, in my End to end tests, I'm just switching back to real timers (jest.useRealTimers()).

Handling Basic Authentication in Karate UI scenario

I have just started implementing karate UI (v0.9.5). Have already implemented api testing using karate and it works perfectly.
Following the HTTP basic auth strategy on this page - https://github.com/intuit/karate#http-basic-authentication-example the basic auth handling works for api tests. I set the HTTP headers once and run all api tests.
Now for the UI testing, the URL that I open brings up the basic auth pop-up as shown below:
So I thought that I could use the same strategy that I used for api tests to handle this. In the background section of my feature file, i call the feature file that does the authentication and sets headers as below:
The called feature file to set headers (admin-headers.feature). This feature file gets the token after admin user login is performed via karate-config.js. Then assigns the token along with the Base64 encoded basic auth to the headers calling headers.js. The Base64 user and password are being input as maven arguments and read via karate-config variables.
(/admin-headers.feature)
Feature: karate-config.js will perform one time login for admin and
set the session token for all subsequent requests
Background:
* def session = adminAuthInfo.authSession
* def basic_auth = call read('classpath:basic-auth.js') { username: '#(basicAuthUser)', password: '#(basicAuthPassword)' }
* configure headers = read('classpath:headers.js')
Scenario: One-time login for user and set the
session token in request header
The js code for returning Auth and Cookie to above feature file (/headers.js).
function() {
var session = karate.get('session');
var basic_auth = karate.get('basic_auth');
if(session){
return {
Authorization: basic_auth,
Cookie: "SESSION=" + session
};
} else {
return {};
}
}
My UI test feature file (/ui-test.feature):
Feature: Login test
Background:
# Authorise via api
* callonce read('classpath:common/headers/admin-headers.feature')
* configure driver = { type: 'chrome' }
Scenario: Test login
Given driver 'https://test.internal.mysite.com/names'
Running the above feature file still shows the auth pop-up.
I then tried to set the cookies while I am initialising the driver (which I think is probably not the right way?) as below:
Feature: Login test
Background:
# Authorise via api
* def login = callonce read('classpath:common/headers/admin-headers.feature')
* def uiCookie = { name: 'SESSION', value: '#(login.userAuthInfo.authSession)', domain: 'test.internal.mysite.com' }
* configure driver = { type: 'chrome', cookie: '#(uiCookie)' }
Scenario: Test login
Given driver 'https://test.internal.mysite.com/names'
The above also does not work. What is it that I am doing wrong here? the pop-up keeps coming up because the cookie is not set when the driver is initialised and then opens the specified url?
Help is much appreciated.
I think you raised a very good feature request, that configure driver should take cookies also, so that you can navigate to the page and set cookies in one-shot, and I opened a feature request: https://github.com/intuit/karate/issues/1053
So try this sequence, refer docs for cookie(): https://github.com/intuit/karate/tree/master/karate-core#cookieset
* driver 'about:blank'
* cookie(uiCookie)
* driver 'https://test.internal.mysite.com/names'
And now it should work !
Feature: Windows Authentication feature
Background:
* configure driver = { type: 'chrome' }
Scenario: Windows Authentication Valid Login test case
Given driver 'http://the-internet.herokuapp.com/basic_auth'
And delay(3000)
And screenshot()
* robot {}
* robot.input('admin' + Key.TAB)
* robot.input('admin')
* robot.click('Sign in')
And delay(3000)
And screenshot()
works fine with chrome, edge

Express-Gateway, How to pick a service end point based on URL pattern?

I am trying to get a bunch of individual servers on the same domain behind the gateway. Currently, each of these servers can be reached from outside world via multiple names. Our sales team wanted to provide customers with a unique url, so if a server serves 10 customers, we have 10 CNAME records pointing to it.
As you can see, with 5 or 6 servers, the number of apiEndpoints is pretty large. On top of that, new CNAMEs can be created at any given time making hardcoded apiEndpoints a pain to manage.
Is it possible to have a dynamic serviceEndpoint url. What I'm thinking is something like this:
apiEndpoints:
legacy:
host: '*.mydomain.com'
paths: '/v1/*'
serviceEndpoints:
legacyEndPoint:
url: '${someVarWithValueofStar}.internal.com'
pipelines:
default:
apiEndpoints:
- legacy:
policies:
- proxy:
- action:
serviceEndpoint: legacyEndPoint
Basically, what I want to achieve is to redirect the all the x.mydomain.com to x.internal.com where x can be anything.
Can I use variables in the url strings? Is there a way to get the string that matched the wild card in the host? Are there other options to deal with this problem?
I ended up hacking a proxy plugin together for my needs. Very basic and requires more work and testing, but this what I started with:
The proxy plugin (my-proxy)
const httpProxy = require("http-proxy");
/**
* This is a very rudimentary proxy plugin for the express gateway framework.
* Basically it will redirect requests xxx.external.com to xxx.internal.com
* Where xxx can be any name and the destination comes from providing a
* service endpoint with a http://*.destination.com url
* #param {*} params
* #param {*} config
*/
module.exports = function (params, config) {
const serviceEndpointKey = params.serviceEndpoint;
const changeOrigin = params.changeOrigin;
const endpoint = config.gatewayConfig.serviceEndpoints[serviceEndpointKey];
const url = endpoint.url;
const reg = /(\/\/\*\.)(\S+)/;
const match = reg.exec(url);
const domain = match[2];
const proxy = httpProxy.createProxyServer({changeOrigin : changeOrigin});
proxy.on("error", (err, req, res) => {
console.error(err);
if (!res.headersSent) {
res.status(502).send('Bad gateway.');
} else {
res.end();
}
});
return (req, res, next) => {
const hostname = req.hostname;
const regex = /^(.*?)\./
const tokens = regex.exec(hostname)
const serverName = tokens[1];
const destination = req.protocol + "://" + serverName + "." + domain;
proxy.web(req, res, {target : destination});
};
};
gateway.config.xml
http:
port: 8080
apiEndpoints:
legacy:
host: '*.external.com'
paths: '/v1/*'
serviceEndpoints:
legacy_end_point:
url: 'https://*.internal.com'
policies:
- my-proxy
pipelines:
default:
apiEndpoints:
- legacy
policies:
- my-proxy:
- action:
serviceEndpoint: legacy_end_point
changeOrigin: true
It all boils down to regex parsing the wild cards in the apiEndpoints and serviceEndpoints host and urls, nothing fancy so far. I looked at the source code of the built in proxy plugin and I don't think my naive approach will fit in very well, but it works for what I need it.
thanks for the question, I think this is going to be asked a lot over the following months.
Express Gateway has support for environment variables; unfortunately right now the apiEndpoint can only be a single and well defined endpoint without any replacement capabilities.
This is something we'll probably change in the near term future — with a Proxy Table API that will let you insert some more difficult templates.
In case this is pressing for you, I'd invite you to open an issue so that everybody in the team is aware of such feature and we can prioritize it effectively.
In meantime, unfortunately, you'll have to deal with numerous numbers of ApiEndpoints
V.

Cannot run PlusDomains example in Google App Maker

I am trying to run this example code in Google App Maker:
/**
* The following example demonstrates how to create a post that is available
* to all users within your G Suite domain.
*/
function createPost() {
var userId = 'me';
var post = {
object: {
originalContent: 'Happy Monday! #caseofthemondays'
},
access: {
items: [{
type: 'domain'
}],
domainRestricted: true
}
};
post = PlusDomains.Activities.insert(post, userId);
Logger.log('Post created with URL: %s', post.url);
}
However, I keep getting this:
GoogleJsonResponseException: Access to the Google+ Domains API is not allowed as the user has consented to incompatible scopes.
Has anybody else managed to get this working?
Pavel's link had the answer: I just had to remove all access at https://security.google.com/settings/security/permissions and then re-authorize.
Thanks, Pavel!

JSON Store is not creating in Android for latest version fix pack 7.1.0.00.20160919-1656

Below sample code is not working in latest fix on Android but if we remove the password field from options then it's working fine. We are getting below error on Android but it's working fine on IOS
{"src":"initCollection","err":-3,"msg":"INVALID_KEY_ON_PROVISION","col":"people","usr":"test","doc":{},"res":{}}
function wlCommonInit(){
/*
* Use of WL.Client.connect() API before any connectivity to a MobileFirst Server is required.
* This API should be called only once, before any other WL.Client methods that communicate with the MobileFirst Server.
* Don't forget to specify and implement onSuccess and onFailure callback functions for WL.Client.connect(), e.g:
*
* WL.Client.connect({
* onSuccess: onConnectSuccess,
* onFailure: onConnectFailure
* });
*
*/
// Common initialization code goes here
}
function onClick(){
alert("Click");
var collectionName = 'people';
// Object that defines all the collections.
var collections = {
// Object that defines the 'people' collection.
people : {
// Object that defines the Search Fields for the 'people' collection.
searchFields : {name: 'string', age: 'integer'}
}
};
// Optional options object.
var options = {
username:"test",
// Optional password, default no passw`enter code here`ord.
password : '123',
};
WL.JSONStore.init(collections, options)
.then(function () {
alert("Success in jstore");
})
.fail(function (errorObject) {
// Handle failure for any of the previous JSONStore operations (init, add).
alert("Failure in jstore : "+ JSON.stringify(errorObject));
});
};
Update: The iFix is now released. Build number is 7.1.0.0-IF201610060540 .
This is a known issue with the latest available iFix. It has been recently fixed and should be available soon.
Keep an eye out for a newer iFix release in the IBM Fix Central website for a fix for this issue.