In Cucumber (the ruby version) you can easily call steps from other steps and thus build hierarchical libraries of steps making it easy to write the Gherkin feature specifications in the most generic terms.
However it is not readily apparent how to do this in Cucumber-JVM and I have been unable to find documentation for it.
Let me be clear I am not interested in calling the step implementation function directly because I don't want to have to know what its signature is, nor to change the call every time the implementation changes.
Rather, I want to pass an arbitrary string that will go through the regex matcher and automatically find the matching step and execute it. Just as the engine runs all steps.
simple example of what I would expect syntax to look like to define synonym "logout":
When("user logs out") { () =>
d.executeScript("logout();")
}
When("logout") { () =>
Step("user logs out")
}
This functionality is not supported in Cucumber-JVM. (Note that the Cucumber Backgrounder document you link in your question describes using Steps within Steps as "an anti-pattern")
Essentially, we believe that Cucumber is a collaboration tool and that Gherkin is not a programming language.
You can see a longer discussion of how we arrived at this decision here
To call steps within step definitions, inherit cuke4duke.Steps in java
import cuke4duke.StepMother;
import cuke4duke.Steps;
import cuke4duke.annotation.I18n.EN.When;
public class CallingSteps extends Steps {
public CallingSteps(StepMother stepMother) {
super(stepMother);
}
#When("^I call another step$")
public void iCallAnotherStep() {
Given("it is magic"); // This will call a step defined somewhere else.
}
}
Example:
https://github.com/cucumber-attic/cuke4duke/blob/master/examples/java/src/test/java/simple/CallingSteps.java
Note: cuke4duke support scala as well
Calling steps within steps is a terrible anti-pattern that can easily be replaced by something much simpler.
Instead of one step calling another step, have both steps call the same helper method.
If you apply this pattern with rigour you and up with
step definitions that are all just single calls to helper methods
a suite of helper methods that collectively provide a test-api
The art of elegantly implementing your Cucumber scenarios now becomes a known programming problem as all your functionality is now directly in code in your programming language rather than being in some restrictive construct specific to Cucumber.
You can now
refactor your helper methods to provide cleaner interaces
use parameters to give methods greater power
use naming to give all your calls greater clarity
use a helper method as an entry point to a suite of extra functionality
use delegation to move functionality out of helper methods and into test service objects
...
Providing this separation can be initially challenging if you are not a programmer or not experienced in the particular programming language in use. However once you get past this initial hurdle the code you can and should produce will be much easier to work with than the tangled mess that inevitably occurs with step nesting.
In Cucumber each Step is a Method. That way, you can call other methods in any step that you want.
#When("^click on \"([^\"]*)\"$")
public void clickOn(String arg1) throws Throwable {
driver.findElement(By.linkText(arg1)).click();
}
#Then("^should see the static elements changing$")
public void shouldSeeTheStaticElementsChanging() throws Throwable {
clickOn();
}
Related
Let's assume we have a function that returns a list of apples in our warehouse:
List<Apple> getApples();
After some lifetime of the application we've found a bug - in rare cases clients of this function get intoxication because some of the apples returned are not ripe yet.
However another set of clients absolutely does not care about ripeness, they use this function simply to know about all available apples.
Naive way of solving this problem would be to add the 'ripeness' member to an apple and then find all places where ripeness can cause problems and put some checks.
const auto apples = getApples();
for (const auto& apple : apples)
if (apple.isRipe())
consume(apple)
However, if we correlate this new requirement of having ripe apples with the way class interfaces are usually designed, we might find out that we need new interface which is a subset of a more generic one:
List<Apple> getRipeApples();
which basically extends the getApples() interface by filtering the ones that are not ripe.
So the questions are:
Is this correct way of thinking?
Should the old interface (getApples) remain unchanged?
How will it handle scaling if later on we figure out that some customers are allergic to red/green/yellow apples (getRipeNonRedApples)?
Are there any other alternative ways of modifying the API?
One constraint, though: how do we minimize the probability of inexperienced/inattentive developer calling getApples instead of getRipeApples? Subclass the Apple with the RipeApple? Make a downcast in the getRipeApples?
A pattern found often with Java people is the idea of versioned capabilities.
You have something like:
interface Capability ...
interface AppleDealer {
List<Apples> getApples();
}
and in order to retrieve an AppleDealer, there is some central service like
public <T> T getCapability (Class<T> type);
So your client code would be doing:
AppleDealer dealer = service.getCapability(AppleDealer.class);
When the need for another method comes up, you go:
interface AppleDealerV2 extends AppleDealer { ...
And clients that want V2, just do a `getCapability(AppleDealerV2.class) call. Those that don't care don't have to modify their code!
Please note: of course, this only works for extending interfaces. You can't use this approach neither to change signatures nor to remove methods in existing interfaces.
Regarding your question 3/4: I go with MaxZoom there, but to be precise: I would very much recommend for "flags" to be something like List<String>, or List<Integer> (for 'real' int like flags) or even Map<String, Object>. In other words: if you really don't know what kind of conditions might come over time, go for interfaces that work for everything: like one where you can give a map with "keys" and "expected values" for the different keys. If you go for pure enums there, you quickly run into similar "versioning" issues.
Alternatively: consider to allow your client to do the filtering himself, using something like; using Java8 you can think of Predicates, lambdas and all that stuff.
Example:
Predicate<Apple> applePredicate = new Predicate<Apple>() {
#Override
public boolean test(Apple a) {
return a.getColour() == AppleColor.GoldenPoisonFrogGolden;
}
};
List<Apples> myApples = dealer.getApples(applePredicate);
IMHO creating new class/method for any possible Apple combination will result in a code pollution. The situation described in your post could be gracefully handled by introducing flags parameter :
List<Apple> getApples(); // keep for backward compatibility
List<Apple> getApples(FLAGS); // use flag as a filter
Possible flags:
RED_FLAG
GREEN_FLAG
RIPE_FLAG
SWEET_FLAG
So a call like below could be possible:
List<Apple> getApples(RIPE_FLAG & RED_FLAG & SWEET_FLAG);
that will produce a list of apples that are ripe, and red-delicious.
I want to write a code generator that generates a class based on the meta model of another ceylon class. I want the code generator to run at compile time. What is the best way for me to do this. I could probably accomplish this by writing a plugin for gradle or the ceylon build system but I'm hoping for a simpler solution. Unfortunately, I don't see any support for code generators in ceylon. Also, are there any plans for code generators in ceylon?
I want to write this code generator because I'm thinking about writing a simple web framework for ceylon that look at a class like the following using the meta-model:
controller
shared class Controller() {
shared void doSomething() => print("did it!");
}
I plan for it to be like Spring MVC. This framework would make a restful API from the Controller class that allows someone to write an AJAX call like this:
$http.get("/Controller/doSomething");
I want to make things more convenient, high level, and simple by doing something like GWT. I want to create a code generator that automatically generates a class like this:
shared class RemoteController() {
shared void doSomething() {
$http.get("/Controller/doSomething");
}
}
The RemoteController would be run in a user's browser as javaScript and allow client side ceylon code to do an Ajax call like this:
RemoteController().doSomething();
That would end up calling the Controller().doSomething() on the server so "did it!" would be printed.
AST Transformers have been proposed, but are still in the early design phase. For now, to do compile-time code generation, you’ll have to rig up something of your own.
To actually generate the code, I would recommend use of ceylon.ast and ceylon.formatter. The workflow would roughly be:
analyze source code –
either parse it with ceylon.ast (ceylon.ast.redhat::compileAnyCompilationUnit) and analyze it without typechecking,
or parse it using the compiler, run the typechecker, then convert it to ceylon.ast (ceylon.ast.redhat::anyCompilationUnitToCeylon), keeping the typechecker information using the new update hooks in the very soon upcoming 1.2.0 release
edit the source code AST to add your new code (using a custom ceylon.ast.core::Editor that injects new class definitions into the CompilationUnits), or perhaps create entirely new compilation units if the RemoteController lives in a different module
convert the ceylon.ast AST to a compiler AST and feed it into ceylon.formatter to turn the AST into code again (see here for an example of that)
Alternatively, if you integrate this into your build step, you could skip the ceylon.formatter part of step 3 and instead feed the converted compiler AST into the typechecker and rest of the compiler directly.
How to do code management for AB testing?
In particular, how to organize the code (baseline and variant) in the project folder?
how to remove code after the experiment?
There is no "one" answer. You can do this in many ways different folders, different classes or do something as simple as if statement in your code.
I think what you are actually asking is how to find all these experiments in the code. A good solution for this is to make the "experiment definition" code with concrete classes so you can easily find it in your IDE and once you delete the experiment definition class your compilation will break and you will easily find all the places in the code that use it.
A good example of this pattern is used by the open source AB test framework called PETRI, which is promoting exactly that. You create an experiment spec (the AB test definition) as a concrete class and use it to conduct the the test.
#RequestMapping(value = "/conductExperimentWithSpecDefinition", method = RequestMethod.GET)
#ResponseBody
public String conductExperimentWithSpecDefinition( #RequestParam("fallback") String fallback) throws ClassNotFoundException {
return laboratory.conductExperiment(TestSpecDefinition.class, fallback, new StringConverter());
}
This is the problem:
Create a class and set the access to be private for some of the properties or methods.
Use the doc command for the created class. This will auto-generate documentation from your comments and show it in the built-in help browser.
doc classname
The problem is that documentation for the private properties and methods is not shown in the help browser. Is there any way to overcome this problem?
So I spent like 10 minutes using the debugger, jumping from one function to the next, tracing the execution path of a simple doc MyClass call.
Eventually it lead me to the following file:
fullfile(toolboxdir('matlab'),'helptools','+helpUtils','isAccessible.m')
This function is called during the process of generating documentation for a class to determine if the class elements (including methods, properties, and events) are publicly accessible and non-hidden. This information is used later on to "cull" the elements.
So if you are willing to modify MATLAB's internal functions, and you want the docs to always show all methods and properties regardless of their scope, just rewrite the function to say:
function b = isAccessible(classElement, elementKeyword)
b = true;
return
% ... some more code we'll never reach!
end
Of course, don't forget to make a backup of the file in case you changed your mind later :)
(on recent Windows, you'll need to perform this step with administrative privileges)
As a test, take the sample class defined in this page and run doc someClass. The result:
This behaviour is by design - the auto-generated documentation is intended for users of the class, who would only be able to access the public properties and methods.
There's no way that I'm aware of to change this behaviour.
You could try:
Use an alternative system of auto-generating documentation such as this from the MATLAB Central File Exchange (which I believe will document all properties, not just public).
Implement your own doc command. Your doc command should accept exactly the same inputs as the built-in doc command, detect if its inputs correspond to your class/methods/properties etc, and if so display their documentation, otherwise pass its inputs straight through to the built-in doc. Make sure your command is ahead of the built-in on the path.
I am implementing a plugin system with Lua scripts for an application. Basically it will allow the users to extend the functionality by defining one or more functions in Lua. The plugin function will be called in response to an application event.
Are there some good open source plugin frameworks in Lua that can serve as a model?
In particular I wonder what is the best way to pass parameters to the plugin and receive the returned values, in a way that is both flexible and easy to use for the plugin writers.
Just to clarify, I am interested in the design of the API from the point of view of the script programming in Lua, not from the point of view of the hosting application.
Any other advice or best practices related to the design of a plugin system in Lua will be appreciated.
Lua's first-class functions make this kind of thing so simple that I think you won't find much in the way of frameworks. Remember that Lua's mantra is to provide minimal mechanism and let individual programmers work out policy for themselves.
Your question is very general, but here's what I recommend for your API:
A single plugin should be represented by a single Lua table (just as a Lua module is represented by a single table).
The fields of the table should contain operations or callbacks of the table.
Shared state should not be stored in the table; it should be stored in local variables of the code that creates the table, e.g.,
local initialized = false
return {
init = function(self, t) ... ; initialized = true end,
something_else = function (self, t)
if not initialized then error(...) end
...
end,
...
}
You'll also see that I recommend all plugin operations use the same interface:
The first argument to the plugin is the table itself
The only other argument is a table containing all other information needed by the operation.
Finally, each operation should return a result table.
The reason for passing and returning a single table instead of positional results is that it will help you keep code compatible as interfaces evolve.
In summary, use tables and first-class functions aggressively, and protect your plugin's private state.
The plugin function will be called in response to an application event.
That suggests the observer pattern. For example, if your app has two events, 'foo' and 'bar', you could write something like:
HostApp.listeners = {
foo = {},
bar = {},
}
function HostApp:addListener(event, listener)
table.insert(self.listeners[event], listener)
end
function HostApp:notifyListeners(event, ...)
for _,listener in pairs(self.listeners[event]) do
listener(...)
end
end
Then when the foo event happens:
self:notifyListeners('foo', 'apple', 'donut')
A client (e.g. a plugin) interested in the foo event would just register a listener for it:
HostApp:addListener('foo', function(...)
print('foo happened!', ...)
end)
Extend to suit your needs.
In particular I wonder what is the best way to pass parameters to the plugin and receive the returned values
The plugin just supples you a function to call. You can pass any parameters you want to it, and process it's return values however you wish.