Get from IQueryable to IEnumerable - casting

this should be a quick one for all you f# rockers, but it's got me stuck at the moment.
I've got an F# type which I'm trying to get to implement a c# interface
public interface ICrudService<T> where T: DelEntity, new()
{
IEnumerable<T> GetAll();
}
here's how it's implemnted in c#:
public IEnumerable<T> GetAll()
{
return repo.GetAll();
}
repo.GetAll returns an IQueryable, but the c# compiler knows enough to convert to IEnumerable because IQueryable<T> : IEnumerable<T>. but In F# the compiler can't work it and I've tried a few attempt to cast it correctly
type CrudService<'T when 'T :(new : unit -> 'T) and 'T :> DelEntity>(repo : IRepo<'T>) =
interface ICrudService<'T> with
member this.GetAll () =
repo.GetAll<'T>
this is giving me a type mismatch error

You need to cast to IEnumerable<'T>:
type CrudService<'T when 'T :(new : unit -> 'T) and 'T :> DelEntity>(repo : IRepo<'T>) =
interface ICrudService<'T> with
member this.GetAll () =
repo.GetAll() :> IEnumerable<'T>

What if you used Seq.cast<'T? It sounds like it just needs to be casted to the correct Type. Since IEnumerables are implemented differently in F# than they are in C#.
let seqCast : seq<int> = Seq.cast repo.GetAll<'T>

Related

How to get java class from object in kotlin?

I am trying mockito to mock a getValue function that consumes a java class as parameter.
To simplify, i did the following test:
#Test
fun test1() {
val map = HashMap<String,Any>()
val v:Long = 1L
map["K"]= v
println(map["K"]!!::class.java) //prints class java.lang.Long
println(Long::class.java) //prints long
val dss = Mockito.mock(DataSnapshot::class.java)
Mockito.`when`(dss.getValue( map["K"]!!::java.class))
.thenReturn( map["K"]!!)
//production code uses calls the function like this but it fails to get the value. Returns null;
Assert.assertEquals( map["K"],dss.getValue(Long::class.java))
}
As the prints show, the type in map["K"]!!::class.java is different from Long::class.java.
If i mock the method using the type inline it works:
Mockito.`when`(dss.getValue( Long::class.java))
.thenReturn( map["K"]!!)
How can i mock the method in a way that the type parameter hasn't to be determined by a long switch logic?
Some insides in kotlin and java types could help.
If you're asserting against java.lang.Long, use Long?::class.java. Long::class.java will give you the primitive long on the JVM. Nullable Long instead maps to the boxed version - java.long.Long.

How to use a functor in OCaml

I can't find on the internet how to use the functor I've written. I will post a minimal code, if you need more contextual information tell me and I'll add, but I'm sure it's really easy to do.
I think I just don't understand what a functor is, I see things like this (I will use an analogy with Java to ilustrate my understanding since I'm new to OCaml) :
sig (=) Interface MyInterface
struct (=) Object implements MyInterface
functor (=) MyInterfaceBis extends MyInterface
The following example I'm about to give is stupid, it's just so I can understand the concept behind it :
module type tF = sig
type 'a t
val create : 'a t
end
module F : tF = struct
type 'a t = 'a list
let create = []
end
module type tF2 = functor(F : tF) -> sig
val foo : 'a F.t -> 'a F.t
end
module F2 : tF2 = functor(F : tF) -> struct
let foo f = f
end
I know I can do for example :
let test = F.create
But I don't know how to use F2.
I've tried this page but it's not using my notation and I was more confused after than before.
F2 takes in a module with type tF and produces a module with one function foo:
module NewF = F2 (F)
For more information, see the section about functors in Real World OCaml.

Testing interfaces with foq

I am trying to use Foq to testing an interface with Foq.
So far, all examples I have seen for this have been relatively simple, such as the following:
let users = [|{ID = 1; pass = true};{ID = 2; pass= false}|]
type IFoo =
abstract member Bar: int -> bool
//tests with Foq
let dataAccess =
Mock<IFoo>()
.Setup(fun x-> <# x.Bar(users.[0].ID) #>).Returns(users.[0].pass)
.Setup(fun x-> <# x.Bar(users.[1].ID) #>).Returns(users.[1].pass)
.Create()
The examples have been sourced from 'Testing with F# - Mikael Lundin'
I have also researched this through a bit of googling (this link was helpful - http://trelford.com/blog/post/Foq.aspx)
However, the real Interfaces I want to test are the following:
type IParameters =
abstract member ParameterDate : int->string->DateTime
type IDataSource =
abstract member MortParameters: IParameters
I have tried a number of different ways to test these (e.g. defining a function with a signature of int->string to be used as the input to the setup. Alternatively, having the return value as a string->DateTime and the Setup as just an integer.
My question is really the following: When testing interfaces using Foq, how can I extend the testing to interfaces with function signatures of any general length (e.g. a->b->c->d->e etc.)
Since ParameterDate a property with a function type, you could just set it up as a property that returns a lambda value. See an example of property set-up in Foq. This should be easy to modify for your case:
let instance =
Mock<System.Collections.IList>()
.Setup(fun x -> <# x.Count #>).Returns(1)
.Create()
However, I guess you would lose the ability to have a strict mock with fixed expectations on the function inputs.
To enforce only expected inputs for the function returned by the mock property you could provide a function like this:
fun i s ->
match i, s with
| 1, "" -> DateTime.Now
| _ -> failwith "Invalid mock input"
I would probably stop here, but if you're working with code where you need to verify a function was called, as opposed to just ensuring you get the correct output, you could add a helper like this:
type Verifiable<'a, 'b> (f : 'a -> 'b) =
let called = ref false
member this.Func x =
called := true
f x
member this.Verify() =
if not called.Value then failwith "Mock function was not called"
And here's how you would use it:
let parameterDateMock =
fun i s ->
match i, s with
| 1, "" -> DateTime.Now
| _ -> failwith "Unexpected mock input"
|> Verifiable
let parameters =
{ new IParameters with member this.ParameterDate i s = parameterDateMock.Func i s }
parameters.ParameterDate 1 ""
parameterDateMock.Verify()
Caveat: This only verifies the function was called with at least one parameter. It may have returned another function by currying and not actually run the code in the mock function body. To get around that you'd need a variation of the Verifiable class for every function arity and use the right one in each case.

binding library : returning untyped object - method definition

Part of a library I'm trying to bind returns an object -
Editor.prototype.getHandlers = function() {
return {
'shape.append': require('./draw/AppendShapeHandler'),
'shape.create': require('./draw/CreateShapeHandler')
};
};
What I can't figure out is how to specify the class type as the returned object is anonymous :
class type editor = object
method getHandlers : ? Js.t Js.opt Js.meth
end
Could anyone suggest a way forward here?
Thanks
Nick
For this case, perhaps something like:
class type editor = object
method getHandlers : <shape_append : Js.js_string Js.t Js.meth> Js.t Js.meth
end
More example:
class type server = object
method listen : int -> (unit -> unit) Js.callback -> unit Js.meth
method close : (unit -> unit) Js.callback -> unit Js.meth
method address :
<address: Js.js_string Js.t Js.readonly_prop;
family : Js.js_string Js.t Js.readonly_prop;
port: Js.js_string Js.t Js.readonly_prop> Js.t Js.meth
end
This approach, of binding this way, works but as I learned in my OCaml nodejs bindings, its better to write at a higher level rather than do these bindings. https://github.com/fxfactorial/ocaml-nodejs (Look at early git history for many more examples like this)

using Moq and generic type boxing issue

I tried to make a generic helper method using Moq with nunit as described below
public void PrepareWebRequest<T>() where T : new()
{
httpCommunicator = new Mock<IHttpCommunicator>();
httpCommunicator.Setup(x => x.Post(It.IsAny<Object>(),
It.IsAny<string>())).Throws<T>();
service = new ApiClient(httpCommunicator.Object);
}
But this causes the following error:
The type 'T' cannot be used as type parameter 'TException' in the generic type or method 'Moq.Language.IThrows.Throws()'. There is no boxing conversion or type parameter conversion from 'T' to 'System.Exception'.
I know this can be refactored by not using the generic method on Moq, but would really like to know what I'm doing wrong.
Best regards
Rasmus
Problem was a missing Exception in the Where clause. Should be
public void PrepareWebRequest<T>() where T : Exception, new()
{
httpCommunicator = new Mock<IHttpCommunicator>();
httpCommunicator.Setup(x => x.Post(It.IsAny<Object>(),
It.IsAny<string>())).Throws<T>();
service = new ApiClient(httpCommunicator.Object);
}