What is the correct implementation of singleton pattern in perl6?
I've tried this but I dont' know how to use static keyword in perl6:
It one of the few reasons that require using bless method
class Singleton {
my Singleton $instance;
method new {!!!}
submethod instance {
$instance = Singleton.bless unless $instance;
$instance;
}
}
Related
I'm working in a project which has some Java legacy code. One common pattern there is to create singletons using the "enum" approach:
enum MySingleton {
INSTANCE;
int answer;
init {
answer = 42;
}
int fun1() { return answer };
This INSTANCE object in reality has some complex dependencies which I cannot fulfill during unit tests. I thus would like to return a mocked MySingleton object whenever the caller uses MySingleton.INSTANCE. Is that possible?
you can mock enums using mockkObject(Enum)
As per the official Mockk documentation, It can be done like below.
enum class Enumeration(val goodInt: Int) {
CONSTANT(35),
OTHER_CONSTANT(45);
}
mockkObject(Enumeration.CONSTANT)
every { Enumeration.CONSTANT.goodInt } returns 42
assertEquals(42, Enumeration.CONSTANT.goodInt)
No, it isn't. You can't mock enum instances.
I'm relatively new to Kotlin, however I studied Java before this. One thing I don't understand very well is calling a method/function from a class in another class.
Currently I have:
Class Commands(){
fun cmdInit(){
//code in here
}
}
Class Main(){
Commands.cmdInit() //This is how I would usually do it in java, however there is no static referencing in Kotlin, and I dont understand Object Declaration very well
}
Thanks in advance for helping. :D
If you want to acess it like a static method in Java, you can create a companion object. You just have to change your Commands class to this:
class Commands {
companion object {
fun cmdInit(){
//code in here
}
}
}
for more info: https://kotlinlang.org/docs/object-declarations.html#companion-objects
I encountered an unfortunate aspect of Spock Framework (1.3-groovy-2.5), which I use for integration testing of a Gradle plugin.
The code sample
Parent class:
class ClassA extends Specification {
def setupSpec() {
System.out.println("In ClassA setupSpec()")
}
def "base feature"() {
expect:
true
}
}
Child class:
class ClassB extends ClassA {
#Override
def setupSpec() {
System.out.println("In ClassB setupSpec()")
}
def "extended feature"() {
expect:
true
}
}
When I run tests in ClassB, both versions of setupSpec() are called:
In ClassA setupSpec()
In ClassB setupSpec()
Of course, if I call method via native Groovy ways:
class Main {
static void main(String[] args) {
ClassB classB = new ClassB()
classB.setupSpec()
}
}
Then I see only what is expected:
In ClassB setupSpec()
So, evidently, this is a Spock feature of some kind.
Question
In practice, what is the suggested way of inheriting from implementations of Specification while overriding setup logic?
As documented in Fixture Method Invocation Order
If fixture methods are overridden in a specification subclass then
setup() of the superclass will run before setup() of the subclass.
cleanup() works in reverse order, that is cleanup() of the subclass
will execute before cleanup() of the superclass. setupSpec() and
cleanupSpec() behave in the same way. There is no need to explicitly
call super.setup() or super.cleanup() as Spock will automatically find
and execute fixture methods at all levels in an inheritance hierarchy.
The easiest way would be to just move the logic to another method that you can override.
class Base extends Specification {
def setupSpec() {
init()
}
def init() {
println "foo"
}
def "let's try this!"() {
expect:
Math.max(1, 2) == 2
}
}
class Sub extends Base {
#Override
def init() {
println "bar"
}
}
As documented, fixture methods are not meant to override each other but to complement each other, i.e. they are all called in a specific, logical order. Like you said, this is a feature.
Hence, my answer is: There is no suggested way to override setup logic. Instead, the suggested way is to design your base and derived specifications in such a way that overriding is not necessary. I never had any problems to do so and hope you shall solve your problem easily too.
Your sample code is too schematic to say anything more, but basically think about fixture methods in base classes as responsible for to setting up and cleaning up fixture fields in there, while derived specs' fixture methods would take care of additional fixtures specific to those classes. In your example there also is a feature method in the base spec, which I find rather strange because it would be executed for the base spec itself and each time a derived spec is executed. I rather like to think of base specs as practically abstract (avoiding to add any feature methods to them and them being picked up by the test runner), but I am sure there are cases in which what you sketched above might also be helpful. I just cannot think of one now.
Is there a way to test private methods in Raku?
I understand that one should ideally define their tests targeting the public methods, but is there a way to do it "the wrong way"? :)
I initially thought about defining a subclass for the Testing that inherited from the class I wanted to test and do the tests there, but it seems that private methods are not inherited.
Then I saw the 'trusts' routine, but I wouldn't want to reference a Testing class on any of the classes of the code.
Is there something like changing the 'private' property of a method via introspection?
What would be the best way to call/test a private method?
This can be done using introspection.
Consider this is the class you want to test:
class SomeClass {
has Int $!attribute;
method set-value(Int $value) returns Nil {
$!attribute = $value;
return;
}
method get-value returns Int {
return $!attribute;
}
# Private method
method !increase-value-by(Int $extra) returns Nil {
$!attribute += $extra;
return;
}
}
You may create a test like this:
use Test;
use SomeClass;
plan 3;
my SomeClass $some-class = SomeClass.new;
my Method:D $increase-value = $some-class.^find_private_method: 'increase-value-by';
$some-class.set-value: 1;
$increase-value($some-class, 4);
is $some-class.get-value, 5, '1+4 = 5';
$increase-value($some-class, 5);
is $some-class.get-value, 10, '5+5 = 10';
my SomeClass $a-new-class = SomeClass.new;
$a-new-class.set-value: 0;
$increase-value($a-new-class, -1);
is $a-new-class.get-value, -1, '0+(-1) = -1; The method can be used on a new class';
done-testing;
You first create an instance of the class and the use ^find_private_method to get its private Method. Then you can call that Method by passing an instance of a class as the first parameter.
There's a more complete explanation on this answer:
How do you access private methods or attributes from outside the type they belong to?
A fresh cup of tea and #Julio's and #JJ's answers inspired the following:
class SomeClass { method !private ($foo) { say $foo } }
use MONKEY-TYPING; augment class SomeClass { trusts GLOBAL }
my SomeClass $some-class = SomeClass.new;
$some-class!SomeClass::private(42); # 42
My solution tweaks the class using monkey typing. Monkey typing is a generally dodgy thing to do (hence the LOUD pragma). But it seems tailor made for a case just like this. Augment the class with a trusts GLOBAL and Bob's your Uncle.
Raku requires the SomeClass:: qualification for this to work. (Perhaps when RakuAST macros arrive there'll be a tidy way to get around that.) My inclination is to think that having to write a class qualification is OK, and the above solution is much better than the following, but YMMV...
Perhaps, instead:
use MONKEY-TYPING;
augment class SomeClass {
multi method FALLBACK ($name where .starts-with('!!!'), |args) {
.(self, |args) with $?CLASS.^find_private_method: $name.substr: 3
}
}
and then:
$some-class.'!!!private'(42); # 42
I've used:
A multi for the FALLBACK, and have required that the method name string starts with !!!;
A regular method call (. not !);
Calling the method by a string version of its name.
The multi and !!! is in case the class being tested already has one or more FALLBACK methods declared.
A convention of prepending !!! seems more or less guaranteed to ensure that the testing code will never interfere with how the class is supposed to work. (In particular, if there were some call to a private method that didn't exist, and there was existing FALLBACK handling, it would handle that case without this monkey FALLBACK getting involved.)
It should also alert anyone reading the test code that something odd is going on, in the incredibly unlikely case that something weird did start happening, either because I'm missing something that I just can't see, or because some FALLBACK code within a class just so happened to use the same convention.
Besides using introspection, you can try and use a external helper role to access all private methods and call them directly. For instance:
role Privateer {
method test-private-method ( $method-name, |c ) {
self!"$method-name"(|c);
}
}
class Privateed does Privateer {
method !private() { return "⌣" }
}
my $obj = Privateed.new;
say $obj.test-private-method( "private" );
The key here is to call a method by name, which you can do with public and private methods, although for private methods you need to use their special syntax self!.
We can easily check if object has a method by using respondsToSelector:, but how we do it for static functions in class?
I would like to have something like this:
if ([cls classRespondsToSelector:#selector(staticMethodName)]) {
...
}
In Objective-C classes are objects too.
if ([[myClass class] respondsToSelector:#selector(classMethod)]) {
}
Also a small note, these are NOT 'static' methods. That means something specific which doesn't exist in Objective-C. They are class methods.