same cucumber gherkin step but different methods - overloading

I have a step
Given I have a pass
|hotel|
and
Given I have a pass
One runs with data and one runs without data. To handle above requirement I wrote two functions:
#Given("^I have a pass$")
public void givenIhaveAPass() {
}
and
#Given("^I have a pass$")
public void givenIhaveAPass(DataTable table) throws Exception {
}
but it is giving error DefinitionTestSuite.initializationError DuplicateStepDefinition Duplicate
Want to use same step with method overloading. How can I do that?

I don't think this is possible since the matching is done with regex only, and not considering the parameters. You can do two just
Given I have a pass with:
|hotel|
and
Given I have a pass
and match them in your two java methods. This way you can give them a clearer name as well.

This is not applicable method in cucumber. There is so much issues opened and closed about your question in cucumber's github issues page.
As a work around solution I can suggest following methods.
When you use (.*), you don't have to provide any arguments just erase the 'string' part while you calling step definition :
#Given("^I have a pass(.*)$")
public void givenIhaveAPass() {
}
#Given("^I have a pass$")
public void givenIhaveAPass(DataTable table) throws Exception {
}

Related

C++ dynamic code generation based on input parameter

I have the following function:
void scan(DataRow& input) {
if(input.isRaw()) {
...
}
if(input.isExternal()) {
...
}
if(input.hasMultipleFields()) {
...
for(auto& field: input.fields()) {
if(field.size() == 2) {
...
}
}
}
}
The DataRow class has many sub-classes and all the is functions above are virtual.
This function is used to scan several large groups of data rows. For each group, all data row instances will have the same property (e.g., all raw, all external).
So instead of having all these if/else logics in the scan function, I am thinking if there is a way to generate ad-hoc code. For example, now I already know my next group are all raw (or all not), then I can get rid of the first if branch.
In Java, I used to do such kind of things by generating byte code for class and dynamically load the generated class in JVM. I know the same trick does not work for C++ but I have little experience how to do this. Can anyone give some hint? Thanks!
You cannot easily manipulate executable code during runtime. But your question doesn’t look like you’d have to go down that road anway.
You have groups of rows with similar properties and special processing logic for each group. Also, there seems to be a small fixed number of different kinds of groups.
You have all necessary information to split up your code at compile time – “programming time” actually. Split the scan() function into one function for each kind of group and call scan_raw(), scan_external(), etc. accordingly.
This reduces the number of if condition checks from once per row to once per group. As an added benefit the separate scan functions can use the appropriate derived class as their parameter type and you can get rid of the whole isSomething() machinery.
Hm, at this point I’m tempted to point you towards std::variant and std::visit (or their Boost equivalents). That could be a larger refactoring, though. Because when using them you’d ideally use them as a complete replacement for your current inheritance based polymorphism approach.

Turtle Mock: MOCK_EXPECT fails if mocked class method returns a value

I am a long time lurker in the board, and is needless to say that you guys are the best and I am grateful for all the times you saved my job. That is my first time post here and I hope I don't mess it up.
I am writing a C++ Boost application for Linux (Virtualized Ubuntu 16.04 amd_64) and am using Turtle Mock for the mocking framework and Boost Test for the testing framework. When I try to test a class which uses dependency injection technique, I mock the classes that need to be given to the testing class so I can verify the sequence of their invocation. S far so good, but the problem comes here.
I am using MOCK_BASE_CLASS(MockAClass, AClass), to override the virtual methods of the real AClass, and use to new MockAClass to proceed with my tests. Let's say AClass has a virtual method int getTest(int), and MockAClass has MOCK_METHOD(getTest, 1, int(int)), after setting expectation and return value for the getTest method of MockAClass object, and invoking the method, the expectation which in most cases is MOCK_EXPECT(objMockAClass.getTest).at_least(1) is NEVER verified. I can control the return value, but the call is never verified as it happened. This only occurs if the function returns a value (for ex. if the function is void getTest(int) then the verification will pass).
I am attaching a simple PoC of my problem that will fail on my system.
class AClass
{
public:
virtual int getTest(int a) {return 0}
}
MOCK_BASE_CLASS (MockAClass, AClass)
{
MOCK_METHOD(getTest, 1, int(int));
}
BOOST_AUTО_TEST_CASE(SomeClassFunctionality)
{
MockAClass objMockAClass;
MOCK_EXPECT(objMockAClass.getTest).returns(1);
MOCK_EXPECT(objMockAClass.getTest).at_least(1);
objMockAClass.getTest(1);
}
MOCK_EXPECT(objMockAClass.getTest).returns(1);
MOCK_EXPECT(objMockAClass.getTest).at_least(1);
This is actually two expectations. The first one means 'everytime getTest gets called return 1' and the second 'getTest must be called at least one time'.
The problem is that the first one will always match, therefore the second will not have a chance to be triggered.
Тhe problem is solved if separate EXPECT statements are combined in one whole EXPECT statement.
MOCK_EXPECT(objMockAClass.getTest).at_least(1).returns(1); - This will make the example work as planned.
Regards,

Decorator design pattern vs. inheritance?

I've read the decorator design pattern from Wikipedia, and code example from this site.
I see the point that traditional inheritance follows an 'is-a' pattern whereas decorator follows a 'has-a' pattern. And the calling convention of decorator looks like a 'skin' over 'skin' .. over 'core'. e.g.
I* anXYZ = new Z( new Y( new X( new A ) ) );
as demonstrated in above code example link.
However there are still a couple of questions that I do not understand:
what does wiki mean by 'The decorator pattern can be used to extend (decorate) the functionality of a certain object at run-time'? the 'new ...(new... (new...))' is a run-time call and is good but a 'AwithXYZ anXYZ;' is a inheritance at compile time and is bad?
from the code example link I can see that the number of class definition is almost the same in both implementations. I recall in some other design pattern books like 'Head first design patterns'. They use starbuzz coffee as example and say traditional inheritance will cause a 'class explosion' because for each combination of coffee, you would come up with a class for it.
But isn't it the same for decorator in this case? If a decorator class can take ANY abstract class and decorate it, then I guess it does prevent explosion, but from the code example, you have exact # of class definitions, no less...
Would anyone explain?
Let's take some abstract streams for example and imagine you want to provide encryption and compression services over them.
With decorator you have (pseudo code):
Stream plain = Stream();
Stream encrypted = EncryptedStream(Stream());
Stream zipped = ZippedStream(Stream());
Stream zippedEncrypted = ZippedStream(EncryptedStream(Stream());
Stream encryptedZipped = EncryptedStream(ZippedStream(Stream());
With inheritance, you have:
class Stream() {...}
class EncryptedStream() : Stream {...}
class ZippedStream() : Stream {...}
class ZippedEncryptedStream() : EncryptedStream {...}
class EncryptedZippedStream() : ZippedStream {...}
1) with decorator, you combine the functionality at runtime, depending on your needs. Each class only takes care of one facet of functionality (compression, encryption, ...)
2) in this simple example, we have 3 classes with decorators, and 5 with inheritance. Now let's add some more services, e.g. filtering and clipping. With decorator you need just 2 more classes to support all possible scenarios, e.g. filtering -> clipping -> compression -> encription.
With inheritance, you need to provide a class for each combination so you end up with tens of classes.
In reverse order:
2) With, say, 10 different independent extensions, any combination of which might be needed at run time, 10 decorator classes will do the job. To cover all possibilities by inheritance you'd need 1024 subclasses. And there'd be no way of getting around massive code redundancy.
1) Imagine you had those 1024 subclasses to choose from at run time. Try to sketch out the code that would be needed. Bear in mind that you might not be able to dictate the order in which options are picked or rejected. Also remember that you might have to use an instance for a while before extending it. Go ahead, try. Doing it with decorators is trivial by comparison.
You are correct that they can be very similar at times. The applicability and benefits of either solution will depend on your situation.
Others have beat me to adequate answers to your second question. In short it is that you can combine decorators to achieve more combinations which you cannot do with inheritance.
As such I focus on the first:
You cannot strictly say compile-time is bad and run-time is good, it is just different flexibility. The ability to change things at run-time can be important for some projects because it allows changes without recompilation which can be slow and requires you be in an environment where you can compile.
An example where you cannot use inheritance, is when you want to add functionality to an instantiated object. Suppose you are provided an instance of an object that implements a logging interface:
public interface ILog{
//Writes string to log
public void Write( string message );
}
Now suppose you begin a complicated task that involves many objects and each of them does logging so you pass along the logging object. However you want every message from the task to be prefixed with the task Name and Task Id. You could pass around a function, or pass along the Name and Id and trust every caller to follow the rule of pre-pending that information, or you could decorate the logging object before passing it along and not have to worry about the other objects doing it right
public class PrependLogDecorator : ILog{
ILog decorated;
public PrependLogDecorator( ILog toDecorate, string messagePrefix ){
this.decorated = toDecorate;
this.prefix = messagePrefix;
}
public void Write( string message ){
decorated.Write( prefix + message );
}
}
Sorry about the C# code but I think it will still communicate the ideas to someone who knows C++
To address the second part of your question (which might in turn address your first part), using the decorator method you have access to the same number of combinations, but don't have to write them. If you have 3 layers of decorators with 5 options at each level, you have 5*5*5 possible classes to define using inheritance. Using the decorator method you need 15.
First off, I'm a C# person and haven't dealt with C++ in a while, but hopefully you get where I'm coming from.
A good example that comes to mind is a DbRepository and a CachingDbRepository:
public interface IRepository {
object GetStuff();
}
public class DbRepository : IRepository {
public object GetStuff() {
//do something against the database
}
}
public class CachingDbRepository : IRepository {
public CachingDbRepository(IRepository repo){ }
public object GetStuff() {
//check the cache first
if(its_not_there) {
repo.GetStuff();
}
}
So, if I just used inheritance, I'd have a DbRepository and a CachingDbRepository. The DbRepository would query from a database; the CachingDbRepository would check its cache and if the data wasn't there, it would query a database. So there's a possible duplicate implementation here.
By using the decorator pattern, I still have the same number of classes, but my CachingDbRepository takes in a IRepository and calls its GetStuff() to get the data from the underlying repo if it's not in the cache.
So the number of classes are the same, but the use of the classes are related. CachingDbRepo calls the Repo that was passed into it...so it's more like composition over inheritance.
I find it subjective when to decide when to use just inheritance over decoration.
I hope this helps. Good luck!

What do I name this class whose sole purpose is to report failure?

In our system, we have a number of classes whose construction must happen asynchronously. We wrap the construction process in another class that derives from an IConstructor class:
class IConstructor {
public:
virtual void Update() = 0;
virtual Status GetStatus() = 0;
virtual int GetLastError() = 0;
};
There's an issue with the design of the current system - the functions that create the IConstructor-derived classes are often doing additional work which can also fail. At that point, instead of getting a constructor which can be queried for an error, a NULL pointer is returned.
Restructuring the code to avoid this is possible, but time-consuming. In the meantime, I decided to create a constructor class which we create and return in case of error, instead of a NULL pointer:
class FailedConstructor : public IConstructor
public:
virtual void Update() {}
virtual Status GetStatus() { return STATUS_ERROR; }
virtual int GetLastError() { return m_errorCode; }
private: int m_errorCode;
};
All of the above this the setup for a mundane question: what do I name the FailedConstructor class? In our current system, FailedConstructor would indicate "a class which constructs an instance of Failed", not "a class which represents a failed attempt to construct another class".
I feel like it should be named for one of the design patterns, like Proxy or Adapter, but I'm not sure which.
EDIT: I should make it clear that I'm looking for an answer that adheres to, ideally, one of the GoF design patterns, or some other well-established naming convention for things of this nature.
To answer your literal question, I'd probably go with ConstructorFailure, as it describes the event of failing.
However, I'd probably go one step further and make it an Exception, in which case ConstructorException doesn't sound too shabby. Any reason you want to return this instead of throwing it?
I'd name it NullConstructor in line with the null object pattern, which is the pattern you're using. See http://en.wikipedia.org/wiki/Null_Object_pattern
Throw an exception. That is If I understand your description correctly and the creation of the IConstructor object is not done asynchronously.
Though if you don't have exceptions available to you I would probably call it ConstructorCreationError. Yes it does convey a failure mode but, more accurately, it is communicating the specific error that occurred. Also, having constructor as the last word, to me, seems to give the wrong meaning, but you could put "constructor" at the end as well.
You could also replace the verb "Creation" with something like SpawnConstructorError, ConstructorGenerationError and or if you're a fan of Dr. Chevalier maybe ErroneousConstructor.
I'd go for DummyConstructor because its only purpose is to simulate a valid Constructor instance, but no real functionality is implemented by it.
FailureResponseConstructor?
You're not creating a failure, you're creating the response to the failure. Thus, I would think any synonym to 'response' or 'respond' would work.
If you willing to spend effort checking returned pointer against the "FailureConstructor", I don't see reason why couldn't you check it against NULL ?
Unless your system is designed to mask component failure from each other, it just doesn't make sense to assume every associated parts are working well.
I'm going to go with something based on Niall C.'s comment -- FailedConstructorProxy. The Proxy pattern seems to fit best with what this class is; though rather than it relaying method calls to an object, it's standing in and generating what we wanted the actual constructor to return.
(If someone has a more correct answer, post it and I'll mark that one as accepted. I'm still not 100% convinced this is the right name!)
Why not create a Failed class to represent a class that failed construction and go with FailedConstructor? This way the naming is consistent.
I would suggest calling this class FailedObjectConstructionHandler which describes what the class does.

Is this proper use of dynamic_cast?

I have three classes: Generic, CFG, and Evaluator.
Here's Generic:
class Generic: public virtual Evaluator, public CFG, public LCDInterface {
Here's CFG:
class CFG : public virtual Evaluator {
And Evaluator subclasses nothing.
I'm providing a DLL named PluginLCD, and it has a method called Connect:
void PluginLCD::Connect(Evaluator *visitor) {
visitor_ = dynamic_cast<Generic *>(visitor);
if(!visitor_)
return;
type_ = visitor_->GetType();
}
Here's how I'm compiling the DLL through scons:
env.SharedLibrary(['PluginLCD.cpp', 'Evaluator.cpp', 'Generic.cpp', 'CFG.cpp'])
Now, there are two scenarios in my code. One is in class LCDControl, which subclasses CFG. The other scenario is above where Generic subclasses Evaluator and CFG. Evaluator has a method called LoadPlugins, which does what its name suggests, passing this through to the DLL via method Connect. Well, in the first scenario the cast to Generic * in Connect should return NULL. However, in the second scenario, as far as I know, a valid pointer should be returned. It doesn't seem to be happening this way. Am I wrong about this?
dynamic_cast is known to break across module boundaries with many compilers (including MSVC and gcc). I don't know exactly why that is, but googling for it yields many hits. I'd recommend trying to get rid of the dynamic_cast in the first place instead of trying to find out why it returns null in your second scenario.