Determine if SoapUI (ReadyAPI) is started via testrunner.bat or by the user (running in UI-mode) - batch-file

Is it possible to determine if SoapUI (ReadyAPI) is started
via testrunner.bat
by the user (running in interactive UI-mode)
I know that you can retrieve the current environment using this groovy script code:
def env = testRunner.testCase.testSuite.project.activeEnvironment.name
However I wonder what value this will return when running via the command-line (testrunner.bat) ; will it return the active environment from the test project, or will it be null/empty ?
Update (use-case)
The user case is that depending on the way the tests are run. In case of testrunner.bat I want to be able to set the environment to a fixed value. Else I want enable the user to select the environment manually.
Note that the some environment settings like EndPoints for each environment are defined a pre-defined XML file.
Update (possible solution)
#albciff
On the latest version from ReadyAPI (1.9.0), this does not work as you described.
testrunner.bat returns SoapUIProTestCaseRunner
running via ui returns InProcessSoapUIProTestCaseRunner
When using this code:
def runner = com.eviware.soapui.SoapUI.getCmdLineRunner();
log.info "runner = [" + runner.getClass().getSimpleName() + "]"

A more easier way to detect this would be:
if (com.eviware.soapui.SoapUI.isCommandLine()) {
// todo
}
Found at community.smartbear.com

I think that there is no property inside SOAPUI to difference between how it's executed. In fact I test your proposal:
def env = testRunner.testCase.testSuite.project.activeEnvironment.name
And it returns Default for both cases (from UI and using testrunner).
A possible workaround to do so, it's for example to pass a project property parameter in the CLI of the testrunner execution; and then in your code check for this parameter to detect how the project is launched.
To pass a project property you've to use -Pname=value. So for example launch the testrunner using:
testrunner -r -I <path/To/yourProject.xml> -PrunningBy=testRunner
And then in your code you can get the property and check for this content to decide if it's running by testrunner or from the UI, something like:
def runningBy = testRunner.testCase.testSuite.project.getPropertyValue('runningBy')
if(runningBy){
// it's not null so is launched from testRunner
}else{
// it's null, so is launched from UI
}
UPDATE
After reviewing the API seems that it's possible thought the follow method:
com.eviware.soapui.SoapUI.getCmdLineRunner()
It returns null when executed from UI, instead when executed from testrunner it returns and instance of com.eviware.soapui.tools.CmdLineRunner.
So you can use something like:
def clr = com.eviware.soapui.SoapUI.getCmdLineRunner()
if(clr){
// it's not null so is launched from testRunner
}else{
// it's null, so is launched from UI
}

Related

Using dispatcher to invoke on another thread - Config/Settings is not threadsafe in .Net Core 3.1

Issue:
I am trying to update the GUI from a second thread.
Unfortunately the label stays the same. At first I thought there is an issue with the dispatcher but it works fine. It appears that the configuration is not threadsafe!
Code to reproduce:
I have a Settings File which is mainly used to keep variables persistent during application relaunches:
this is the Update code:
// get the amount of tickets created for me last week
int amountOftickets = JiraInterface.DayStatisticsGenerator.GetLastWeeksTicketAmount();
config.Default.Lastweekstickets = amountOftickets; // int == 12;
// Update GUI on GUI thread
mainWindow.Dispatcher.Invoke(() =>
{
mainWindow.SetIconsAccordingtoConfig();
mainWindow.NumberTicketsCreated.Content = config.Default.Lastweekstickets.ToString(); // int == 0!!
});
Does anyone have an Idea on how to shove the running configuration from the thread who updated it to the Gui thread?
After a quick look in the documentation, it seems that you have 2 options:
You can either use the Dispatcher.Invoke to set your config.Default
on GUI thread.
It seems that .NET Core and .NET Framework support synchronized SettingsBase which is what the Configs are ( https://learn.microsoft.com/en-us/dotnet/api/system.configuration.settingsbase.synchronized?view=netcore-3.0 )
EDIT 1:
Looking into the C# Properties more, it seems that if you look in your config file in Visual Studio under:
Properties -> Config.settings -> Config.Designer.cs
During the class initialization it seems that .NET Framework, already uses Synhronized property which should make the config thread safe
private static Config defaultInstance = ((Config)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Config())));
It could be that when you created this file, Synchronized wasn't used, so your config file isn't thread safe, especially if it was created in code and not designer/properties
From Microsoft Docs on SettingsBase Synchronized:
The indexer will get and set property data in a thread-safe manner if the IsSynchronized property is set to true. A SettingsBase instance by default is not thread-safe. However, you can call Synchronized passing in a SettingsBase instance to make the SettingsBase indexer operate in a thread-safe manner.

Need to supply DB password to run evolutions at run time - Play + Slick

I need to avoid storing plain text passwords in config files, and so I'm storing the Postgres password externally (in AWS Secrets Manager).
Similarly to the solution provided here:
Encrypted database password in Play + Slick + HikariCP application, I've been able to override dbConfig and supply the password to my DAO classes like this:
trait MyDaoSlick extends MyTableDefinitions with HasDatabaseConfig[MyPostgresDriver] {
protected val dbConfigProvider: DatabaseConfigProvider
override protected val dbConfig: DatabaseConfig[MyPostgresDriver] = secretDbConfig(dbConfigProvider)
def secretDbConfig(dbConfigProvider: DatabaseConfigProvider): DatabaseConfig[MyPostgresDriver] = {
DatabaseConfig.forConfig[MyPostgresDriver]("", dbConfigProvider.get[MyPostgresDriver].config
.withValue("db.user", ConfigValueFactory.fromAnyRef(getUN))
.withValue("db.password", ConfigValueFactory.fromAnyRef(getPWD)))
}
}
This works great for regular DB queries, however evolutions bypass this and still expect the username and the password to be in application.conf, which kind of defeats the purpose of the password being a secret.
Any advice on how evolutions could get the DB credentials from a function?
I ran into the same issue, and I managed to resolve it like this:
Create a custom application loader, as shown here: https://www.playframework.com/documentation/2.7.x/ScalaDependencyInjection#Advanced:-Extending-the-GuiceApplicationLoader
Inside the custom loader's builder, append the DB configuration parameters for Slick:
val extra = Seq(
"slick.dbs.default.db.url" -> secrets.url,
"slick.dbs.default.db.user" -> secrets.user,
"slick.dbs.default.db.password" -> secrets.pass
)
Nothing else needs to be changed, as you've basically added the configuration needed for anything Slick, evolutions included.
On older versions of Play, we used to do this inside GlobalSettings.onLoadConfig, but, at some point, that has been deprecated in favour of DI. More details here: https://www.playframework.com/documentation/2.7.x/GlobalSettings

Turn off Hystrix functionality

I am integrating Hystrix in an application. That application is already in production and we will be testing out hystrix integration work in sandbox before we will push it to production.
My question is that is there any way to turn on/off hystrix functionality using some configuration setting?
There is no single setting for this. You'll need to set multiple parameters to disable Hystrix.
See https://github.com/Netflix/Hystrix/wiki/Configuration for the configuration options:
hystrix.command.default.execution.isolation.strategy=SEMAPHORE
hystrix.command.default.execution.isolation.semaphore.maxConcurrentRequests=100000 # basically 'unlimited'
hystrix.command.default.execution.timeout.enabled=false
hystrix.command.default.circuitBreaker.enabled=false
hystrix.command.default.fallback.enabled=false
Please double check your version of Hystrix for the available parameters.
This is all what you need:
# Disable Circuit Breaker (Hystrix)
spring:
cloud:
circuit:
breaker:
enabled: false
hystrix:
command:
default:
circuitBreaker:
enabled: false
As ahus1 said, there is no single way to disable Hystrix entirely. To disable it in our application, we decided it was cleanest and safest to put a HystrixCommand in a wrapper class, and that wrapper class only exposed the parts of the HystrixCommand that we used (in our case, the execute() method). When constructing the wrapper class, we pass it a Callable that contains the code we want executed, and if Hystrix is disabled (according to our own config value), we simply call that Callable without ever creating a HystrixCommand. This avoids executing any Hystrix code whatsoever and makes it easier to say that Hystrix isn't affecting our application at all when it's disabled.
There are a couple of ways to achieve this-
Doing this for your every group including default. Although this will not disable hystrix(it will only keep the circuit closed all the time) but you will achieve the same result-
hystrix.command.{group-key}.circuitBreaker.forceClosed=false
If you are using java, you can create an around advice over #HystrixCommand annotation and bypass hystrix execution based upon a flag.
Java Code for #2-
#Pointcut("#annotation(com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand)")
public void hystrixCommandAnnotationPointcut() {
}
#Around("hystrixCommandAnnotationPointcut()")
public Object methodsAnnotatedWithHystrixCommand(final ProceedingJoinPoint joinPoint) throws Throwable {
Object result = null;
Method method = AopUtils.getMethodFromTarget(joinPoint);
if ((System.getProperty(enable.hystrix).equals("true")) {
result = joinPoint.proceed();
} else {
result = method.invoke(joinPoint.getTarget(), joinPoint.getArgs());
}
return result;
}
If your Project is spring Managed you can comment the bean definition of hystrixAspect in applicationContext.xml
Comment the following line
bean id="hystrixAspect"class="com.netflix.hystrix.contrib.javanica.aop.aspectj.HystrixCommandAspect"/>
This will remove Hystrix from your project.
I ran into this situation where I wanted to completely turnoff Hystrix using a single property (We use IBM uDeploy to manage dynamic properties). We are using javanica library built on top of Hystrix
Create a Configuration class which creates the HystrixCommandAspect
#Configuration
public class HystrixConfiguration{
#Bean(name = "hystrixCommandAspect")
#Conditional(HystrixEnableCondition.class)
public HystrixCommandAspect hystrixCommandAspect(){
return new HystrixCommandAspect()}
}
2. And the conditional class would be enabled based on a system property.
public class HystrixEnableCondition implements Condition{
#Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata){
return
"YES".equalsIgnoreCase(
context.getEnvironment().getProperty("circuitBreaker.enabled")) ||
"YES".equalsIgnoreCase(
System.getProperty("circuitBreaker.enabled"));
}
}
setting
hystrix.command.default.execution.isolation.strategy=SEMAPHORE
is enough.
Additionally you may or should disable also the timeout threads
with hystrix.command.default.execution.timeout.enabled=false

Specflow - Log steps - Given/When /Then steps logging

We run nightly regression scripts using Specflow. Was wondering if there is a way to log the specflow console logs to a file. Since it runs at night, we are not sure about the step where the failure occurred.We do use ReportUnit to convert the nunit xml to html. Will be good to have those console logs in the html too.
you can add hooks which execute before scenario steps ([BeforeStep] and [AfterStep]) and log in there. You can access the ScenarioStepContext to get details of the current step.
A lot has changed with SpecFlow in the last 6 years. Specifically SpecFlow logs each step (along with whether it passes or fails) to the standard output. You can also generate test results files using whichever unit test framework you want. That being said, I did come across a use case where the existing logging that SpecFlow does was not working with Azure DevOps. For my case, I had passing tests, which periodically ran extremely slow. In Azure DevOps release pipelines, a passing test does not get the standard output saved for viewing later. I needed to log the date/time for when a step began, and when it finished.
A before/after step hook using the ScenarioContext object was how I got this logging to work:
[Binding]
public class Hooks
{
[BeforeStep]
public void BeforeStep(ScenarioContext scenario)
{
var stepInfo = scenario.StepContext.StepInfo;
var stepText = $"{stepInfo.StepDefinitionType} {stepInfo.Text}";
// log 'stepText' some place
}
[AfterStep]
public void AfterStep(ScenarioContext scenario)
{
var stepInfo = scenario.StepContext.StepInfo;
var stepText = $"{stepInfo.StepDefinitionType} {stepInfo.Text}";
// log 'stepText' some place
}
}

Grails 2.4.4 Multiple datasources, separate drivers, IntegrationSpec

I am attempting to use multiple datasources in a Grails 2.4.4 project. According to the docs, this should be possible:
http://www.grails.org/doc/2.4.4/guide/conf.html#multipleDatasources
My primary dataSource (the one I want to use for all domain classes) is using H2 at the moment, as configured by the default DataSource.groovy configuration. My second, read-only datasource is SQL Server, and I tried to declare it as follows at the top level of my DataSource.groovy config (shared by all environments):
ds {
pooled = true
dialect = "org.hibernate.dialect.SQLServer2008Dialect"
driverClassName = "net.sourceforge.jtds.jdbc.Driver"
url = "jdbc:jtds:sqlserver://myserver:1433/mydb;domain=mydomain;useNTLMv2=true;user=myuser"
dbCreate = "none"
}
(Don't let the URL throw you off - I'm just having to use Windows Auth with JTDS. I've tested this via third-party clients as well.)
I inject this into my service class and use it, and everything appears to hook up well:
def dataSource_ds
def serviceMethod(){
Sql ds = new Sql(dataSource_ds)
String query = "SELECT ... "
def results = ds.rows(query)
println "Results are ${results.size()}"
return "Some value"
}
But when I try to access this from an IntegrationSpec-backed Integration Test, I noticed that I was getting "schema not found" errors for valid schemas referred to by my query string, such as "dbo". And the stack trace of any errors from this setup looks like this:
org.h2.jdbc.JdbcSQLException: Schema "DBO" not found; SQL statement:
...
at org.h2.message.DbException.getJdbcSQLException(DbException.java:329)
at org.h2.message.DbException.get(DbException.java:169)
at org.h2.message.DbException.get(DbException.java:146)
at org.h2.command.Parser.readTableOrView(Parser.java:4774)
at org.h2.command.Parser.readTableFilter(Parser.java:1083)
at org.h2.command.Parser.parseSelectSimpleFromPart(Parser.java:1689)
at org.h2.command.Parser.parseSelectSimple(Parser.java:1796)
at org.h2.command.Parser.parseSelectSub(Parser.java:1683)
at org.h2.command.Parser.parseSelectUnion(Parser.java:1526)
at org.h2.command.Parser.parseSelect(Parser.java:1514)
at org.h2.command.Parser.parsePrepared(Parser.java:404)
at org.h2.command.Parser.parse(Parser.java:278)
at org.h2.command.Parser.parse(Parser.java:250)
at org.h2.command.Parser.prepareCommand(Parser.java:217)
at org.h2.engine.Session.prepareLocal(Session.java:414)
at org.h2.engine.Session.prepareCommand(Session.java:363)
...
Now why would THIS datasource be trying to use the H2 driver?
In case it's relevant, my Integration test looks like this:
void "serviceMethod" () {
when: "service method is called"
String response = myService.serviceMethod()
then: "we should get the appropriate text back"
response.equals("Some value")
}
If, in the Service class, I hard-code the connection using a constructor of the Groovy Sql object, the integration test works fine, and any stack traces go through the JTDS driver.But when I try to use the injected datasource, things are strange.
Any idea what I'm doing wrong here?
Just to close the loop on this and hopefully save someone pain on this oversight in the future:
Grails uses an in-memory database when running tests. Make sure to read up on the other differences between integration tests and production here:
http://www.grails.org/doc/latest/guide/testing.html#integrationTesting
This feature makes the use of external (read-only) datasources during any tests pretty interesting, but some of that is to be expected (a test which depends on an external datasource is not a very good test in the long run). I hope to refactor my app and its testing approach at some point (e.g., to use a simple DAO and mock that during the test), because I don't really care about asserting the contents of the external datasource from my app's tests.

Resources