How does gauge_clear_state_level work with Javascript and Typescript? - getgauge

I am trying to understand how Gauge handles concurrent execution of tests and how it manages state. However, I don't get it how gauge_clear_state_level is supposed to work. I have created two small examples in Javascript and also Typescript and for both I don't see any effect.
In my default.properties it is set as follows:
...
gauge_clear_state_level = scenario
...
This is my test specification:
# Example specification A
## Example scenario A1
* foo "A1"
* bar "A1"
* foo "A1"
## Example scenario A2
* bar "A2"
* foo "A2"
* bar "A2"
The implementation in Typescript looks like this:
import { Step } from "gauge-ts";
export default class StepImplementation {
private fooCounter: number = 0;
private barCounter: number = 0;
#Step("foo <x>")
public async foo(x: string) {
await delay(1000);
this.fooCounter++;
console.log("foo " + x + " (" + this.fooCounter + ")")
}
#Step("bar <x>")
public async bar(x: string) {
await delay(1000);
this.barCounter++;
console.log("bar " + x + " (" + this.barCounter + ")")
}
}
// https://stackoverflow.com/a/37764963
function delay(ms: number) {
return new Promise( resolve => setTimeout(resolve, ms) );
}
When I run the specification, the output is:
Running tool: gauge.cmd run c:\....\specs\exampleA.spec --simple-console --hide-suggestion
"Windows support is not tested yet. There might be some issues."
# Example specification A
## Example scenario A1
foo A1 (1)
bar A1 (1)
foo A1 (2)
## Example scenario A2
bar A2 (2)
foo A2 (3)
bar A2 (3)
Successfully generated html-report to => c:\....\reports\html-report\index.html
Specifications: 1 executed 1 passed 0 failed 0 skipped
Scenarios: 2 executed 2 passed 0 failed 0 skipped
Total time taken: 6.424s
Success: Tests passed.
What I would have expected is that both counters are reset after each scenario but the output above shows that this is not the case.
Any ideas or suggestions anyone?

I did some more investigation and digged into the code of respective Gauge language runners. I did not find any usage of the gauge_clear_state_level property. I raised an issue in the Gauge project to update the documentation accordingly. They confirmed my findings and will remove the gauge_clear_state_level property from the documentation.
https://github.com/getgauge/docs.gauge.org/issues/291
The gauge_clear_state_level property is language specific, currently it is only supported by Java and .NET language runners. For all other languages one can use Data Stores to control the lifecycle of state information.

Related

How to print more than one value in the same line?

A simple example
Print("This is a number {0}", 1) // results in 4
How can I print 1 2 3 in the same line?
I have tried
Print(1, 2, 3) // Does not work
The forloop also does not work.
The while loop below prints the elements but each in a separate line since we do not have control over the line feed character \n:
fn Main() -> i32 {
var a: [i32;3] = (1, 2, 3); // Define array containing the numbers 1,2,3
var i:i32 =0;
while(i<3){
Print("{0}", a[i]);
i= i+1;
}
return 0;
}
which results in
1
2
3
here is the code
How can I get 1 2 3?
Short explanation: Providing more than 2 arguments to Print is currently not supported, so is not including a line break.
Details
This is definitely something that will change in the future, as the language is in its early design phases. You can find the source for Print as an instrinsic (non-carbon native) here: https://github.com/carbon-language/carbon-lang/blob/trunk/explorer/interpreter/type_checker.cpp#L2297
case IntrinsicExpression::Intrinsic::Print:
// TODO: Remove Print special casing once we have variadics or
// overloads. Here, that's the name Print instead of __intrinsic_print
// in errors.
if (args.size() < 1 || args.size() > 2) {
return CompilationError(e->source_loc())
<< "Print takes 1 or 2 arguments, received " << args.size();
}
CARBON_RETURN_IF_ERROR(ExpectExactType(
e->source_loc(), "Print argument 0", arena_->New<StringType>(),
&args[0]->static_type(), impl_scope));
if (args.size() >= 2) {
CARBON_RETURN_IF_ERROR(ExpectExactType(
e->source_loc(), "Print argument 1", arena_->New<IntType>(),
&args[1]->static_type(), impl_scope));
}
If you look at the code you will also see that the type of input variable is limited to just integer types. It would be easy enough create a PR to manually add support for 2-3 if you want :)

updated groovy and spock causes propertymissing and methodmissing invocation problems

I updated (migrating) Groovy to 3.0.4 and Spock to 2.0-M3-groovy-3.0. No other changes were made to relevant classes. The tests and code have all been in place for many years and are run regularly. What is being tested is an application the collects job run statistics. It does so dynamically as this needs to work for many different jobs, each of which may need a different set of counters.
When I run the tests with the aforementioned library upgrade, I am getting failures. For example:
Too many invocations for:
0 * _ (1 invocation)
Matching invocations (ordered by last occurrence):
1 * mockCounter.methodMissing('getFailureCount', []) <-- this triggered the error
Nothing has changed, as I stated, other than library versions. Here is the test code (to make clear per kriegaex reply below, this is the test in it's entirety - I somehow left the when clause outside the code block):
when:
postProcessor.run()
then:
1 * mockContext.getOrCreateCounter('MyCategory') >> mockCounter
1 * mockContext.getOrCreateCounter('MyProductPage') >> mockPageCounter
1 * mockCounter.propertyMissing('failureCount') >> 1
1 * mockLogger.info('MyProductDeleteProcessor exited due to failures')
0 * _
What is interesting to me, and puzzling, is that the methodMissing('getFailureCount', []) is a getter for the property I am mocking.
So, I can add that method to get rid of the missing method exception - something that seems wrong - (and two more) and now my test looks like:
when:
postProcessor.run()
then:
1 * mockContext.getOrCreateCounter('MyCategory') >> mockCounter
1 * mockContext.getOrCreateCounter('MyProductPage') >> mockPageCounter
1 * mockCounter.propertyMissing('failureCount') >> 1
1 * mockCounter.methodMissing('getFailureCount', [])
1 * mockCounter.methodMissing('getRecoveryCount', [])
1 * mockPageCounter.methodMissing('getTotalCount', [])
1 * mockLogger.info('MyProductDeleteProcessor exited due to failures')
0 * _
This then leads to:
Too few invocations for:
1 * mockCounter.propertyMissing('failureCount') >> 1
What the? I clearly mocked that! So I remove that line and now my test looks like:
when:
postProcessor.run()
then:
1 * mockContext.getOrCreateCounter('MyCategory') >> mockCounter
1 * mockContext.getOrCreateCounter('MyProductPage') >> mockPageCounter
1 * mockCounter.methodMissing('getFailureCount', [])
1 * mockCounter.methodMissing('getRecoveryCount', [])
1 * mockPageCounter.methodMissing('getTotalCount', [])
1 * mockLogger.info('MyProductDeleteProcessor exited due to failures')
0 * _
I then get:
Too many invocations for:
0 * _ (1 invocation)
Matching invocations (ordered by last occurrence):
1 * mockCounter.methodMissing('getFailureCount', [])
That makes no sense to me. I mocked it, as stated above. What am I missing?
The comment by kriegaex states he wants the code to the class under test. This could lead to potentially confusion and a lot of code. So I have below the partial set code from our JobStatsCounter counter, specifically the constructor and the two methods for handling missing properties and methods.
public JobStatsCounter(String whatWeAreTracking, List<String> extraMetrics = ['total', 'success', 'failure', 'unmodified', 'deleted', 'recovery', 'ignored']) {
this.whatWeAreTracking = whatWeAreTracking
extraMetrics.each {
this.extraMetrics.put(it, new AtomicLong())
}
}
void methodMissing(String methodName, def args) {
if (methodName.startsWith('job')) {
String metric = StringUtils.uncapitalize(methodName - 'job')
AtomicLong counter = extraMetrics.putIfAbsent(metric, new AtomicLong())
if (counter == null) {
counter = extraMetrics.putIfAbsent(metric, new AtomicLong())
}
counter.incrementAndGet()
return
}
throw new NoSuchMethodError("Got a request for undefined method '$methodName'")
}
long propertyMissing(String property) {
if (property.endsWith('Count')) {
String metric = property - 'Count'
if (extraMetrics.containsKey(metric)) {
return extraMetrics[metric].get()
}
throw new NoSuchFieldError("Got a request for metric '$property', but there is no metric called '${metric}'")
}
throw new NoSuchFieldError("Got a request for undefined property '$property'")
}

Define 2 switchable implementations of the same functions in NodeJS / Express

I have a bunch of field to calculate, and I have 3 cases.
Fields are mostly the same, but there is some differences.
Also, calculation to obtain each field may depend on differents variable, so function may have different signature.
In other languages, I would define an interface, use constructors using interface instead of concrete class and use dependency injection.
In nodeJS, I'm a newbie, and I saw there is no such thing that interfaces.
To take a concrete example, I must calculate
I have 2 case:
case sup36 === true
fixedRouting = (CG + CC + CSF * subscribedPower) / 12
case sup36 === false
fixedRouting = (CG + CC) / 12 + subscribedPower * billedCSFCoef * numDayInPeriod / 100
Right now, I add a parameter:
getFixedRouting(isSup36, CG, CC, subscribedPower, billedCSFCoef, numDayInPeriod) {
if isSup{
return (CG + CC + CSF * subscribedPower) / 12
}else{
return (CG + CC) / 12 + subscribedPower * billedCSFCoef * numDayInPeriod / 100
}
},
Problem is I will have more than 2 cases, and I will have to code more cases in the future. This way of coding will also increase the complexity of my code.
How should I do to be able to have 2 switchable implementations of getFixedRouting(...) ?
You can either have different functions for the different cases like this:
function getFixedRoutingSup36(CG, CC, subscribedPower) {
return (CG + CC + CSF * subscribedPower) / 12;
}
function getFixedRoutingNonSup36(CG, CC, subscribedPower, billedCSFCoef, numDayInPeriod) {
return (CG + CC) / 12 + subscribedPower * billedCSFCoef * numDayInPeriod / 100;
}
This can be helpful if the parameters sent to each differ greatly (for example above the sup36 case does not need or use billedCSFCoef or numDayInPeriod).
If you like having one entry point for all of this you can still have the functions split above like that but have this one entry point that you tell people to use:
function getFixedRouting(dataType, CG, CC, subscribedPower, billedCSFCoef, numDayInPeriod) {
switch (dataType) {
case 1:
return getFixedRoutingSup36(CG, CC, subscribedPower);
case 2:
return getFixedRoutingNonSup36(CG, CC, subscribedPower, billedCSFCoef, numDayInPeriod);
case 3:
return someOtherFunction();
}
}
The drawback here is that if your variety of cases take a different set of parameters it can get ugly.
Another variant is to pass the parameters as a Javascript Object so the contents can vary:
function getFixedRouting(data) {
switch (data.type) {
case 1:
return getFixedRoutingSup36(data.CG, data.CC, data.subscribedPower);
case 2:
return getFixedRoutingNonSup36(data.CG, data.CC, data.subscribedPower, data.billedCSFCoef, data.numDayInPeriod);
case 3:
return someOtherFunction();
}
}

Please help me with this C# code

Why is the output of the given 200 and not 20000 as I had expected ????
Please help me on this !!!
class Program
{
static void Main(string[] args)
{
mukul x = new mukul();
x.b= 200;
Console.WriteLine(Convert.ToString(x.calculate));
Console.ReadLine()
}
}
class mukul
{
public int b;
public int calculate
{
get { return b; }
set { b = value * 100; }
}
}
You're setting x.b directly - you're not using the calculate setter, so it's not multiplying by 100.
If you changed this line:
x.b = 200;
to this:
x.calculate = 200;
then it would act as you expect.
There are several points to make though:
If you indent your code properly, it will make it easier to read
If your b field were private, you couldn't have set it directly. Fields should almost always be private.
You should follow normal .NET naming conventions (PascalCase for properties and types, for example)
Your property is very odd. It's very unusual for code like this:
x.calculate = x.calculate;
to actually make a difference. I would rethink your design if I were you.
If you're calling Console.WriteLine, there's already an overload to handle an int value, and even if there weren't the value could be boxed to object instead. So your code would be written more simply as:
Console.WriteLine(x.calculate);
In this " x.b= 200;" you calling only "b" variable.not "calculate" method.So every time you get the 200 as output with out performing calculate method.
For better understanding
Take two breakpoints at the below two instructions
get { return b; }
set { b = value * 100; }
Then perform stepinto debug(press F11) for the two instructons like "x.b=200" and "x.claculate=200".Then observe the difference between "x.b=200" and "x.claculate=200"
In x.b=200
"set{b=value*100;}"method cant execute.That means b=value*100 not executed.So every time you get "200" as output.
In x.calculate=200
"set{b=value*100;}"method is executed.That means b assigned with value*100.So you get "20000" as output.
Finally you have to call method("calculate") not variable("b").
Hope you got the answer.Have a happy Programming........

print the closure definition/source in Groovy

Anyone who knows how the print the source of a closure in Groovy?
For example, I have this closure (binded to a)
def a = { it.twice() }
I would like to have the String "it.twice()" or "{ it.twice() }"
Just a simple toString ofcourse won't work:
a.toString(); //results in: Script1$_run_closure1_closure4_closure6#12f1bf0
short answer is you can't. long answer is:
depending on what you need the code for, you could perhaps get away with
// file: example1.groovy
def a = { it.twice() }
println a.metaClass.classNode.getDeclaredMethods("doCall")[0].code.text
// prints: { return it.twice() }
BUT
you will need the source code of the script available in the classpath AT RUNTIME as explained in
groovy.lang.MetaClass#getClassNode()
"Obtains a reference to the original
AST for the MetaClass if it is
available at runtime
#return The
original AST or null if it cannot be
returned"
AND
the text trick does not really return the same code, just a code like representation of the AST, as can be seen in this script
// file: example2.groovy
def b = {p-> p.twice() * "p"}
println b.metaClass.classNode.getDeclaredMethods("doCall")[0].code.text
// prints: { return (p.twice() * p) }
still, it might be useful as it is if you just want to take a quick look
AND, if you have too much time on your hands and don't know what to do you could write your own org.codehaus.groovy.ast.GroovyCodeVisitor to pretty print it
OR, just steal an existing one like groovy.inspect.swingui.AstNodeToScriptVisitor
// file: example3.groovy
def c = {w->
[1,2,3].each {
println "$it"
(1..it).each {x->
println 'this seems' << ' somewhat closer' << ''' to the
original''' << " $x"
}
}
}
def node = c.metaClass.classNode.getDeclaredMethods("doCall")[0].code
def writer = new StringWriter()
node.visit new groovy.inspect.swingui.AstNodeToScriptVisitor(writer)
println writer
// prints: return [1, 2, 3].each({
// this.println("$it")
// return (1.. it ).each({ java.lang.Object x ->
// return this.println('this seems' << ' somewhat closer' << ' to the \n original' << " $x")
// })
// })
now.
if you want the original, exact, runnable code ... you are out of luck
i mean, you could use the source line information, but last time i checked, it wasn't really getting them right
// file: example1.groovy
....
def code = a.metaClass.classNode.getDeclaredMethods("doCall")[0].code
println "$code.lineNumber $code.columnNumber $code.lastLineNumber $code.lastColumnNumber"
new File('example1.groovy').readLines()
... etc etc you get the idea.
line numbers shuld be at least near the original code though
That isn't possible in groovy. Even when a groovy script is run directly, without compiling it first, the script is converted into JVM bytecode. Closures aren't treated any differently, they are compiled like regular methods. By the time the code is run, the source code isn't available any more.

Resources