How to assert that every item in collection is within range - arrays

I have a Groovy array that will get a set number of random Integer Values. And I want to assert that each item in the array has a value within the given range. I'm trying to use Hamcrest Matchers. So my test looks like this:
#Test
void testShouldReturnArrayOfStats(){
def results = pg.rollStats()
assertThat results, everyItem(both(greaterThan(0)).and(lessThanOrEqualTo(6)))
}
When I run the test I get an assertionError
java.lang.AssertionError: Expected: every item is (a value greater than <0> and a value less than or equal to <6>)
but: was [<6>, <3>, <5>, <4>, <3>, <2>]
I've tried some variations of this but I'm not getting a passing test. just by looking at the "But:was" portion of the error I can seen that all 6 values meet the requirements, but the test still fails.
I've not used Groovy or Hamcrest for very long so I'm sure that I'm missing something.
Thanks

Could you just use groovy?
assert results.every { it in 1..6 }

Related

kotlin "contains" doesn't work as expected

I am working with a method which filters the preferences which match with the ids, I am using the contains method, but even though the values are the same, the contains is showing a false in each iteration. The method looks like:
private fun filterPreferencesByIds(context: MyPodCastPresenterContext): List<FanPreferences> {
return context.preferences?.filter {
context.ids.contains(it.id)
}
}
The values of the arrays are:
for the context.ids:
"B52594F5-80A4-4B18-B5E2-8F7B12E92958" and "3998EDE7-F84B-4F02-8E15-65F535080100"
And for the context.preferences:
But even though, when the first and the final ids have the same id value as the context.ids, the contains is false in the debug. I think it could be related with the types in the context.ids rows Json$JsonTextNode. Because when I did the same with numeric values hardcoded the compare is successful.
Any ideas?
Thanks!
If the type of FanPreferences.id is String and the type of context.ids list element is JsonTextNode, you won't find an element equal to the given id string, because it's not of String type.
Try mapping your context ids to the list of strings before filtering:
val ids = context.ids.map { it.toString() }.toSet()
return context.preferences?.filter {
ids.contains(it.id)
}
Note that calling toString() on JsonTextNode might be not the best way to get the string data from it. It's better to consult the API documentation of that class to find it out.

How to find which element failed comparison between arrays in Kotlin?

I'm writing automated tests for one site. There's a page with all items added to the cart. Maximum items is 58. Instead of verification of each element one by one I decided to create 2 arrays filled with strings: 1 with correct names : String and 1 with names : String I got from the site. Then I compare those 2 arrays with contentEquals.
If that comparison fails, how do I know which element exactly caused comparison fail?
Short simple of what I have now:
#Test
fun verifyNamesOfAddedItems () {
val getAllElementsNames = arrayOf(materials.text, element2.text,
element3.text...)
val correctElementsNames = arrayOf("name1", "name2", "name3"...)
val areArraysEqual = getAllElementsNames contentEquals correctElementsNames
if (!areArraysEqual) {
assert(false)
} else {
assert(true)
}
}
This test fails if 2 arrays are not the same but it doesn't show me the details, so is there a way to see more details of fail, e.g. element that failed comparison?
Thanks.
I recommend using a matcher library like Hamcrest or AssertJ in tests. They provide much better error messages for cases like this. In this case with Hamcrest it would be:
import org.hamcrest.Matchers.*
assertThat(getAllElementsNames, contains(*correctElementsNames))
// or just
assertThat(getAllElementsNames, contains("name1", "name2", "name3", ...))
There are also matcher libraries made specifically for Kotlin: https://github.com/kotlintest/kotlintest, https://yobriefca.se/expect.kt/, https://github.com/winterbe/expekt, https://github.com/MarkusAmshove/Kluent, probably more. Tests using them should be even more readable, but I haven't tried any of them. Look at their documentation and examples and pick the one you like.
You need to find the intersection between the two collections. Intersection will be the common elements. After than removing the intersection collection from the collection you want to perform the test will give you the complementary elements.
val intersection = getAllElementsNames.intersect(correctElementsNames)
getAllElementsNames.removeAll(intersection)

Retrievieng SharedArray on Julia 0.4

Edit: I did try using fetch()
I seem to have break something in Julia this week. I had played with the SharedArray type on a computer with 12 threads (6 doble thread cpu), I maneged to get a result and to print it and save it as matrix text file without problem, more or less following the instructions on http://docs.julialang.org/en/release-0.4/manual/parallel-computing/#shared-arrays. I had this routine where I initialized a number of workers and an Array, pass them as argument to a function, and expected to obtain a SharedArray with numerical values in return. It went more or less like this
addprocs(11)
BCero=rand(128,128)
ConjuntoX=Array[]
for j,k=1:128
push!(ConjuntoX, [j,k])
end
function obtenerKernelParalell(LasB::Array, lasX::Array, jmax::Int)
result=SharedArray(Float64,(jmax,jmax))
#sync #parallel for j=1:jmax
xj=lasX[j]
for k=1:j
xk=lasX[k]
for l=1:jmax
xl=lasX[l]
result[j,k]+= LasB[(xk-xl+xconstante)...]*LasB[(xj-xl+xconstante)...]
end
end
end
end
KSuaveParalel=obtenerKernelParalell(BceroSuave, ConjuntoX,128);
What I did get after runing this for the first time was an array that behaved itself like a normal Array. If I typed KSuaveParalel[3,12] I obtained a value. But now I get the next thing from the REPL:
KSuaveParalel
11-element Array{Any,1}:
RemoteRef{Channel{Any}}(2,1,122)
RemoteRef{Channel{Any}}(3,1,123)
RemoteRef{Channel{Any}}(4,1,124)
RemoteRef{Channel{Any}}(5,1,125)
RemoteRef{Channel{Any}}(6,1,126)
RemoteRef{Channel{Any}}(7,1,127)
RemoteRef{Channel{Any}}(8,1,128)
RemoteRef{Channel{Any}}(9,1,129)
RemoteRef{Channel{Any}}(10,1,130)
RemoteRef{Channel{Any}}(11,1,131)
RemoteRef{Channel{Any}}(12,1,132)
So I got an array of References... and I do not know how to get its values. Also using fetch() doesn't seem to work.
What is going on here?
Edit:
You need to make sure you return the array in the function.
i.e. return result
You will want to call fetch() on each Remote Reference object to wait and get the value that will be returned.
[fetch(x) for x in KSuaveParalel]
The RemoteRef object is returned immediately (i.e. before the computation has actually been done). See this answer (Julia Parallel macro does not seem to work) and the docs for more info.
http://docs.julialang.org/en/release-0.4/stdlib/parallel/#Base.fetch
Okey, sort of figured a way to do it, but is not probably the most efficient way to do it: If I convert INSIDE the function the result from SharredArray to Array, I get the (apparently) correct result:
function obtenerKernelParalell(LasB::Array, lasX::Array, jmax::Int)
result=SharedArray(Float64,(jmax,jmax))
#sync #parallel for j=1:jmax
xj=lasX[j]
for k=1:j
xk=lasX[k]
for l=1:jmax
xl=lasX[l]
result[j,k]+= LasB[(xk-xl+xconstante)...]*LasB[(xjxl+xconstante)...]
end
end
end
result=Array(result)
return result
end
Is this because the conversion does the fetch() with the right settings automatically?

can't convert Enumerator into Array

While working on one application I am getting this error:
can't convert Enumerator into Array
Here is my code, mr_collection is MongoID query.
mr_collection = self.where(query).map_reduce(map, reduce).finalize(finalize).out({:replace => 'mr_results'})
paginator = WillPaginate::Collection.new(page, limit, collection_count)
collection = mr_collection.find(
:sort => sort,
:limit => limit,
:skip => skip
)
paginator.replace(collection)
While getting mr_collection, if I inspect the result mr_collection gives me:
[
{"_id"=>1.0, "value"=>{"s"=>4.2, "p"=>14.95, "pml"=>0.01993}},
{"_id"=>2.0, "value"=>{"s"=>3.7, "p"=>12.9, "pml"=>0.0172}},
{"_id"=>3.0, "value"=>{"s"=>4.2, "p"=>12.9, "pml"=>0.0172}},
{"_id"=>4.0, "value"=>{"s"=>4.0, "p"=>11.95, "pml"=>0.01593}},
{"_id"=>300.0, "value"=>{"s"=>0.0, "p"=>8.95, "pml"=>0.01193}},
]
While getting collection, if I inspect the result collection gives me:
#<Enumerator: []:find({:sort=>[["value.s", :desc], ["value.pml", :asc]], :limit=>10, :skip=>0})>
I am getting error on the line paginator.replace(collection). I'm using Ruby 1.9.3 & Rails 3.2.6.
collection is an Enumerator which obviously can't convert into an Array, which is what replace expects.
Here are the comments from the rubydocs:
Enumerable#find(ifnone = nil) { |e| ... }
Passes each entry in enum to block. Returns the first for which block
is not false. If no object matches, calls ifnone and returns its
result when it is specified, or returns nil otherwise.
If no block is given, an enumerator is returned instead.
Therefore you have two options:
If you want all elements, yield from the Enumerator to an Array.
If you only want the first match, supply a block that determines what the match is.
Hope this helps.
(Moral of the story: always read the docs!)
I have no idea about mongoid having never used it.
But a search has brought to fore an awfully similar question -
Mongoid 3 - access map_reduce results
Unfortunately my environent is not set to test the magic of
collection = mr_collection.send(:documents).sort(sort).limit(limit).skip(skip).to_a
Have you had a look at this link? Hopefully it'll help solve your issue!

Testing a (big) collection retrieved from a db

I'm currently doing integration testing on a database and I have the following sql statement:
var date = DateTime.Parse("01-01-2010 20:30:00");
var result = datacontext.Repository<IObject>().Where(r => r.DateTime > date).First();
Assert.IsFalse(result.Finished);
I need to test if the results retrieved from the statement, where the given date is less then the date of the object, have Finished set to False. I do not know how many results I get back and currently I'm getting the first object of the list and check if that object has Finished set to false. I know testing only the first item of the list is not valid testing, as a solution for that I could iterate through the list and check all items on Finished, but putting logic in a Test is kinda going against the concept of writing 'good' tests.
So my question is:
Does anyone have a good solution of how to properly test the results of this list?
You can go the other way around, check if you have any result in that date range that is finished.
If there is any, then your test should fail.
I can't test any fancier code, so I'll give you a simple way:
int noOfResultsFinished = datacontext.Repository<IObject>()
.Where(r => r.DateTime > date && r.Finished).Count();
if (noOfResultsFinished > 0)
{
// fail test
}

Resources