Trying to figure out, how to use multiple karate-config.js and karate-config-.js file
like below File 1: karate-congig.js
function fn() {
var env = karate.env; // get system property 'karate.env'
karate.log('karate.env system property was:', env);
if (!env) {
env = 'dev';
}
var config = {
}
if (env == 'dev') {
// customize
// e.g. config.foo = 'bar';
} else if (env == 'e2e') {
// customize
}
return config;
}
File 2: karate-config-SysVar.js
function fn() {
var config = {
dbUserName : 'UserName',
dbPassword : 'password',
HostURL : 'URL'
}
return config;
}
Tried to refer this documentation: https://github.com/karatelabs/karate#environment-specific-config
And example Not Found https://github.com/karatelabs/karate/blob/master/karate-demo/src/test/java/karate-config-contract.js
Thanks in Advance
Related
The original developers for my project didn't commit the package-lock.json file, only the package.json file. I created my own package-lock.json file when I did npm install, but that was 5 years ago and I didn't realise at the time that I needed to check the file into Git because I stupidly assumed that the original developers knew what they were doing.
Now we have a second developer, plus I need to add a new package. Both of these things require that I have the "original" package-lock.json file.
Is there a way to reconstruct the package-lock.json file using npm from the contents of my node_modules directory which is now the only source of truth? I have looked at various answers and tried a few npm commands, such as npm i --package-lock-only, but that gave me a file as it would be created today, not the file based on my node_modules directory.
So, not finding an answer, I've spent the last two days writing some PHP code to do the job for me. The code is not complete, for example it assumes that the only production modules will be angular and angular-ui-router because I didn't need anything more complicated with my project. However, it's good enough to create an exact copy of the package-lock.json file, minus optional dependencies that weren't installed, because it can't resolve versions of packages it can't find.
The code was written to work, not necessarily to be easy to understand, so it might be a little opaque.
It's run with:
<?php
$package_lock = new PackageLock();
// or
$package_lock = new PackageLock('path/to/packages');
The code:
<?php
class PackageLock {
protected const MY_PACKAGE = 'my-package';
protected const MY_VERSION = '0.0.0';
//
protected const FILE_NAME = 'package-lock-recreated.json';
protected const NODE_MODULES = 'node_modules';
//
protected array $modules = [];
protected array $packages = [
'name' => PackageLock::MY_PACKAGE,
'version' => PackageLock::MY_VERSION,
'lockfileVersion' => 1,
'requires' => true,
];
protected string $dir;
public function __construct(string $dir = '.') {
$this->dir = $dir;
$this->packages['dependencies'] = $this->parse();
file_put_contents(PackageLock::FILE_NAME, preg_replace('/^( +)\1/m', '$1', json_encode($this->packages, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT)));
}
protected function parse(array $priors = []): array {
$nm = PackageLock::NODE_MODULES;
$requests = $priors;
array_unshift($requests, '');
$current_priors = $requests;
$current_priors[] = '';
$main_path = $this->dir . implode("/{$nm}/", $current_priors);
$dir_pattern = $main_path . '*';
$dirs = glob($dir_pattern);
$current_dir = dirname($dir_pattern, 2);
$dependencies = [];
foreach ($dirs as $dir) {
$module_name = basename($dir);
if (in_array($module_name, ['angular-moment-picker', 'json-loader', 'moment-timezone'])) {
continue;
}
$this->modules[$dir] = json_decode(file_get_contents("{$dir}/package.json"));
}
foreach ($this->modules as $dir => $module) {
if (strpos($dir, $main_path) !== 0) {
continue;
}
$module_name = basename($dir);
$dependencies[$module_name] = [
'version' => $module->version,
'resolved' => $module->_resolved,
'integrity' => $module->_integrity,
];
if (!$this->is_prod($module_name)) {
$dependencies[$module_name]['dev'] = true;
}
if ($this->is_optional($main_path . $module_name)) {
$dependencies[$module_name]['optional'] = true;
}
if (!empty($module->dependencies) && (array)$module->dependencies) {
$dependencies[$module_name]['requires'] = $module->dependencies;
}
if (is_dir("{$current_dir}/{$nm}/{$module_name}/{$nm}")) {
$dependencies[$module_name]['dependencies'] = $this->parse_dependencies($priors, $module_name);
}
}
return $dependencies;
}
protected function is_prod($module_name): bool {
return in_array($module_name, ['angular', 'angular-ui-router']);
}
protected function parse_dependencies(array $priors, string $module_name): array {
$priors[] = $module_name;
return $this->parse($priors);
}
protected function is_optional($key): bool {
$module_name = basename($key);
$is_optional = false;
if (!array_key_exists($key, $this->modules)) {
var_dump("Key does not exist: {$key}");
}
if ($this->modules[$key]) {
foreach ($this->modules[$key]->_requiredBy as $parent_module_path) {
if (in_array($parent_module_path, ['/', '#USER', '#DEV:/'])) {
break;
}
$parent_module_path = $this->module_to_file_path($parent_module_path);
if (array_key_exists($parent_module_path, $this->modules)) {
$is_optional = $this->check_optional($parent_module_path, $module_name);
}
else {
$file_name = "{$parent_module_path}/package.json";
if (!file_exists($file_name)) {
$is_optional = true;
}
else {
$this->modules[$parent_module_path] = json_decode(file_get_contents($file_name));
$is_optional = $this->check_optional($parent_module_path, $module_name);
unset($this->modules[$parent_module_path]);
}
}
if (!$is_optional) {
break;
}
}
}
return $is_optional;
}
protected function module_to_file_path($module_path): string {
return $this->dir . str_replace('/', '/' . PackageLock::NODE_MODULES . '/', $module_path);
}
protected function check_optional(string $parent_module_path, $module_name): bool {
if (
!empty($this->modules[$parent_module_path]->optionalDependencies)
&& property_exists($this->modules[$parent_module_path]->optionalDependencies, $module_name)
) {
$is_optional = true;
}
else {
$is_optional = $this->is_optional($parent_module_path);
}
return $is_optional;
}
}
reqres.feature
Feature: Reqres api test cases
Background: base url
Given url base_url
* def validateResponse = read('classpath:helpers/common_assertions.js')
Scenario: list single user get request
Given path single_user_path
When method get
Then status 200
* validateResponse()
common_assertion.js
function common_assertions() {
var contentType = karate.get("responseHeaders['Content-Type'][0]");
if (contentType !== 'application/json; charset=utf-8') {
karate.fail('content type is not json');
}
var responseType = karate.get('responseType');
if (responseType !== 'json') {
karate.fail('response type is not json');
}
var responseTime = karate.get('responseTime');
if (responseTime > 5000) {
karate.fail('response is too slow');
}
}
karate-config.js
function fn() {
var env = karate.env; // get system property 'karate.env'
karate.log('karate.env system property was:', env);
if (!env) {
env = 'dev';
}
var config = {
base_url: 'https://reqres.in/api',
single_user_path: '/users/2'
};
if (env == 'dev') {
// customize
// e.g. config.foo = 'bar';
} else if (env == 'e2e') {
// customize
}
return config;
}
I would like to use common_assertions.js file in karate-config.js file rather than using in the background section so that i can reuse * validateResponse() method across all feature files. Is there a way?Please help
I am able to run tests locally on my remote selenium server and they run just fine.
When I go to run them on my Jenkins box on the same remote selenium server in Jenkins I am getting No Specs found, and in the output of my selenium server I am seeing the following:
21:33:41.256 INFO - Executing: [execute async script: try { return (function (attempts, ng12Hybrid, asyncCallback) {
var callback = function(args) {
setTimeout(function() {
asyncCallback(args);
}, 0);
};
var check = function(n) {
try {
if (!ng12Hybrid && window.getAllAngularTestabilities) {
callback({ver: 2});
} else if (window.angular && window.angular.resumeBootstrap) {
callback({ver: 1});
} else if (n < 1) {
if (window.angular) {
callback({message: 'angular never provided resumeBootstrap'});
} else {
callback({message: 'retries looking for angular exceeded'});
}
} else {
window.setTimeout(function() {check(n - 1);}, 1000);
}
} catch (e) {
callback({message: e});
}
};
check(attempts);
}).apply(this, arguments); }
catch(e) { throw (e instanceof Error) ? e : new Error(e); }, [10, false]])
21:33:41.273 INFO - Done: [execute async script: try { return (function (attempts, ng12Hybrid, asyncCallback) {
var callback = function(args) {
setTimeout(function() {
asyncCallback(args);
}, 0);
};
var check = function(n) {
try {
if (!ng12Hybrid && window.getAllAngularTestabilities) {
callback({ver: 2});
} else if (window.angular && window.angular.resumeBootstrap) {
callback({ver: 1});
} else if (n < 1) {
if (window.angular) {
callback({message: 'angular never provided resumeBootstrap'});
} else {
callback({message: 'retries looking for angular exceeded'});
}
} else {
window.setTimeout(function() {check(n - 1);}, 1000);
}
} catch (e) {
callback({message: e});
}
};
check(attempts);
}).apply(this, arguments); }
catch(e) { throw (e instanceof Error) ? e : new Error(e); }, [10, false]]
21:33:41.288 INFO - Executing: [execute script: return (function (trackOutstandingTimeouts) {
var ngMod = angular.module('protractorBaseModule_', []).config([
'$compileProvider',
function($compileProvider) {
if ($compileProvider.debugInfoEnabled) {
$compileProvider.debugInfoEnabled(true);
}
}
]);
if (trackOutstandingTimeouts) {
ngMod.config([
'$provide',
function ($provide) {
$provide.decorator('$timeout', [
'$delegate',
function ($delegate) {
var $timeout = $delegate;
var taskId = 0;
if (!window['NG_PENDING_TIMEOUTS']) {
window['NG_PENDING_TIMEOUTS'] = {};
}
var extendedTimeout= function() {
var args = Array.prototype.slice.call(arguments);
if (typeof(args[0]) !== 'function') {
return $timeout.apply(null, args);
}
taskId++;
var fn = args[0];
window['NG_PENDING_TIMEOUTS'][taskId] =
fn.toString();
var wrappedFn = (function(taskId_) {
return function() {
delete window['NG_PENDING_TIMEOUTS'][taskId_];
return fn.apply(null, arguments);
};
})(taskId);
args[0] = wrappedFn;
var promise = $timeout.apply(null, args);
promise.ptorTaskId_ = taskId;
return promise;
};
extendedTimeout.cancel = function() {
var taskId_ = arguments[0] && arguments[0].ptorTaskId_;
if (taskId_) {
delete window['NG_PENDING_TIMEOUTS'][taskId_];
}
return $timeout.cancel.apply($timeout, arguments);
};
return extendedTimeout;
}
]);
}
]);
}
}).apply(null, arguments);, [true]])
21:33:41.312 INFO - Done: [execute script: return (function (trackOutstandingTimeouts) {
var ngMod = angular.module('protractorBaseModule_', []).config([
'$compileProvider',
function($compileProvider) {
if ($compileProvider.debugInfoEnabled) {
$compileProvider.debugInfoEnabled(true);
}
}
]);
if (trackOutstandingTimeouts) {
ngMod.config([
'$provide',
function ($provide) {
$provide.decorator('$timeout', [
'$delegate',
function ($delegate) {
var $timeout = $delegate;
var taskId = 0;
if (!window['NG_PENDING_TIMEOUTS']) {
window['NG_PENDING_TIMEOUTS'] = {};
}
var extendedTimeout= function() {
var args = Array.prototype.slice.call(arguments);
if (typeof(args[0]) !== 'function') {
return $timeout.apply(null, args);
}
taskId++;
var fn = args[0];
window['NG_PENDING_TIMEOUTS'][taskId] =
fn.toString();
var wrappedFn = (function(taskId_) {
return function() {
delete window['NG_PENDING_TIMEOUTS'][taskId_];
return fn.apply(null, arguments);
};
})(taskId);
args[0] = wrappedFn;
var promise = $timeout.apply(null, args);
promise.ptorTaskId_ = taskId;
return promise;
};
extendedTimeout.cancel = function() {
var taskId_ = arguments[0] && arguments[0].ptorTaskId_;
if (taskId_) {
delete window['NG_PENDING_TIMEOUTS'][taskId_];
}
return $timeout.cancel.apply($timeout, arguments);
};
return extendedTimeout;
}
]);
}
]);
}
}).apply(null, arguments);, [true]]
Like I said, these run just fine locally, so I am not sure what is going on with my Jenkins machine.
Here is my protractor config file:
// Configuration constants
var downloadsFolder = 'test/downloads/',
today = ("0" + (new Date()).getDate()).slice(-2),
month = ("0" + ((new Date()).getMonth() + 1)).slice(-2),
baseUrl = 'BASE URL GOES HERE';
// Test report setup w/ screenshot
var HtmlScreenshotReporter = require('protractor-jasmine2-screenshot-reporter');
var reporter = new HtmlScreenshotReporter({
dest: 'test/report',
filename: 'e2e-report.html'
});
// Protractor config
exports.config = {
suites: {
explore: '.protractor/src/app/exploration/tests/exploration.scenario.js',
login: '.protractor/src/auth-app/login/tests/login.scenario.js',
stories: '.protractor/src/app/story/tests/story.scenario.js',
cohorts: '.protractor/src/app/cohort/tests/cohort.scenario.js',
visualize: '.protractor/src/app/visualize/tests/visualize.scenario.js'
},
baseUrl: 'BASE URL GOES HERE',
directConnect: false,
// Override default 11s timeout for long requests such as visualize's "Recommended Visualizations"
// See https://github.com/angular/protractor/blob/master/docs/timeouts.md
allScriptsTimeout: 25 * 1000,
jasmineNodeOpts: {
defaultTimeoutInterval: 90 * 1000
},
multiCapabilities: [
{
browserName: 'chrome',
seleniumAddress: "http://SELENIUM SERVER URL HERE:4444/wd/hub",
platform: 'ANY',
version: 'ANY',
chromeOptions: {
args: ['--no-sandbox', '--test-type=browser', '--lang=en', '--start-maximized'],
prefs: {
download: {
prompt_for_download: false,
directory_upgrade: true,
default_directory: 'test/downloads'
},
},
}
// shardTestFiles: true,
// maxInstances: 2
}
],
onPrepare: function() {
// Set browser window size
browser.driver.manage().window().maximize();
//Setup screenshots
jasmine.getEnv().addReporter(reporter);
browser.get('BASE URL GOES HERE');
},
// Setup the report before any tests start
beforeLaunch: function() {
return new Promise(function(resolve){
reporter.beforeLaunch(resolve);
});
},
// Close the report after all tests finish
afterLaunch: function(exitCode) {
return new Promise(function(resolve){
reporter.afterLaunch(resolve.bind(this, exitCode));
});
},
params: {
baseUrl: baseUrl,
downloadsFolder: 'test/downloads',
cohort: {
listView: baseUrl + 'cohorts',
newView: baseUrl + 'cohorts/new'
},
story: {
listView: baseUrl + 'stories',
newView: baseUrl + 'story/new',
displayView: baseUrl + 'story'
},
visualize: {
listView: baseUrl + 'visualize',
newView: baseUrl + 'visualize/new'
},
explore: {
listView: baseUrl + 'explorations',
newView: baseUrl + 'explorations/new',
excelFilename: downloadsFolder + `DataExport_2016-${month}-${today}.xlsx`,
csvFilename: downloadsFolder + `DataExport_2016-${month}-${today}.csv`,
maxDownloadTime: 10 * 1000
}
}
};
This boiled down to a permissions issue. Once I added my jenkins user to sudo I was able to do a make command on the project which built all of the necessary files and which also converted my typescript tests over to Javascript and allowed them to run.
If I have like 10 m.module on my page, can I call m.startComputation, m.endComputation, m.redraw or m.request for only one of those modules?
It looks like any of these will redraw all of my modules.
I know only module 1 will be affected by some piece of code, I only want mithril to redraw that.
Right now, there's no simple support for multi-tenancy (i.e. running multiple modules independently of each other).
The workaround would involve using subtree directives to prevent redraws on other modules, e.g.
//helpers
var target
function tenant(id, module) {
return {
controller: module.controller,
view: function(ctrl) {
return target == id ? module.view(ctrl) : {subtree: "retain"}
}
}
}
function local(id, callback) {
return function(e) {
target = id
callback.call(this, e)
}
}
//a module
var MyModule = {
controller: function() {
this.doStuff = function() {alert(1)}
},
view: function() {
return m("button[type=button]", {
onclick: local("MyModule", ctrl.doStuff)
}, "redraw only MyModule")
}
}
//init
m.module(element, tenant("MyModule", MyModule))
You could probably also use something like this or this to automate decorating of event handlers w/ local
Need multi-tenancy support for components ? Here is my gist link
var z = (function (){
//helpers
var cache = {};
var target;
var type = {}.toString;
var tenant=function(componentName, component) {
return {
controller: component.controller,
view: function(ctrl) {
var args=[];
if (arguments.length > 1) args = args.concat([].slice.call(arguments, 1))
if((type.call(target) === '[object Array]' && target.indexOf(componentName) > -1) || target === componentName || target === "all")
return component.view.apply(component, args.length ? [ctrl].concat(args) : [ctrl])
else
return {subtree: "retain"}
}
}
}
return {
withTarget:function(components, callback) {
return function(e) {
target = components;
callback.call(this, e)
}
},
component:function(componentName,component){
//target = componentName;
var args=[];
if (arguments.length > 2) args = args.concat([].slice.call(arguments, 2))
return m.component.apply(undefined,[tenant(componentName,component)].concat(args));
},
setTarget:function(targets){
target = targets;
},
bindOnce:function(componentName,viewName,view) {
if(cache[componentName] === undefined) {
cache[componentName] = {};
}
if (cache[componentName][viewName] === undefined) {
cache[componentName][viewName] = true
return view()
}
else return {subtree: "retain"}
},
removeCache:function(componentName){
delete cache[componentName]
}
}
})();
What is the syntax of the keybinds.settings? I am a vim user, and I would ultimately like to:
bind shift-j to go down 8 lines (nnoremap J 8j)
the same with k (nnoremak J 8k)
Use , as a "leader", i.e. I would like to bind ",b" to "build", and perhaps ",g" to run "ghci file-name" in a terminal.
keybinding.settings file works only for cloud9 commands for now, for customizing vim commands you will have to use init script (see Open Your Init Script item in Cloud9 menu)
You can use following snippet
require(["plugins/c9.ide.ace.keymaps/vim/keymap"], function(vim) {
var defaultKeymap = vim.aceKeyboardHandler.defaultKeymap;
function ideCommand() { services.commands.exec(this.name); }
function map(keys, action, context) {
var mapping;
if (!action) {
return defaultKeymap.forEach(function(x) {
if (x.keys == keys) {
x.defaultKeys = keys;
x.keys = "";
}
});
} else if (/^c9:/.test(action)) {
var commandName = action.substr(3);
mapping = {
keys: keys, type: "action", action: "aceCommand",
actionArgs: { exec: ideCommand, name: commandName }
};
} else {
mapping = { keys: keys, type: "keyToKey", toKeys: action };
}
if (context)
mapping.context = context;
mapping.user = true;
defaultKeymap.unshift(mapping);
}
map("J", "8j", "normal");
map("K", "8k", "normal");
map(",", ""); // remove default mapping of ,
map(",b", "c9:build", "normal");
map(",g", "c9:run", "normal");
});
note that for ,g you need to create ghci runner, see https://docs.c9.io/custom_runners.html for details.