Golang testing with functions - function

I am using a third-party library that is a wrapper over some C functions. Unfortunately, nearly all of the Go functions are free (they don't have a receiver, they are not methods); not the design approach I would have taken but it is what I have.
Using just Go's standard "testing" library:
Is there a solution that allows me to create tests where I can mock functions?
Or is the solution to wrap the library into structures and interfaces, then mock the interface to achieve my goal?
I have created a monte carlo simulation that also process the produced dataset. One of my evaluation algorithms looks for specific models that it then passes the third-party function for its evaluation. I know my edge cases and know what the call counts should be, and this is what I want to test.
Perhaps a simple counter is all that is needed?
Other projects using this library, that I have found, do not have full coverage or no testing at all.

You can do this by using a reference to the actual function whenever you need to call it.
Then, when you need to mock the function you just point the reference to a mock implementation.
Let's say this is your external function:
// this is the wrapper for an external function
func externalFunction(i int) int {
return i * 10 // do something with input
}
You never call this directly but instead declare a reference to it:
var processInt func(int) int = externalFunction
When you need to invoke the function you do it using the reference:
fmt.Println(processInt(5))
Then, went you want to mock the function you just assign a mock implementation to that reference:
processInt = mockFunction
This playground puts it together and might be more clear than the explanation:
https://play.golang.org/p/xBuriFHlm9
If you have a function that receives a func(int) int, you can send that function either the actual externalFunction or the mockFunction when you want it to use the mock implementation.

Related

Accessing regmap RegFields

I am trying to find a clean way to access the regmap that is used with *RegisterNode for creating documentation and testing files. The TLRegisterNode has methods for generating the json through some Annotations. These are done in the regmap method by adding them to the ElaborationArtefacts object. Other protocols don't seem to have these annotations.
Is there anyway to iterate over the "regmap" Register Fields post elaboration or during?
I cannot just access the regmap as it's not really a val/var since it's a method. I can't quite figure out where this information is being stored. I don't really believe it's actually "storing" any information as much as it is simply creating the hardware to attach the specified logic to the RegisterNode based logic.
The JSON output is actually fine for me as I could just write a post processing script to convert JSON to my required formats, but I'm wondering if I can access this information OR if I could add a custom function call at the end. I cannot extend the case class *RegisterNode, but I'm not sure if it's possible to add custom functions to run at the end of the regmap method.
Here is something I threw together quickly:
//in *RegisterRouter.scala
def customregmap(customFunc: (RegField.Map*) => Unit, mapping: RegField.Map*) = {
regmap(mapping:_*)
customFunc(mapping:_*)
}
def regmap(mapping: RegField.Map*) = {
//normal stuff
}
A user could then create a custom function to run and pass it to the regmap or to the RegisterRouter
def myFunc(mapping: RegField.Map*): Unit = {
println("I'm doing my custom function for regmap!")
}
// ...
node.customregmap(myFunc,
0x0 -> coreControlRegFields,
0x4 -> fdControlRegFields,
0x8 -> fdControl2RegFields,
)
This is just a quick example I have. I believe what would be better, if something like this was possible, would be to have a Seq of functions that could be added to the RegisterNode that are ran at the end of the regmap method, similar to how TLRegisterNode currently works. So a user could add an arbitrary number and you still use the regmap call.
Background (not directly part of question):
I have a unified register script that I have built over the years in which I describe the registers for a particular IP. It works very similar to the RegField/node.regmap, except it obviously doesn't know about diplomacy and the like. It will generate the Verilog, but also a variety of files for DV (basic `defines for simple verilog simulations and more complex uvm_reg_block defines also with the ability to describe multiple of the IPs for a subsystem all the way up to an SoC level). It will also print out C Header files for SW and Sphinx reStructuredText for documentation.
Diplomacy actually solves one of the main issues I've been dealing with so I'm obviously trying to push most of my newer designs to Chisel/Diplo.
I ended up solving this by creating my own RegisterNode which is the same as the rocketchip RegisterNodes except that I use a different Elaboration Artifact to grab the info and store it for later.

How to declare Function's bind method for TypeScript

I am trying to use Mootools together with TypeScript. Mootools, and some modern browsers support .bind method, which is polymorphic.
How can I properly declare this feature in a *.d.ts file, to be able to use constructs like [1,2].map(this.foo.bind(this)); ?
I know I can avoid such constructs by using lambdas, but sometimes I do not want to.
Perhaps there is a mootools.d.ts file somewhere which I could download instead of reinventing it myself?
TypeScript's lib.d.ts already defines the bind function's signature in the Function interface as follows:
bind(thisArg: any, ...argArray: any[]): Function;
I don't think there's any better way of doing it until generics get added to the language.
For the time being though, if you want to use bind and the recipient of the resulting function expects a specific signature, you're going to have to cast the function back to that signature:
var bfn : (p: number) => string;
bfn = <(p: number) => string> fn.bind(ctx);
There's a growing list of definition files being tracked here.
As for generating methods pre-bound to their this pointer in TypeScript I've suggested two ways of doing this. 1) a simple base class I defined at the end of this thread. and 2) a more advanced mixin & attribute system here.

Do I need to implement the NPN functions myself?

I got my header files from: http://code.google.com/p/npapi-sdk/source/browse/?r=7#svn%2Fwiki
So in the Initialize method, I stored a pointer to all of the browser NPN methods like so
static NPNetscapeFuncs* browser;
NPError NP_Initialize(NPNetscapeFuncs* browserFuncs)
{
/* Save the browser function table. */
browser = browserFuncs;
return NPERR_NO_ERROR;
}
When I am creating my NPClass struct, should I just assign it the already existing browser functions like this:
struct NPClass class;
class.hasMethod = browser-> hasmethod;
etc.
Or do I need to implement the functions in the npruntimeheader using the browser funcs and assign them to the class that way. Example:
class.hasMethod = NPN_HasMethod;
And then implement the function below:
bool NPN_HasMethod(NPP npp, NPObject *npobj, NPIdentifier methodName)
{
return browser->hasmethod(npp, npobj, methodName);
}
Or are the NPN functions in the runtime header already implemented somehow?
I need to write this in c, and I don't think using firebreath would be a great idea for this particular project. Thanks in advance for your help
You need to implement the functions for your NPClasses yourself, they define the behaviour of your scriptable objects. Part three of taxilians NPAPI tutorial covers this.
The functions that you receive via the browser function table are for calling into the browser (and already implemented there), e.g. to get information about NPObjects with hasmethod etc.
However the function declarations like NPN_HasMethod() need to be implemented by you if you want to use them, at their simplest just calling the corresponding functions in browser as you have shown with HasMethod().

What are callback methods?

I'm a programming noob and didn't quite understand the concept behind callback methods. Tried reading about it in wiki and it went over my head. Can somebody please explain this in simple terms?
The callback is something that you pass to a function, which tells it what it should call at some point in its operation. The code in the function decides when to call the function (and what arguments to pass). Typically, the way you do this is to pass the function itself as the 'callback', in languages where functions are objects. In other languages, you might have to pass some kind of special thing called a "function pointer" (or similar); or you might have to pass the name of the function (which then gets looked up at runtime).
A trivial example, in Python:
void call_something_three_times(what_to_call, what_to_pass_it):
for i in xrange(3): what_to_call(what_to_pass_it)
# Write "Hi mom" three times, using a callback.
call_something_three_times(sys.stdout.write, "Hi mom\n")
This example let us separate the task of repeating a function call, from the task of actually calling the function. That's not very useful, but it demonstrates the concept.
In the real world, callbacks are used a lot for things like threading libraries, where you call some thread-creation function with a callback that describes the work that the thread will do. The thread-creation function does the necessary work to set up a thread, and then arranges for the callback function to be called by the new thread.
Wiki says:
In computer programming, a callback is
a reference to executable code, or a
piece of executable code, that is
passed as an argument to other code.
This allows a lower-level software
layer to call a subroutine (or
function) defined in a higher-level
layer.
In common terms it is the mechanism to notify a piece of code i.e. a method, which piece of code to execute, i.e. another method, when it is needed.
Callback is related to the fact that the client of the calling function specifies a function that belongs to the client code's responsibility to the calling function to execute and this is passed as an argument.
An example is in GUIs. You pass as argument the function to be called once an event occurs (e.g. button pressed) and once the event
occurs this function is called.
This function is usually implemented by the object that originally registered for the event
Callback function is a function that is called through a function pointer. If you pass the pointer (address) of a function as an argument to another, when that pointer is used to call the function it points to it is said that a call back is made.
Why Should You Use Callback Functions?
A callback can be used for notifications. For instance, you need to set a timer in your application. Each time the timer expires, your application must be notified. But, the implementer of the time'rs mechanism doesn't know anything about your application. It only wants a pointer to a function with a given prototype, and in using that pointer it makes a callback, notifying your application about the event that has occurred. Indeed, the SetTimer() WinAPI uses a callback function to notify that the timer has expired (and, in case there is no callback function provided, it posts a message to the application's queue).
In general you supply a function as a parameter which gets called when something occurs.
In C code you will pass something that looks like this:
int (callback *)(void *, long );
meaning a function that takes two parameters, void * and long and returns an int.
With object-orientated languages the syntax is sometimes simpler. For example you might be able to construct a callback mechanism that allows the user to pass in an object that looks like a function or has an abstract method (thus wrapping a function) and context data too.
Modern languages use the term "delegate" to refer to a function "pattern". These can be used as callbacks. Some languages also use the term lambda which is essentially a function with no name, often created "on the fly" in a block of code and passed as a callback.
C++11 has introduced these into its standard.
The advantage of using a callback is that you can separate out, i.e. reduce / decouple an API from what is calling it, and to some extent vice versa, i.e. although in one place you know you are calling into the API, at the point of the "handler" it does not need to know from where it was called.
For example, you can have an API that generates objects and then "calls-back" as they get generated.
Call back means that you pass the code as a parameter. For example, imagine a button, that much show a dialog when pressed:
Button testBtn;
testBtn.setOnClickListener(new OnClickListener() {
#Override
public void onCLick() {
JOptionPane.showDialog(testBtn, "Test button pressed");
}
}
Here we tell the button what to execute, when it will be click. So, the framework will execute the passed code, when it detecs the click. Inside the framework there are some code like:
void processEvent(Event e) {
if (e.type == Event.CLICK) {
e.getComponent().getOnClickListener().onClick();
}
}
So, some basic code calls back the listener when the appropriate event happens.
PS: Pseudocode here, just do describe the idea.
A callback method is a method that gets called when an event occurs
In simple word, actually, a Callback is a reference to a function or method, which you can pass as a parameter to another function for calling it back later.
From the above figure, B_reference() is the callback method.
Source code sample:
>>> def A(A_msg,B_reference):
... # After printing message, method B is called.
... print(A_msg)
... B_reference()
...
>>> def B():
... print("Message from B")
...
>>>
>>> A("Message from A",B)
Message from A
Message from B
>>>
If you still don't understand what it is, you can check this video:

Whats the difference between C# delegates, Dynamic Proxy, Closures and function pointers?

What are useful definitions for the common methods of passing a method or function as data, such as:
Delegates
Closures
Function pointers
Invocation by dynamic proxy and
First class methods?
Function pointers lets you pass functions around like variables. Function pointer is basically legacy method to pass function around in languages that don't support first-class methods, such as C/C++.
First class methods Basically means you can pass functions around like variables. Methods (loosely) mean functions. So this basically means first class functions. In simplest terms, it means functions are treated as "first class citizens", like variables. In the old days (C/C++), because we can't directly pass a function around, and we had to resort to workarounds like function pointers, we said functions weren't first-class citizens.
Delegates is C#'s answer to first-class methods. Delegates are somewhat more powerful because it involves closures, consider the following code snippet:
void foo( int a )
{
void bar() { writefln( a ); }
call( &bar );
}
void call( void delegate() dg ) { dg(); }
int main( char[][] args ) {
foo( 100 );
}
Notice that bar can reference the local variable a because delegates can use closures.
Closures can be very confusing at first. But the lazy-man's definition can be really simple. It basically means a variable can be available in the human-expected way. Put in other words, a variable can be referenced in places where they look like they would be present, by reading the structure of the source code. For example, looking at the code fragment above. If we didn't have closure, bar would not be able to reference a because a was only local to foo, but not bar, which is another function.
Dynamic Proxy is the odd one out. It doesn't belong to these items. Explaining it requires some very long text. It stems from the famous Proxy Pattern. The problem with Proxy Pattern was that the Proxy class needs to be implementing the same interface as the Subject. Dynamic Proxy basically means using reflective approach to discover the Subject's method so that the ProxyPattern can be freed from being tied to the Subject's interface.
just the ones i know about:
Function pointers: just that, a pointer to a piece of code. you jump to it, it executes. typed languages can enforce some parameter passing convention (i.e. C declarations)
Closures: a function with some state paired. most naturally written in lexically scoped languages (i.e. Scheme, JavaScript, Lua). several closures can share the same state (or part of it), making it an easy way to implement OOP.
First class methods: a closure created from an object instance and a method. some languages with both closures and a native OOP (Python, JavaScript) can create closures automatically.
Closure is a programming language concept. Delegate is its realization in MS.NET.
A Delegate in MS.NET is a strongly typed pointer to an object's method (a delegate instance points to both - an object and its method). There is also a way to combine several void delegate instances into one.