OBJECT MANIPULATION FUNCTION TEST ON on JEST - unit-testing

so I want to setup tests for many functions which are manipulating the order of elements in array.
const arr1 = [1,2,3];
const arr2 = [2,1,2];
function reorder(arr) {
// changes the order
}
as in javascript everything is reference we haven't been returning on the go, is there any way by which I can test this function with some inbuilt functions in jest without returning the values in the functions

Related

How to implement a property enumerator for a C++ native object in V8?

I'm writing a Node.js C++ module that communicates with a database which returns BSON objects, and wrap them in a V8 object so they can be accessed from the JavaScript.
For that I create an ObjectTemplate, and configure it through SetHandler. My getter and setter work, but the property enumerator does not return anything. Here is the code:
void PropertyEnumerator(const PropertyCallbackInfo<Array>& info)
{
// Enumerator, aka `Object.keys(obj)`
auto isolate = info.GetIsolate();
auto data = unrwap_internal_field<BsonObjectData>(info.Holder(), 0);
Local<Array> array = Array::New(isolate);
int i = 0;
bson_iter_t iter;
bson_iter_init_from_data(&iter, data->document_data, data->document_length);
while (bson_iter_next(&iter)) {
const char* key = bson_iter_key(&iter);
array->Set(i++, String::NewFromUtf8(isolate, key, v8::NewStringType::kNormal).ToLocalChecked());
}
info.GetReturnValue().Set(array);
}
I have checked that the function is actually called
I have checked that the array is populated with the right values
But in the JavaScript when I do console.log(Object.keys(obj)) I get an empty array. It's like info.GetReturnValue().Set(array); does not do anything. The documentation states that each element of the array must be a Name, and String inherits from Name so I really don't understand.
Thoughts?
As #jmrk suggested in their comment, the problem was that I didn't implement the query function for my object template. This made the enumerator work properly:
void PropertyQuery(Local<Name> property, const PropertyCallbackInfo<Integer>& info)
{
info.GetReturnValue().Set(PropertyAttribute::None);
}

How to speed up access to QList<qreal> exposed from C++ to QML

I have some problem with speed to access to QList<qreal> property.
I have declared:
Q_PROPERTY(QList<qreal> circlePointsX READ circlePointsX NOTIFY circlePointsXChanged);
QList<qreal> circlePointsX(void) const
{
return mCirclePointsX;
}
and in QML file, I made
pArea.circlesPointsX = paintAreaHelper.circlePointsX;
and after that some code is reading point by point:
var cPointsX = circlesPointsX;
var cPointsY = circlesPointsY;
var noOfPoints = circlesPointsX.length - 4;
for (var i = 0; i <= noOfPoints; i+=4)
{
ctx.moveTo(cPointsX[i], cPointsY[i]);
ctx.lineTo(cPointsX[i+1], cPointsY[i+1]);
ctx.lineTo(cPointsX[i+2], cPointsY[i+2]);
ctx.lineTo(cPointsX[i+3], cPointsY[i+3]);
ctx.lineTo(cPointsX[i], cPointsY[i]);
}
of course the type of property is var
property var circlesPointsX;#
and assignment:
var cPointsX = circlesPointsX;
does not speed up anything, because it's just copying the reference.
I debuged it, and for every single loop access, the c++ method is called.
I would like to copy the data from c++ once and access it from "local qml copy" instead of calling c++ getter every time.
The documentation sheds some light on it:
If the sequence is exposed as a Q_PROPERTY, accessing any value in the sequence by index will cause the sequence data to be read from the QObject's property, then a read to occur. Similarly, modifying any value in the sequence will cause the sequence data to be read, and then the modification will be performed and the modified sequence will be written back to the QObject's property.
If the sequence is returned from a Q_INVOKABLE function, access and mutation is much cheaper, as no QObject property read or write occurs; instead, the C++ sequence data is accessed and modified directly.
So, your solution is to declare circlePointsX as:
Q_INVOKABLE QList<qreal> circlePointsX() const { return mCirclePointsX; }
You should drop the circlePoints property, or rename it to something else.
Nitpick: Putting void in the parameter list is a C-ism that has no place in C++. The reason for it in C was that void foo() is equivalent to void foo(...). This is no longer the case in C++.

creating an array of objects within a function of a program

could someone please tell me what I need to do in order to create an array of objects in a function (other than in the main function).
I will try to explain by making up some sort of example...
Let's say I have a program named TimeScheduler.cpp that implements the class Schedule.h
(and I have the implementation in a separate file Schedule.cpp where we define the methods).
In the declaration file we have declared two constructors
Schedule(); //the default
and
Schedule(int, int, int);//accepts three arguments
to get to the point--let's say in the main program file TimeScheduler.cpp we created our own functions in this program apart from the functions inherited from the class Schedule. so we have our prototypes listed at the top.
/*prototypes*/
void makeSomeTime();
etc.....
we have
main(){
//etc etc...
}
we then define these program functions
void makeSomeTime(){
//process
}
let's say that inside the function makeSomeTime(), we would like to create an array of Schedule objects like this
Schedule ob[]={
summer(5,14, 49),
fall(9,25,50)
};
what do I have to do to the function makeSomeTime() in order for it to allow me to create this array of objects.
The reason I ask is currently i'm having difficulty with my own program in that it WILL allow me to create this array of objects in main()....but NOT in a function like I just gave an example of. The strange thing is it will allow me to create a dynamic array of objects in the function..... like
Schedule *ob = new Schedule[n+1];
ob[2]= Schedule(x,y,z);
Why would it let me assign to a non-dynamic array in main(), but not let me do that in the function?
This is not correct:
Schedule ob[]={
summer(5,14, 49),
fall(9,25,50)
};
You appear to be trying to introduce 3 new names:
ob, which is an array of Scedules
summer, which is a Schedule
fall, which is a Schedule
You can't introduce summer and fall as new names like that. Perhaps this was just a typo, and you meant:
Schedule ob[]={
Schedule(5,14, 49),
Schedule(9,25,50)
};
...which is perfectly fine, and can exist in a function such as:
void make_schedule()
{
Schedule ob[]={
Schedule(5,14, 49),
Schedule(9,25,50)
};
}
But now you have another problem -- your make_schedule function returns void. The Schedule array you created in make_schedule is created and then just thrown away. If you want to return an array from a functtion, the best thing to do is to use a vector, and return that:
std::vector<Schedule> make_schedule()
{
Schedule ob[]={
Schedule(5,14, 49),
Schedule(9,25,50)
};
const size_t num_obs = sizeof(ob)/sizeof(ob[0]);
std::vector<Schedule> ret;
std::copy( &ob[0], &ob[num_obs], std::back_inserter(ret));
return ret;
}
A poorer alternative is to use dynamic allocation to allocate your array, and return a pointer to the first element. In this case, when using new [] it's important to note that you can only use the default constructor.
I decided that instead of using a vector, I could use an unordered_map. I didn't realize that when you 'name' an object in c++, you aren't really giving it a name...it is simply used as a sort of temporary reference. if you want to use names you are better off using a name as a sort of key value in a set. like:
string foodname;
foodname = "cake";
[foodname, 10.95]
foodname = "bread";
[foodname, 5.75]
I found help with unordered_map on http://msdn.microsoft.com/en-us/library/bb981993.aspx

Specific actionscript functions for a c++ progammer

I am coming from the C++ world and i want to do some simple stuff with Actionscript 3.0.
Have search around this site and google and haven't found a universally accepted way to do so. I will give you the C++ code of the analogous of what I am trying to do in Actionscript 3.0.
Pass by reference:
void somefunction (string &passvariable);
Create instance of, deep copy:
string something;
string somethingelse;
something = "randomtext";
somethingelse = something;
Pass by reference
Every object is passed by reference. As far as I know, there are no explicit & address of or * dereference operators. Actionscript is a higher level language than that.
Primitive types (and Strings are primitive - see link) are Immutable in Actionscript, so pass by value / pass by reference are effectively the same.
Deep Copy / Instance of
ObjectUtil.clone / ObjectUtil.copy will create sometimes-deep copies of Objects, if you're working in Flex. I usually don't rely on it for anything deep, however. In most cases you will want to create your own clone style method to create a deep copy.
A generic, flexible clone method can be found here
The rules for pass as reference are different for simple data types like string and number than they are for objects and complex data types.
If you are passing a string to a function, it creates a copy, leaving the original untouched.
So to pass by reference, try creating an object:
var str:Object = {string:"foo"};
passByref(str);
trace(str.string);
private function passByref(str:Object):void
{
str.string = str.string + "bar";
trace("inside", str);
}
As for deep object cloning, this works great:
package
{
import flash.utils.ByteArray;
public class DeepCopyUtil
{
public static function clone (source : Object) : *
{
var array : ByteArray = new ByteArray ();
array.writeObject (source);
array.position = 0;
return array.readObject ();
}
}
}
Credit where credit is due:
http://cookbooks.adobe.com/post_How_to_create_deep_copies_of_objects_and_arrays-19261.html
In Actionscript you have to define all things with function, var or const.
You should define the (return type) after the variable name, like var:String
Creating a function
function someFunction (var:String):void
{
}
Copy a string
var something:String;
var somethingElse:String;
something = "randomtext";
somethingelse = something;

What is the easiest way to expose M-file subfunctions for unit testing?

I have been tinkering lately with fully integrating continuous testing into my Matlab development cycle and have run across a problem I don't know how to get around. As almost all users know, Matlab kindly hides sub-functions within an M-file from the view of any functions outside that M-file. A toy example can be seen below:
function [things] = myfunc(data)
[stuff] = mysubfunc(data)
things = mean(stuff);
end
I want to perform unit testing on subfunc itself. This is, AFAIK, impossible because I cannot call it from any external function.
I'm currently using Matlab xUnit by Steve Eddins and cannot get around this issue. The easy solution -- splitting subfunc out to its own M-file -- is not acceptable in practice because I will have numerous small functions I want to test and don't want to pollute my filesystem with a separate M-file for each one. What can I do to write and perform easy unit tests without making new files for each function I want to test?
What you need to do in general is get function handles to your subfunctions from within the primary function and pass them outside the function where you can unit test them. One way to do this is to modify your primary function such that, given a particular set of input arguments (i.e. no inputs, some flag value for an argument, etc.), it will return the function handles you need.
For example, you can add a few lines of code to the beginning of your function so that it returns all of the subfunction handles when no input is specified:
function things = myfunc(data)
if nargin == 0 % If data is not specified...
things = {#mysubfunc #myothersubfunc}; % Return a cell array of
% function handles
return % Return from the function
end
% The normal processing for myfunc...
stuff = mysubfunc(data);
things = mean(stuff);
end
function mysubfunc
% One subfunction
end
function myothersubfunc
% Another subfunction
end
Or, if you prefer specifying an input flag (to avoid any confusion associated with accidentally calling the function with no inputs as Jonas mentions in his comment), you could return the subfunction handles when the input argument data is a particular character string. For example, you could change the input checking logic in the above code to this:
if ischar(data) && strcmp(data, '-getSubHandles')
I have a pretty hacky way to do this. Not perfect but at least it's possible.
function [things] = myfunc(data)
global TESTING
if TESTING == 1
unittests()
else
[stuff] = mysubfunc(data);
things = mean(stuff);
end
end
function unittests()
%%Test one
tdata = 1;
assert(mysubfunc(tdata) == 3)
end
function [stuff] = mysubfunc(data)
stuff = data + 1;
end
Then at the prompt this will do the trick:
>> global TESTING; TESTING = 1; myfunc(1)
??? Error using ==> myfunc>unittests at 19
Assertion failed.
Error in ==> myfunc at 6
unittests()
>> TESTING = 0; myfunc(1)
ans =
2
>>
Have you used the new-style classes? You could turn that function in to a static method on a utility class. Then you could either turn the subfunctions in to other static methods, or turn the subfunctions in to local functions to the class, and give the class a static method that returns the handles to them.
classdef fooUtil
methods (Static)
function [things] = myfunc(data)
[stuff] = mysubfunc(data);
things = mean(stuff);
end
function out = getLocalFunctionHandlesForTesting()
onlyAllowThisInsideUnitTest();
out.mysubfunc = #mysubfunc;
out.sub2 = #sub2;
end
end
end
% Functions local to the class
function out = mysubfunc(x)
out = x .* 2; % example dummy logic
end
function sub2()
% ...
end
function onlyAllowThisInsideUnitTest()
%ONLYALLOWTHISINSIDEUNITTEST Make sure prod code does not depend on this encapsulation-breaking feature
isUnitTestRunning = true; % This should actually be some call to xUnit to find out if a test is active
assert(isUnitTestRunning, 'private function handles can only be grabbed for unit testing');
end
If you use the classdef style syntax, all these functions, and any other methods, can all go in a single fooUtil.m file; no filesystem clutter. Or, instead of exposing the private stuff, you could write the test code inside the class.
I think the unit testing purists will say you shouldn't be doing this at all, because you should be testing against the public interface of an object, and if you need to test the subparts they should be factored out to something else that presents them in its public interface. This argues in favor of making them all public static methods and testing directly against them, forgetting about exposing private functions with function handles.
classdef fooUtil
methods (Static)
function [things] = myfunc(data)
[stuff] = fooUtil.mysubfunc(data);
things = mean(stuff);
end
function out = mysubfunc(x)
out = x .* 2; % example dummy logic
end
function sub2()
% ...
end
end
end
I use a method that mirrors the way GUIDE use to generate its entry methods. Granted it's biased towards GUIs...
Foo.m
function varargout=foo(varargin)
if nargin > 1 && ischar(varargin{1}) && ~strncmp( varargin{1},'--',2)
if nargout > 0
varargout = feval( varargin{:} );
else
feval = ( varargout{:} );
else
init();
end
This allows you to do the following
% Calls bar in foo passing 10 and 1
foo('bar', 10, 1)