For Example, I have a variable like this.
var fooBar = 12;
I want a something like this in Dart lang.
print_var_name(fooBar);
which prints:
fooBar
How can I achieve that? Is this even possible?
Thank you.
There is no such thing in Dart for the web or for Flutter.
Reflection can do that, but reflection is only supported in the server VM because it hurts tree-shaking.
You need to write code for that manually or use code generation where you need that.
An example:
class SomeClass {
String foo = 'abc';
int bar = 12;
dynamic operator [](String name) {
switch(name) {
case 'foo': return foo;
case 'bar': return bar;
default: throw 'no such property: "$name"';
}
}
}
main() {
var some = SomeClass();
print(some['foo']);
print(some['bar']);
}
output:
abc
123
Related
I am migrating schemas from proto2 to proto3 syntax. I want to eliminate extensions as they are not supported. Is it possible to get an object using a field name in proto3, similar to what MutableExtension does in proto2.
For example,
Schema in proto2 syntax
message Foo {
message Bar {
unint32 a = 1;
}
extend Foo {
Bar b = 1;
}
}
C++
Foo::Bar b_val = foo.MutableExtension(Foo::b);
Now in proto3, I could do this:
syntax="proto3";
message Foo {
message Bar {
unint32 a = 1;
}
Bar b = 1;
}
C++ code:
Foo::Bar b_val = foo.mutable_b();
However, I want to use the name Foo::b to get a Foo::Bar object. Is there a way to do this?
It's not clear why you need this but what you are asking for is kinda feasible.
Foo::b is a garden variety member function, which means that &Foo::b is a regular pointer-to-member-function.
So you can use it as such using the regular c++ syntax for these entities:
auto b_ref = &Foo::b;
Foo::Bar b_val = (foo.*b_ref)();
Suppose I have a class like this:
class MyClass {
method data-is-valid {
return self!get-data ~~ m{^From};
}
method !get-data {
return 'From Internet';
}
}
where !get-data method gets some data from Internet.
Is it possible to mock that method so that it returns my own hardcoded data so I can test the module without connecting to the Internet?
Ideally, the solution should not modify the definition of the class in any way.
NOTE: A similar question exists regarding unittesting subroutines of modules.
I would first refactor to pull the fetching logic out to a different object, and make MyClass depend on it:
class Downloader {
method get-data {
return 'From Internet';
}
}
class MyClass {
has Downloader $.downloader .= new;
method data-is-valid {
return $!downloader.get-data ~~ m{^From};
}
}
This is an example of dependency inversion, which is a helpful technique for making code testable (and tends to make it easier to evolve in other ways too).
With this change, it is now possible to use the Test::Mock module to mock Downloader:
use Test;
use Test::Mock;
subtest 'Is valid when contains From' => {
my $downloader = mocked Downloader, returning => {
get-data => 'From: blah'
};
my $test = MyClass.new(:$downloader);
ok $test.data-is-valid;
check-mock $downloader,
*.called('get-data', :1times);
}
subtest 'Is not valid when response does not contain From' => {
my $downloader = mocked Downloader, returning => {
get-data => 'To: blah'
};
my $test = MyClass.new(:$downloader);
nok $test.data-is-valid;
check-mock $downloader,
*.called('get-data', :1times);
}
You probably want to take a look at Test::Mock. From its SYNOPSIS:
use Test;
use Test::Mock;
plan 2;
class Foo {
method lol() { 'rofl' }
method wtf() { 'oh ffs' }
}
my $x = mocked(Foo);
$x.lol();
$x.lol();
check-mock($x,
*.called('lol', times => 2),
*.never-called('wtf'),
);
Hi #julio i suggest you take a look at the wrap function for routines, this should do what you need... https://docs.raku.org/language/functions#Routines ... this includes use soft; pragma to prevent inlining
Probably the best idea would be to refactor the code (see Jonathan's answer)
However, If you cannot for some reason, there are still alternatives:
If the method is public you can simply create a subclass and override the method.
For example:
use Test;
class MyClass {
method data-is-valid {
return self.get-data ~~ m{^From};
}
method get-data {
return 'From Internet';
}
}
class MyClassTester is MyClass {
method get-data {
return 'Foobar';
}
}
my MyClassTester $class = MyClassTester.new;
nok $class.data-is-valid, 'Mocked class has invalid data';
done-testing;
If the method is private, you can use wrap as stated on p6steve's answer. However you need introspection in order to modify the private method.
It can be done like this:
use Test;
class MyClass {
method data-is-valid {
return self!get-data ~~ m{^From};
}
method !get-data {
return 'From Internet';
}
}
my $class = MyClass.new;
my Method:D $get-data = $class.^find_private_method: 'get-data';
$get-data.wrap: { 'Foobar' };
nok $class.data-is-valid, 'Mocked class has invalid data';
done-testing;
Hello I'm trying to make use of Squirrel within a C++ application.
For this reason I want to register a Squirrel class in C++.
Let's take the following class as an example.
class Foo
{
constructor(value)
{
::print("constructor called");
this.testValue = value;
}
function saySomething()
{
::print("The value is: " + this.testValue);
}
testValue = 0;
}
Can anybody please show me how to bind it in C++?
I was able to do it, by using this code.
In my example it would look like this:
sqext::SQIClass testClass(L"Foo");
testClass.bind(0, L"testValue");
testClass.bind(1, L"saySomething");
sqext::SQIClassInstance test = testClass.New(4711);
test.call(1);
I have a simple class like
class SomeClass {
def foo() {
def bar= bar()
switch( bar ) {
return something based on format
}
}
def bar() {
return someValue
}
}
I've already written complete unit tests for the bar(). Now I need to write unit tests for foo() which is heavily dependant on the use of bar() method. I don't want to duplicate the setup phase as done for bar(), so I'd like to mock it by simply returning values I want.
I'm aware that Groovy supports this sort of "mocking" easily by simply defining it like SomeClass.property = "Hello World". Also, this can be done with collaborators as SomeClass.service = myMockedService. But I've not found a way to accomplish this with methods inside the unit under tests. Is there?
I tried with MockFor as in
def uut = new MockFor( SomeClass )
uut.demand.bar{ /* some values */ }
uut.use {
assert uut.foo() == expected
}
but it gives me
groovy.lang.MissingMethodException: No signature of method: groovy.mock.interceptor.MockFor.foo() is applicable for argument types: () values: []
UPDATE
In fact, I came up with a simple solution of using sub-classing. In the test method I create a subclass of SomeClass where I override the method I wish to mock/stub. After this, using an instance of the subclass gives me what I need.
This seems a bit rough, though. Any other suggestions on this?
If you want to mock the value returned by bar() for a single instance of SomeClass you can use metaprogramming. Try the following in the Groovy console:
class SomeClass {
def foo() {
}
def bar() {
return 'real value'
}
}
def uut = new SomeClass()
uut.metaClass.bar = {
return 'mock value'
}
assert 'mock value' == uut.bar()
If you want to mock bar() for all instances of SomeClass, replace this:
uut.metaClass.bar = {
return 'mock value'
}
with:
SomeClass.metaClass.bar = {
return 'mock value'
}
I'm working on some D bindings for an existing C library, and I have a bunch of function definitions, and a bunch of bindings for them. For example:
// Functions
void function(int) funcA;
long function() funcB;
bool function(bool) funcC;
char function(string) funcD;
// etc...
// Bindings
if(!presentInLibrary("func")) return false;
if(!bindFunction(funcA, "funcA")) return false;
if(!bindFunction(funcB, "funcB")) return false;
if(!bindFunction(funcC, "funcC")) return false;
if(!bindFunction(funcD, "funcD")) return false;
// etc...
This model is very similar to how Derelict handles OpenGL extension loading. However, this seems like a lot of redundant typing. I'd really like a way to express the "binding" portion above as something like:
BINDGROUP("func", "funcA", "funcB", "funcC", "funcD", ...); // Name of function group, then variable list of function names.
Is this something that can be done with mixins?
I used this when I was doing dynamic loading, while it doesn't answer your question you may be able to adapt it:
void function() a;
int function(int) b;
void function(string) c;
string bindFunctions(string[] funcs...)
{
string ret;
foreach (func; funcs)
{
ret ~= func ~ ` = cast(typeof(` ~ func ~ `))lib.getSymbol("` ~ func ~ `");`;
}
return ret;
}
mixin(bindFunctions("a", "b", "c"));
Here bindFunctions("a", "b", "c") returns a string that looks something like:
a = cast(typeof(a))lib.getSymbol("a");
b = cast(typeof(b))lib.getSymbol("b");
c = cast(typeof(c))lib.getSymbol("c");
Where lib.getSymbol() returns a pointer from dl_open() etc. Hope this helps.
I assume you meant string mixins? You can just make straight-forward use of D's vararg syntax:
string BINDGROUP(string functionGroup, string[] functions...)
{
// ...
}
mixin(BINDGROUP("func", "funcA", "funcB", "funcC", "funcD"));
I believe this is what you're looking for
template BINDGROUP(string group,T...){
alias BINDGROUP presentInLibrary("func") && BINDGROUPFUNCS!(T);
}
template BINDGROUPFUNCS(T...){
static if(T.length)alias BINDGROUPFUNCS true; // all is successful
else alias BINDGROUPFUNCS bindFunction(mixin(T), T) && BINDGROUPFuncts!(T[1..$]);
}
I'm using recursive template declaration here, you could also do this with foreach loops