groovy how to test for environment existence inside config.groovy - groovy

best practice for testing for existence in tree structure? For example testing for environment existence within a config file. Current working example below. Tried .hasProperty but couldn't get right object reference with in a tree structure like config.
def config = new ConfigSlurper(myenvironment).parse(new File('cfg.groovy').toURL())
def results = config.admin.server
try {
assert results.size != 0
} catch...
cfg.groovy
environments {
dev01 {
admin {
server = 'http://'
port = '1'
}
}
test {
admin {
server = 'http://'
port = '1'
}
}
}

I don't know if there is a better way to do so, but you can check if the generated config object for the passed environment is empty:
def environments = '''
environments {
dev01 {
admin {
server = 'http://'
port = '1'
}
}
test {
admin {
server = 'http://'
port = '1'
}
}
}
'''
def noExists = new ConfigSlurper('noExistEnv').parse(environments)
assert !noExists.isEmpty()
Since noExistEnv doesn't exists this execution shows:
Assertion failed:
assert !noExists.isEmpty()
|| |
|[:] true
false
Trying with an existent environment all works correctly:
def environments = '''
environments {
dev01 {
admin {
server = 'http://'
port = '1'
}
}
test {
admin {
server = 'http://'
port = '1'
}
}
}
'''
def testCfg = new ConfigSlurper('test').parse(environments)
def result = testCfg.admin.server
// check that string is not empty
assert !result.isEmpty()
println result // prints "http://"
Hope it helps,

Related

How to run adonis command in ace command file

const { Command } = require('#adonisjs/ace')
const util = require('util')
const execSync = util.promisify(require('child_process').execSync)
const defaultSeedOrder = []
class SeedSync extends Command {
static get signature () {
return `seed:sync
{
order? : Comma separated of seeds
}`
}
static get description () {
return 'Seeds based on a list instead of running all seeds async.'
}
handle (args, options) {
let seedOrder;
if (args.order !== null) {
seedOrder = args.order.split(/=(.+)/)[1].split(',')
} else {
seedOrder = defaultSeedOrder
}
for (const seed of seedOrder) {
console.log(seed)
execSync(`adonis seed --files='${seed}'`, (e, stdout, stderr) => {
if (!stdout.includes('Seeded database in')) {
this.error(`${this.icon('error')} Error: `)
}
console.log(stdout)
})
}
}
}
module.exports = SeedSync
I want an ace command to run seed sequentially, I have copied this code from here:Link to the original code
But it doesnt seem to work at all for me.
Any help will be much appreciated, Thank you
The problem is with these 2 blocks.
This signature needs to be like this to work and get the order variable correctly:
static get signature () {
return `
seed:sync
{ --order=#value: Run only selected files }
`
}
AND
const exec = execSync(`adonis seed --files='${seed}' --force`, {stdio: 'inherit'})
Remove the commas on --files='${seed}' so that it reads --files=${seed}
Because on the terminal, we call the command using adonis seed:sync --order='' (this single comma is passed to adonis Seed.js and causes the error "Nothing to Seed")

Where do i need to set karate.config.dir to run my tests in multiple environments

My current config file looks something like this:
function() {
var env = karate.env;
karate.log('karate.env system property was:', env);
karate.configure('ssl', true);
if (!env) {
env = 'dev';
}
var config = {
env: env,
internalGateway: 'https://gateway.com.au',
externalGateway: 'https://gateway.com.au',
GatewayManagerURL: 'https://manager.com.au'
}
if (env == 'dev') {
}
else if (env == 'e2e') {
}
return config;
}
This is the only file I have for environments. I am unsure as to how can I run my tests in multiple environments.
Do I need to create a new karate.config.<env>.js file (as per the docs) to run my tests in a new environment?
You need only this one file. Now the config JSON returned has some default values set. What you can do now is have different values for e2e, for example:
else if (env == 'e2e') {
config.internalGateway = 'https://gateway-e2e.com.au';
}
And when you run your tests, you switch environments on the command-line. This is just setting a Java System Property. There are many other ways to do this:
mvn test -DargLine="-Dkarate.env=e2e"
All this is explained here: https://github.com/intuit/karate#switching-the-environment

Issue with Node require in class

I'm fairly new to Node, and writing an app with tests, I faced a scenario, where I don't need to load 2 packages for testing (as it will fail to load the packages as they require some binaries, which won't be present in testing environment). I set an environment variable TEST to true to let the app know that it should't load those 2 packages, and the tests run perfectly. However, for production, I get that the package was not loaded.
This is my class code:
"use strict";
const config = require('../../config/mainConfigs');
...Other constants...
if (typeof process.env.TEST === 'undefined' || process.env.TEST === null){
const mssql = require('mssql');
const oracle = require('oracledb');
if (process.env.DB_PASS && process.env.DB_PASS != '') var db_pass = process.env.DB_PASS;
else if (config.Logging.DB.password != '') var db_pass = config.Logging.DB.password;
else {
console.error(`There's no database password set. Use either Enviroment Variable "DB_PASS" or set "password" under "Logging" > "DB" in configuration file.`);
process.exit(1);
}
}
class db {
constructor(){
this._pool = null;
}
get_pool(){
if (process.env.TEST) return new Promise((resolve)=>resolve());
if (config.Logging.DB.type == 'mssql'){
if (!this._pool) {
this._pool = new mssql.ConnectionPool(sqlDbOptions);
}
if (!this._pool.connected){
return this._pool.connect();
}
else{
return new Promise((resolve, reject) => {
resolve(this._pool);
})
}
}else if (config.Logging.DB.type == 'oracle'){
if (!this._pool || this._pool.connectionsOpen == 0){
return this._pool = oracle.getConnection(oracleDbOptions);
}
else{
return new Promise((resolve, reject) => {
resolve(this._pool);
})
}
}
}
... MORE CLASS OPERATIONS...
}
module.exports = db;
Then I use the DB in my app like this:
const db = require('./db_class');
const db_instance = new db();
When starting the app, I call the get_pool() method to establish the connection prior starting the server.
But for some reason, I am getting:
ReferenceError: mssql is not defined
at db.get_pool (C:\Users...\src\db.js:122:34)
If I move the requires outside the if (the one that checks if the env variable is set) it works just fine.
Aren't the requires synchronous?
Any idea how to solve this?
const is block scoped so your two const variables defined within the if statement block will only be defined and usable within that if statement block.
Basically, you can't conditionally assign to a const like you're trying to do and have the variable available outside the scope of the block. So, you have to settle for using a non-const type (var or let). I recommend using let so you can decide exactly which scope you want it declared in and declaring the variable in that explicit scope. You can then assign to the previously declared variable within your if block.
Here's one usual work-around:
let mssql, oracle;
if (typeof process.env.TEST === 'undefined' || process.env.TEST === null){
mssql = require('mssql');
oracle = require('oracledb');
if (process.env.DB_PASS && process.env.DB_PASS != '') var db_pass = process.env.DB_PASS;
else if (config.Logging.DB.password != '') var db_pass = config.Logging.DB.password;
else {
console.error(`There's no database password set. Use either Enviroment Variable "DB_PASS" or set "password" under "Logging" > "DB" in configuration file.`);
process.exit(1);
}
}

MVC5 and IIS 7.5 Configuration

I have virtual server where is configured IIS 7.5 to works with ASP.NET MVC.
When I deploy application everything works fine. Only one thing is not working when I run application, maybe I'm wrong but I thought that code is correct.
<script>
$(document).ready(function () {
$("#Subcode").prop("disabled", true);
$("#MasterId").change(function () {
if ($("#MasterId").val() != "Select Master Code") {
var CountryOptions = {};
CountryOptions.url = "/Audit/FindSubCode";
CountryOptions.type = "POST";
CountryOptions.data = JSON.stringify({ master_id: $("#MasterId").val() });
CountryOptions.datatype = "json";
CountryOptions.contentType = "application/json";
CountryOptions.success = function (SubCodeList) {
$("#Subcode").empty();
for (var i = 0; i < SubCodeList.length; i++) {
$("#Subcode").append("<option>" + SubCodeList[i] + "</option>");
}
$("#Subcode").prop("disabled", false);
};
CountryOptions.error = function () { alert("Error in Getting SubCodes!!"); };
$.ajax(CountryOptions);
}
else {
$("#Subcode").empty();
$("#Subcode").prop("disabled", true);
}
});
});
</script>
#Html.DropDownList("MasterId",ViewBag.MasterId as SelectList,"Select Master Code",new { #class = "form-control"})
<select id="Subcode"></select>
And code from controller
public JsonResult FindSubCode(int master_id)
{
List<string> SubCodeList = new List<string>();
switch(master_id)
{
case 1:
SubCodeList.Add("Test");
break;
case 2:
SubCodeList.Add("Test2");
break;
}
return Json(SubCodeList);
}
Why I'm writing this problem as IIS Configuration, because if I run locally this application, everything works fine. But when I run on server I got error from code "Error in Getting SubCodes!!".
I tried to debug and get next error: Error when devug
Any suggestion how I can fix this ?
I don't think it has to do with configuration. Verify your URL.
/Audit/FindSubCode would be pointing to the root of the server which may be a different path to where the application is being served from.
Try not to hard code the path but rather use razor engin UrlHelper to generate the path.
CountryOptions.url = "#(Url.Action("FindSubCode","Audit")";

How to add custom services in Nixos

using nixops one can easily configure services like:
{
network.description = "Web server";
webserver = { config, pkgs, ... }:
{
services.mysql = {
enable = true;
package = pkgs.mysql51;
};
but i want to extend services. for example by using override as done for pkgs below:
let
myfoo = callPackage ...
in
pkgs = pkgs.override {
overrides = self: super: {
myfoo-core = myfoo;
};
}
question
how to do that for services?
Adding a service requires that you first write a service definition for your service. That is, a nix file that declares the options of your service and provides an implementation.
Let's say our service is called foo, then we write a service definition for it an save it as the file foo.nix:
{ config, lib, pkgs, ... }:
with lib; # use the functions from lib, such as mkIf
let
# the values of the options set for the service by the user of the service
foocfg = config.services.foo;
in {
##### interface. here we define the options that users of our service can specify
options = {
# the options for our service will be located under services.foo
services.foo = {
enable = mkOption {
type = types.bool;
default = false;
description = ''
Whether to enable foo.
'';
};
barOption = {
type = types.str;
default = "qux";
description = ''
The bar option for foo.
'';
};
};
};
##### implementation
config = mkIf foocfg.enable { # only apply the following settings if enabled
# here all options that can be specified in configuration.nix may be used
# configure systemd services
# add system users
# write config files, just as an example here:
environment.etc."foo-bar" = {
text = foocfg.bar; # we can use values of options for this service here
};
};
For example, for Hydra, this file can be found here: https://github.com/NixOS/hydra/blob/dd32033657fc7d6a755c2feae1714148ee43fc7e/hydra-module.nix.
After having written the service definition, we can use it our main configuration like this:
{
network.description = "Web server";
webserver = { config, pkgs, ... }: {
imports = [ ./foo.nix ]; # import our service
services.mysql = {
enable = true;
package = pkgs.mysql51;
};
services.foo = {
enable = true;
bar = "hello nixos modules!";
};
};
}
Disclaimer: there might be some typos in this, I have not tested it.
according to aszlig, we can do this:
configuration.nix
{ config, lib, ... }:
{
disabledModules = [ "services/monitoring/nagios.nix" ];
options.services.nagios.enable = lib.mkOption {
# Make sure that this option type conflicts with the one in
# the original NixOS module for illustration purposes.
type = lib.types.str;
default = "of course";
description = "Really enable nagios?";
};
config = lib.mkIf (config.services.nagios.enable == "of course") {
systemd.services.nagios = {
description = "my own shiny nagios service...";
};
};
}
evaluate it
$ nix-instantiate --eval '<nixpkgs/nixos>' --arg configuration ./test-disable.nix -A config.systemd.services.nagios.description
"my own shiny nagios service..."

versus without disabledModules:
$ nix-instantiate --eval '<nixpkgs/nixos>' --arg configuration ./test-disable.nix -A config.systemd.services.nagios.description
error: The option `services.nagios.enable' in `/home/aszlig/test-disable.nix' is already declared in `/nix/var/nix/profiles/per-user/root/channels/vuizvui/nixpkgs/nixos/modules/services/monitoring/nagios.nix'.
(use '--show-trace' to show detailed location information)

Resources