I've looked through the Jython book on Jython.org and perused the Internet for some answers but I don't see anywhere that suggests the following (of what seems to me to be strange) behavior. I'm doing this using PyDev 1.5.7 in Eclipse 3.6.1 with Jython 2.5.3.
Does a Jython class that inherits from a Java interface with setters automatically call the setVal when self.val = val is executed?
Here's the Java interface:
package com.me.mypackage
import org.python.core.PyDictionary;
public interface MyInterface {
public double getMaxBW();
public boolean setMaxBW(double bw);
}
Here's the Jython class:
from com.me.mypackage import MyInterface
class MyClass(MyInterface):
def __init__(self, maxBW):
self.maxBW = maxBW
def setMaxBW(self, maxBW):
self.maxBW = maxBW
def getMaxBW(self):
return self.maxBW
When I instantiate the class, in the __init__ function:
setMaxBW gets called when self.maxBW = maxBW is run
This function call in turn runs self.maxBW = maxBW
This code again calls setMaxBW
This function call in turn runs self.maxBW = maxBW
Repeat forever
As a result of this infinite recursion, I get a RuntimeError after the maximum recursion depth has been reached.
One thought was that this was something nifty new-style Python classes were doing (I've spent most of my Python time with old-style classes) but this problem doesn't occur with pure Jython (in Eclipse or standalone from the command line) that doesn't inherit from the Java interface. I haven't tried the interface inheritance outside of Eclipse.
And now I reiterate my initial question but in the context of my code: Is a Jython class that inherits a Java interface with setters automatically call setMaxBW when self.maxBW = maxBW is executed?
Related
I am writting a custom module for Micropython called System. The System class is written in C and has the function testpass.
// System class test function
STATIC mp_obj_t system_testpass( mp_obj_t self_in, mp_obj_t thing_in )
{
// How do I get the Thing object so I can access its members?
printf("Thing: %d\r\n", thing->test );
return MP_ROM_NONE;
}
MP_DEFINE_CONST_FUN_OBJ_2(system_testpass_obj, system_testpass);
I have another class called Thing that is written in Python.
class Thing():
def __init__( self, test ):
self.test = test
How do I use the Thing class in the System class?
If I have app.kt file in kotlin, can I create instance like appKt()? Thanks.
Kotlin has top level function. For example I can write in app.kt:
val a = 123
fun abc() {}
appKt.abc()
my question is if I can create appKt instance and call instance method
Only classes can be instanced.
Instead of loose function fun abc() {}, this should be the method of a class:
class appKt() {
// private var a: Integer = 123
fun abc() {}
}
No, you can't put arbitrary code at the top level.
You can put only definitions of classes (just as in Java), objects, functions, and properties.
It wouldn't make much sense to put loose code there, anyway: when would it run?
It's not clear what you're trying to achieve with this. If you want some code that gets run when your program starts up, then you could put it into a top-level function — but you'd then have to call that function (e.g. from your main() method). Or you could put it in the init block of the companion object to a class that you know will be loaded. Or if you're using a framework such as Android or Spring, then that will probably provide ways to specify code to be run at start-up.
I am creating demo code in Kotlin. I am trying so students should be able:
run function itself
run test
For example:
If function is created in .kt file, outside of class:
fun main(){
print("Hello world!")
}
it can be run
but I could not find the way to call it from the test
If the function is inside the class:
class Hello {
fun main(){
print("Hello world!")
}
}
the function can be called from the test
but can not be run - the green "Run" button is not visible.
Question: How to make such a function can be run manually and by test at the same time?
I'll assume you are writing your tests in Java, because if it's in Kotlin, calling main is trivial: main(), provided that you have imported the package/in the same package.
Kotlin global functions are compiled into static methods of a class with a name similar to the Kotlin file in which the function is declared, suffixed with Kt For example, if the file is called "app.kt", the class name would be AppKt. So if you declared main in app.kt, you would call:
AppKt.main();
in Java
You can change this name by annotating the Kotlin file with #JvmName:
#file:JvmName("MyOwnName")
Then you can call:
MyOwnName.main();
in Java.
See more documentation here
I am having trouble with using internal kotlin functions in my Spock tests. Here's short snippet of my spock test:
private def preconditions = new MonetaryPreconditions()
private def usdMonetary = new Monetary(BigDecimal.ZERO, Currency.USD)
def "should throw nothing because Monetaries currencies are same"(){
when:
preconditions.checkMonetariesCurrencies(usdMonetary , usdMonetary )
then:
noExceptionThrown()
}
and my MonetaryPreconditions class:
internal object MonetaryPreconditions {
internal fun checkMonetariesCurrencies(monetary1: Monetary, monetary2: Monetary) {
if (monetary1.currency != monetary2.currency) {
throw CurrencyMismatchException(arrayOf(monetary1.currency, monetary2.currency), "Compared currencies does not match: " + monetary1.currency
+ " , " + monetary2.currency)
}
}
}
My test fails with a stacktrace:
groovy.lang.MissingMethodException: No signature of method: touk.recruitment.parkandrest.parkingmanagement.core.monetary.MonetaryPreconditions.checkMonetariesCurrencies() is applicable for argument types: (touk.recruitment.parkandrest.parkingmanagement.core.monetary.Monetary, touk.recruitment.parkandrest.parkingmanagement.core.monetary.Monetary) values: [touk.recruitment.parkandrest.parkingmanagement.core.monetary.Monetary#7c417213, ...]
The problem lies in internal visibility of my checkMonetariesCurrencies function. If I change it to public it works just fine, however I do want this to be module private. How can I achieve that with Spock?
Other information about my project:
Test class and MonetaryPreconditions have same package.
I am using Maven.
Test class and MonetaryPreconditions are of course in the same module.
I just ran into the same issue, and the workaround I used (suggested by an experienced coworker of mine) was to write a wrapper class in Kotlin (in the same package as the class under test (CUT); I placed the source code file in the test/kotlin folder) and just forward function calls to the CUT. I then used the wrapper class in my groovy unit test code.
Further, calling functions defined within an object in Kotlin from another programming language requires you to access the object's INSTANCE variable, e.g.
MonetaryPreconditions.INSTANCE.myfunction
In your case, the wrapper may look as follows:
package com.yourpackage
object MonetaryPreconditionsWrapper{
fun checkMonetariesCurrencies(monetary1: Monetary, monetary2: Monetary){
MonetaryPreconditions.checkMonetariesCurrencies(monetary1, monetary2)
}
}
Now you can test the MonetaryPreconditions.checkMonetariesCurrencies function by simply calling the wrapper function from the groovy code as follows:
MonetaryPreconditionsWrapper.INSTANCE.checkMonetariesCurrencies(monetary1, monetary2)
Thanks you Giuseppe for your answer. However for me, Spock didn't see the wrapper as it thought it was a property of the test class and threw a groovy.lang.MissingPropertyException. I had add this to build.gradle:
compileTestGroovy.classpath += files(compileTestKotlin.destinationDir)
Taken from here: https://localcoder.org/test-classes-in-groovy-dont-see-test-classes-in-kotlin
My previous approach in Objective-C for unit testing was like following:
Calling a public method: no problem
Calling a private method: create a category of that class in your unit test file and put the signature of the private method into this category
Currently, I have the following:
Class developed in ObjC
Protocol developed in Swift
Unit tests for that class developed in Swift
The class conforms (directly, in its public interface (.h)) to that protocol. I have a class instance in my unit tests but somehow I can not invoke a method declared in the protocol over that instance.
Now, the old Category solution does not work with Extensions. When I put some method signature in the extension I get that error saying "Function body expected in declaration".
How can I call the functions with Swift in the best way?
PS: I do not want to declare the method again in the public interface of the class, that is an ugly solution.
As per the documentation on "Writing Tests with Swift" here:
Xcode provides a two-part solution to this problem:
When you set the Enable Testability build setting to Yes, which is
true by default for test builds in new projects, Xcode includes the
-enable-testing flag during compilation. This makes the Swift entities declared in the compiled module eligible for a higher level of access.
When you add the #testable attribute to an import statement for a
module compiled with testing enabled, you activate the elevated access
for that module in that scope. Classes and class members marked as
internal or public behave as if they were marked open. Other entities
marked as internal act as if they were declared public.
Here is also the example (for MySwiftApp)
Class built for a target with Enable Testability set to yes
import Cocoa
#NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
#IBOutlet weak var window: NSWindow!
func foo() {
println("Hello, World!")
}
}
Unit test class
// Importing XCTest because of XCTestCase
import XCTest
// Importing AppKit because of NSApplication
import AppKit
// Importing MySwiftApp because of AppDelegate
#testable import MySwiftApp
class MySwiftAppTests: XCTestCase {
func testExample() {
let appDelegate = NSApplication.sharedApplication().delegate as! AppDelegate
appDelegate.foo()
}
}
Also see the important Note
Note: #testable provides access only for internal functions;
file-private and private declarations are not visible outside of their
usual scope when using #testable.