Is there a way in CppUtest that can call mock and real function at runtime in the same test file? - cpputest

For example:
Production.cpp
int func1()
{
return 7;
}
void func2()
{
printf("func2");
}
void productionCode()
{
int x = func1();
if(x==7) func2();
}
TestProduction.cpp
int func1()
{
return mock().actualCall("func1").
returnIntValue();
}
void setExpFunc1(int x)
{
mock().expectOneCall("func1")
andReturnValue(x);
}
TEST(testGroupSample, testMockFunc1)
{
setExpFunc1(8);
// this will call mock func1()
productionCode();
}
TEST(testGroupSample, testRealFunc2)
{
// this will call real func1()
productionCode();
}
From my understanding, when func1() was mocked, there's no way to test the actual function.
Below sample code is just an idea on what I'm trying to do.
Because I have to test many functions that calls many functions inside.
Sometimes, I don't care on the actual result of those other function so I mocked it, but when I want to test the behavior of the real function when calling inside a function that I'm testing, I cannot do it since that function is already mocked.
Also I hope I can do this without modifying the production code, only the tests code.

No. You mocked using the linker, so, for the whole file context, the real functions do not exist.

You may achieve this by using function pointers (or std::function, …) to set the implementation used by productionCode() at runtime.
Pseudocode
int func1() { /* Production }
int func1_mock() { /* Mock */ }
std::function<int()> impl; // Use a function ptr for C
void productionCode()
{
int x = impl(); // Call current implementation
// ...
}
TEST(...)
{
impl = func1; // Use production code
productionCode();
impl = func1_mock; // Use mock instead
productionCode();
}

Related

How to detect a usertype is exist in sol3?

In C++ with sol3, My code is like this
sol::state _state;
void Func1()
{
auto userType1 = _state.new_usertype<Test>("Test", sol::constructors<Test()>());
userType1["testFunction1"] = &test1;
}
void Func2()
{
auto userType2 = _state.new_usertype<Test>("Test", sol::constructors<Test()>());
userType2["testFunction2"] = &test2;
}
int main()
{
Func1();
Func2();
}
In lua script, I can only call Test.testFunction2 which means that userType2 override userType1. The lua script can not see testFunction1. I wonder if there is a way to return the userType if exist, and create it if not. Then I can call both testFunction1 and testFunction2. As the code shown below.
void Func1()
{
auto userType1 = _state.CreateOrGetUserType<Test>("Test", sol::constructors<Test()>());
userType1["testFunction1"] = &test1;
}
void Func2()
{
auto userType2 = _state.CreateOrGetUserType<Test>("Test", sol::constructors<Test()>());
userType2["testFunction2"] = &test2;
}
First check whether _state["Test"] exists (and if you are really paranoid, check that it is a table). If so, use it to construct a sol::usertype<Test> to which you can add the second function. If not, create a new usertype as you are doing.

Calling Generic Types function

is it possible to call generic types function.
if not is there a different approach to something like this.
someFunction<T>(){
T.anotherFunction();
}
EDIT
MyModel model = NetworkClient.sendRequest<MyModel>(url);
static Future<T> sendRequest<T>(String URL){
//send request
var res = data.toString();
return T.fromJson(json.decode(res))
}
void main() {
someFunction(Foo());
someFunction(Bar());
}
someFunction<T>(T t) {
if (t is Foo)
t.fooFunc();
else if (t is Bar)
t.barFunc();
else
throw Exception("Unknown type: ${t.runtimeType}");
}
class Foo {
void fooFunc() {
print("foo");
}
}
class Bar {
void barFunc() {
print("bar");
}
}
Put your method (lets say MyMethod) in an interface or base class. Lets say MyInterface.
Then use a constraint on your generic type:
someFunction<T extends MyInterface>(T t){
t.MyMethod();
}
Since you cannot have constructors in an interface, your plan with the fromJson might not work out. I don't know your class structure. But you can write generics with specific constraints in mind.

Javascript Module pattern and closures

I'm trying to get my head around the module pattern in Javascript and have come across various different ways that I can see to do it. What is the difference (if any) between the following:
Person = function() {
return {
//...
}
};
person1 = Person();
function Person2() {
return {
//...
}
}
person2 = Person2();
person3 = function() {
return {
//...
}
}();
person4 = (function() {
return {
// ...
}
})();
person5 = (function() {
return {
// ...
}
}());
They all seem to do the same thing to me.
// This creates a function, which then returns an object.
// Person1 isn't available until the assignment block runs.
Person = function() {
return {
//...
}
};
person1 = Person();
// Same thing, different way of phrasing it.
// There are sometimes advantages of the
// two methods, but in this context they are the same.
// Person2 is available at compile time.
function Person2() {
return {
//...
}
}
person2 = Person2();
// This is identical to 'person4'
// In *this* context, the parens aren't needed
// but serve as a tool for whoever reads the code.
// (In other contexts you do need them.)
person3 = function() {
return {
//...
}
}();
// This is a short cut to create a function and then execute it,
// removing the need for a temporary variable.
// This is called the IIFE (Immediate Invoked Function Expression)
person4 = (function() {
return {
// ...
}
})();
// Exactly the same as Person3 and Person4 -- Explained below.
person5 = (function() {
return {
// ...
}
}());
In the contexts above,
= function() {}();
= (function() {}());
= (function() {})();
All do exactly the same thing.
I'll break them down.
function() {}();
<functionExpression>(); // Call a function expression.
(<functionExpression>()); // Wrapping it up in extra parens means nothing.
// Nothing more than saying (((1))) + (((2)))
(<functionExpression>)();
// We already know the extra parens means nothing, so remove them and you get
<functionExpression>(); // Which is the same as case1
Now, all of that said == why do you sometimes need parens?
Because this is a *function statement)
function test() {};
In order to make a function expression, you need some kind of operator before it.
(function test() {})
!function test() {}
+function test() {}
all work.
By standardizing on the parens, we are able to:
Return a value out of the IIFE
Use a consistent way to let the reader of the code know it is an IIFE, not a regular function.
The first two aren't a module pattern, but a factory function - there is a Person "constructor" that can be invoked multiple times. For the semantic difference see var functionName = function() {} vs function functionName() {}.
The other three are IIFEs, which all do exactly the same thing. For the syntax differences, see Explain the encapsulated anonymous function syntax and Location of parenthesis for auto-executing anonymous JavaScript functions?.
I've found a extremely detail page explaining this kind of stuff
Sth called IIFE
Hope will help.

Porting javascript to dart

I'd like to port this javascript code to dart.
function Beagle() {
this.argv_ = null;
this.io = null;
};
Beagle.prototype.run = function() {
this.io = this.argv_.io.push();
};
runCommandClass(Beagle);
the probleme is
How to create object Beagle
How to create prototype object Beagle.prototype.run
This kind of Js code (function definition and prototype changes) can be ported to a Dart class. You can follow these main rules :
function Xxxx(){/* js code to init */} (pseudo Js class) translates to :
class Xxxx {
/// constructor
Xxxx() {
/* Dart code to init */
}
}
when you have contructor parameters like in function Xxxx(param1, param2){/* js code to init */} you have to create an other constructor with those parameters :
class Xxxx {
/// constructor with parameters
Xxxx(param1, param2) {
/* Dart code to init with param1, param2 */
}
}
Xxxx.prototype.method1 = function(p1, p2, p3){/* js code for method */} are like methods that have to be translated to :
class Xxxx {
// .... other code
/// method
method1(p1, p2, p3) {
/* Dart code */
}
}
To make your code more clear you can also add type annotations on methods and constructors. This is recommanded by the Dart Style Guide.
Type annotations are important documentation for how a library should be used. Annotating the parameter and return types of public methods and functions helps users understand what the API expects and what it provides.
For instance :
class Xxxx {
/// constructor
Xxxx(String param1, int param2) {
/* Dart code to init with param1, param2 */
}
/// method
void method1(num p1, String p2, DateTime p3) {
/* Dart code */
}
}
class Beagle { //
Map argv_;
int io;
Map portInfo;
// could make sense to make this a constructor, that depends how the Terminal class uses it (didn't look)
void run(this.argv_) {
this.portInfo_ = JSON.parse(this.argv_['argString']); // not tested
io = argv_['io'].length;
}
void sendString_(String s) { // no idea what the underlines at the end of argv_, sendString_, ... are for
// ...
}
void onRead_(String s) {}
void onTerminalResize_(int width, int height) {}
void exit(code) {
// ...
}
void close() {
// ...
}
}
var b = new Beagle(); // not translated from the JS source - just added to show how to create a new object from the Beagle class
b.run(argvFromSomewhere);
This includes a some guessing about what the intention of the JavaScript code might be.
I prefer using specific types when porting from JavaScript. It helped me a lot finding bugs and understanding the intention. When I guessed the wrong type I get an exception at runtime, then I can reason about why I got an unexpected type and which of my assumptions were wrong.

Assign function/method to variable in Dart

Does Dart support the concept of variable functions/methods? So to call a method by its name stored in a variable.
For example in PHP this can be done not only for methods:
// With functions...
function foo()
{
echo 'Running foo...';
}
$function = 'foo';
$function();
// With classes...
public static function factory($view)
{
$class = 'View_' . ucfirst($view);
return new $class();
}
I did not found it in the language tour or API. Are others ways to do something like this?
To store the name of a function in variable and call it later you will have to wait until reflection arrives in Dart (or get creative with noSuchMethod). You can however store functions directly in variables like in JavaScript
main() {
var f = (String s) => print(s);
f("hello world");
}
and even inline them, which come in handy if you are doing recusion:
main() {
g(int i) {
if(i > 0) {
print("$i is larger than zero");
g(i-1);
} else {
print("zero or negative");
}
}
g(10);
}
The functions stored can then be passed around to other functions
main() {
var function;
function = (String s) => print(s);
doWork(function);
}
doWork(f(String s)) {
f("hello world");
}
I may not be the best explainer but you may consider this example to have a wider scope of the assigning functions to a variable and also using a closure function as a parameter of a function.
void main() {
// a closure function assigned to a variable.
var fun = (int) => (int * 2);
// a variable which is assigned with the function which is written below
var newFuncResult = newFunc(9, fun);
print(x); // Output: 27
}
//Below is a function with two parameter (1st one as int) (2nd as a closure function)
int newFunc(int a, fun) {
int x = a;
int y = fun(x);
return x + y;
}

Resources