googlemock matcher for output parameters - matcher

I am testing whether my class calls a method on a mocked class, with the proper argument. I have set up a basic expectation:
// mListener is a mocked object
// This expectation accepts any argument
EXPECT_CALL(this->mListener, OnChanged(_))
.Times(1);
This is fine, but I also want to verify the argument. It is an object which only has accessors that use output parameters:
// aValue is an output parameter
HRESULT get_Value(int* aValue);
How can I define a matcher that will inspect the value that get_Value puts into aValue?

You could try something like:
MATCHER_P(CheckValue,
expected_value,
std::string("get_Value ")
+ (negation ? "yields " : "doesn't yield ")
+ PrintToString(expected_value)
+ " as expected.") {
int result;
arg.get_Value(&result);
return expected_value == result;
}
which could check that e.g. aValue == 7 by doing:
EXPECT_CALL(this->mListener, OnChanged(CheckValue(7)))
.Times(1);

Related

Is the usage of rb_protect mandatory when we use rb_funcall

I have started to write a ruby module for the clang-c library.
I wrapp in my clang c module this
unsigned clang_visitChildren(CXCursor parent,
CXCursorVisitor visitor,
CXClientData client_data);
with a visitor like this:
typedef enum CXChildVisitResult (*CXCursorVisitor)(CXCursor cursor,
CXCursor parent,
CXClientData client_data);
and the ruby code (that is working) looks like this:
Clangc.visit_children(cursor: tu.cursor) do |cursor, parent|
puts cursor
puts parent
Clangc::ChildVisitResult::RECURSE
end
The idea is to take the block, pass it to the visitor as a parameter and call it in the visitor.
The C glue code looks like this:
VALUE
m_clangc_visit_children_with_proc(VALUE self, VALUE cursor, VALUE aproc)
{
if (rb_class_of(aproc) != rb_cProc) rb_raise(rb_eTypeError, "Need a block");
VALUE callback = aproc;
Cursor_t *c;
unsigned ret_with_break;
Data_Get_Struct(cursor, Cursor_t, c);
ret_with_break = clang_visitChildren(c->data,
visitor,
(CXClientData) callback);
/*return false if ret_with_break == 0*/
return NOT_0_2_RVAL(ret_with_break);
}
with the visitor (callback) :
static enum CXChildVisitResult
visitor(CXCursor cursor, CXCursor parent, CXClientData client_data)
{
/*basic variables initialization...*/
r_ret = rb_funcall(callback, rb_intern("call"), 2, r_cursor, r_parent);
if (TYPE(r_ret) == T_FIXNUM)
{
ret = NUM2UINT(r_ret);
if (ret == CXChildVisit_Break || ret == CXChildVisit_Continue ||
ret == CXChildVisit_Recurse)
return ret;
else
return CXChildVisit_Break;
}
else
return CXChildVisit_Break;
}
My answer is should I use rb_protect here?
The code can be found here :
https://github.com/cedlemo/ruby-clangc/blob/master/ext/clangc/_clangc_functions.c#L146
https://github.com/cedlemo/ruby-clangc/
After some tests and after reading others people code, I have arrived to the conclusion that the usage of rb_protect to encapsulate the rb_funcall is not mandatory.
It should be used when you need to handle, in C, the possible exceptions in the ruby blocks or procs that are executed by rb_funcall.
I should mention that it must be more important to handle those exceptions when you embed ruby interpreter in C than when you write some C ruby extensions.
References :
git clone git://libvirt.org/ruby-libvirt.git
git clone https://github.com/ruby-gnome2/ruby-gnome2.git
http://clalance.blogspot.fr/2011/01/writing-ruby-extensions-in-c-part-5.html
https://silverhammermba.github.io/emberb/c/

How to check for a Not a Number (NaN) in Swift 2

The following method calculates the percentage using two variables.
func casePercentage() {
let percentage = Int(Double(cases) / Double(calls) * 100)
percentageLabel.stringValue = String(percentage) + "%"
}
The above method is functioning well except when cases = 1 and calls = 0.
This gives a fatal error: floating point value can not be converted to Int because it is either infinite or NaN
So I created this workaround:
func casePercentage() {
if calls != 0 {
let percentage = Int(Double(cases) / Double(calls) * 100)
percentageLabel.stringValue = String(percentage) + "%"
} else {
percentageLabel.stringValue = "0%"
}
}
This will give no errors but in other languages you can check a variable with an .isNaN() method. How does this work within Swift2?
You can "force unwrap" the optional type using the ! operator:
calls! //asserts that calls is NOT nil and gives a non-optional type
However, this will result in a runtime error if it is nil.
One option to prevent using nil or 0 is to do what you have done and check if it's 0.
The second is option is to nil-check
if calls != nil
The third (and most Swift-y) option is to use the if let structure:
if let nonNilCalls = calls {
//...
}
The inside of the if block won't run if calls is nil.
Note that nil-checking and if let will NOT protect you from dividing by 0. You will have to check for that separately.
Combining second and your method:
//calls can neither be nil nor <= 0
if calls != nil && calls > 0

How to write a spock testcase for a method which calls other methods inside

Say i have a method which populate some data to a list and it internally calls one more method(which i'm testing independently) and that populate some data to the list. Here what is the best way of testing?
How to test the outer Method? Should I check for the data's from inner Method also, else it is ok to test only the data's populated by outer method?
Given the following class under test:
class MyTestClass {
int getAPlusB() { return getA() + getB() }
int getA() { return 1 }
int getB() { return 2 }
}
I can write the following spock test to check that the arithmetic is correct, but also that getA() and getB() are actually called by getAPlusB():
def "test using all methods"() {
given: MyTestClass thing = Spy(MyTestClass)
when: def answer = thing.getAPlusB()
then: 1 * thing.getA()
1 * thing.getB()
answer == 3
}
So far this is running all the code on all 3 methods - getA and getB are verified as being called but the code in those methods are actually being executed. In your case, you are testing the inner methods seperately, and perhapse you do not want to call them at all during this test. By using the spock spy, you can instantiate a real instance of the class under test, but with the option of stubbing particular methods which you want to specify the value returned by:
def "test which stubs getA and getB"() {
given: MyTestClass thing = Spy(MyTestClass)
when: def answer = thing.getAPlusB()
then: 1 * thing.getA() >> 5
1 * thing.getB() >> 2
answer == 7
}

Returning Null or Nothing from VBScript function?

I'm trying to write the VBScript equivalent of a function similar to what's below:
object getObject(str)
{
if ( ... )
{
return object_goes_here;
}
return null;
}
My guess would be below, except that I'm not understanding the difference between Nothing and Null. As a caller, I'd rather test if the return value is set by using IsNull() versus X Is Nothing.
Function getObject(str)
If ... Then
Set getObject = object_goes_here
Exit Function
End If
Set getObject = Nothing // <-- or should this be Null?
End Function
The correct way to not return an object is to return Nothing and test for Is Nothing.
VB's Null is a special value of type Variant/Null. There are other special values, such as Variant/Empty or Variant/Error. They all have their use, but it's not the one.
Use the second Function skeleton. Avoid Null when dealing with objects, because of the Set Assignment abomination.
Dim oX : Set oX = getObject(...)
If oX Is Nothing Then
...
Else
nice object to work with here
End If
vs
Dim vX : vX = getObject(...) ' <-- no Set, no object
If IsNull(vX) Then
...
Else
no object to work with here
End If
In your sample code, the object gets always Nothing because that is the last action. This is how it should be:
Function getObject(str)
If ... Then
Set getObject = object_goes_here
Exit Function
End If
Set getObject = Nothing
End Function
or:
Function getObject(str)
Set getObject = Nothing
If ... Then
Set getObject = object_goes_here
End If
End Function
The answer of GSerg is correct: you should use Nothing. Additionally, to see if an object has a null reference, use:
If Not object Is Nothing Then
' do something
End If

Slow Scala assert

We've been profiling our code recently and we've come across a few annoying hotspots. They're in the form
assert(a == b, a + " is not equal to " + b)
Because some of these asserts can be in code called a huge amount of times the string concat starts to add up. assert is defined as:
def assert(assumption : Boolean, message : Any) = ....
why isn't it defined as:
def assert(assumption : Boolean, message : => Any) = ....
That way it would evaluate lazily. Given that it's not defined that way is there an inline way of calling assert with a message param that is evaluated lazily?
Thanks
Lazy evaluation has also some overhead for the function object created. If your message object is already fully constructed (a static message) this overhead is unnecessary.
The appropriate method for your use case would be sprintf-style:
assert(a == b, "%s is not equal to %s", a, b)
As long as there is a speciaized function
assert(Boolean, String, Any, Any)
this implementation has no overhead or the cost of the var args array
assert(Boolean, String, Any*)
for the general case.
Implementing toString would be evaluated lazily, but is not readable:
assert(a == b, new { override def toString = a + " is not equal to " + b })
It is by-name, I changed it over a year ago.
http://www.scala-lang.org/node/825
Current Predef:
#elidable(ASSERTION)
def assert(assertion: Boolean, message: => Any) {
if (!assertion)
throw new java.lang.AssertionError("assertion failed: "+ message)
}
Thomas' answer is great, but just in case you like the idea of the last answer but dislike the unreadability, you can get around it:
object LazyS {
def apply(f: => String): AnyRef = new {
override def toString = f
}
}
Example:
object KnightSpeak {
override def toString = { println("Turned into a string") ; "Ni" }
}
scala> assert(true != false , LazyS("I say " + KnightSpeak))
scala> println( LazyS("I say " + KnightSpeak) )
Turned into a string
I say Ni
Try: assert( a==b, "%s is not equals to %s".format(a,b))
The format should only be called when the assert needs the string. Format is added to RichString via implicit.

Resources