assertj how to check in a list that a property is greather than a value - assertj

Given:
class Point {
int x;
int y;
}
List<Point> points;
How can I check that property x in a list of Points is greather than a value? I aim something similar to:
assertThat(points).extracting("x").isGreatherThan(20)
However I can't find 'isGreatherThan' after 'extracting'
Update
I don't aim writing custom conditions for this kind of value checking, as assertj already has methods for checking numbers.
Thanks

You can use filteredOn as it supports java 8 Predicate, e.g:
assertThat(listOfPoints).filteredOn(p -> p.x > 20).isNotEmpty();
If you want to do more complex stuff, using Condition is the way to go, in AssertJ 3.x they are simpler to write, rewriting Florian Schaetz example:
Condition<Integer> greaterThan20 = new Condition<>(v -> v.intValue() > 20, "greater than 20");

You can try this one...
.extracting( "x", Integer.class ).areAtLeast( 1, greaterThan20 );
Of course you'll have to write the condition yourself, something like...
final Condition<Integer> greaterThan20 = new Condition<Integer>("greater than 20") {
#Override
public boolean matches(Integer value) {
return value.intValue() > 20;
}
};

In Java 8 you can do something like this:
assertThat(listOfPoints.stream().filter(p->p.x > 20).toArray()).hasSameSizeAs(listOfPoints);
That's for the case where you want ALL points to have x > 20.
To verify that there's at least one (as in Florian Schaetz's answer):
assertThat(listOfPoints.stream().filter(p->p.x > 20).toArray()).isNotEmpty();

Related

ranges::views::generate have generator function signal end of range

I'd like to have a generator that terminates, like python, but I can't tell from ranges::views::generate's interface if this is supported.
You can roll it by hand easily enough:
https://godbolt.org/z/xcGz6657r although it's probably better to use a coroutine generator if you have one available.
You can return an optional in the generator, and stop taking elements when a std::nullopt is generated with views::take_while
auto out = ranges::views::generate(
[i = 0]() mutable -> std::optional<int>
{
if (i > 3)
return std::nullopt;
return { i++ };
})
| ranges::views::take_while([](auto opt){ return opt.has_value();})
;

How to combine the elements of an arbitrary number of dependent Fluxes?

In the non reactive world the following code snippet is nothing special:
interface Enhancer {
Result enhance(Result result);
}
Result result = Result.empty();
result = fooEnhancer.enhance(result);
result = barEnhancer.enhance(result);
result = bazEnhancer.enhance(result);
There are three different Enhancer implementations taking a Result instance, enhancing it and returning the enhanced result. Let's assume the order of the enhancer calls matters.
Now what if these methods are replaced by reactive variants returning a Flux<Result>? Because the methods depend on the result(s) of the preceding method, we cannot use combineLatest here.
A possible solution could be:
Flux.just(Result.empty())
.switchMap(result -> first(result)
.switchMap(result -> second(result)
.switchMap(result -> third(result))))
.subscribe(result -> doSomethingWith(result));
Note that the switchMap calls are nested. As we are only interested in the final result, we let switchMap switch to the next flux as soon as new events are emitted in preceding fluxes.
Now let's try to do it with a dynamic number of fluxes. Non reactive (without fluxes), this would again be nothing special:
List<Enhancer> enhancers = <ordered list of different Enhancer impls>;
Result result = Result.empty();
for (Enhancer enhancer : enhancers) {
result = enhancer.enhance(result);
}
But how can I generalize the above reactive example with three fluxes to deal with an arbitrary number of fluxes?
I found a solution using recursion:
#FunctionalInterface
interface FluxProvider {
Flux<Result> get(Result result);
}
// recursive method creating the final Flux
private Flux<Result> cascadingSwitchMap(Result input, List<FluxProvider> fluxProviders, int idx) {
if (idx < fluxProviders.size()) {
return fluxProviders.get(idx).get(input).switchMap(result -> cascadingSwitchMap(result, fluxProviders, idx + 1));
}
return Flux.just(input);
}
// code using the recursive method
List<FluxProvider> fluxProviders = new ArrayList<>();
fluxProviders.add(fooEnhancer::enhance);
fluxProviders.add(barEnhancer::enhance);
fluxProviders.add(bazEnhancer::enhance);
cascadingSwitchMap(Result.empty(), fluxProviders, 0)
.subscribe(result -> doSomethingWith(result));
But maybe there is a more elegant solution using an operator/feature of project-reactor. Does anybody know such a feature? In fact, the requirement doesn't seem to be such an unusual one, is it?
switchMap feels inappropriate here. If you have a List<Enhancer> by the time the Flux pipeline is declared, why not apply a logic close to what you had in imperative style:
List<Enhancer> enhancers = <ordered list of different Enhancer impls>;
Mono<Result> resultMono = Mono.just(Result.empty)
for (Enhancer enhancer : enhancers) {
resultMono = resultMono.map(enhancer::enhance); //previousValue -> enhancer.enhance(previousValue)
}
return resultMono;
That can even be performed later at subscription time for even more dynamic resolution of the enhancers by wrapping the whole code above in a Mono.defer(() -> {...}) block.

Groovy/Scala - Abort Early while iterating using an accumulator

I have a fairly large collection that I would like to iterate and find out if the collection contains more than one instance of a particular number. Since the collection is large, i'd like to exit early, i.e not traverse the complete list.
I have a dirty looking piece of code that does this in a non-functional programming way. However, i'm unable to find a functional programming way of doing this (In Groovy or Scala), since I need to do 2 things at the same time.
Accumulate state
Exit Early
The "accumulate state" can be done using the "inject" or "fold" methods in Groovy/Scala but there's no way of exiting early from those methods. Original groovy code is below. Any thoughts?
def collection = [1,2,3,2,4,6,0,65,... 1 million more numbers]
def n = 2
boolean foundMoreThanOnce(List<Integer> collection, Integer n) {
def foundCount = 0
for(Integer i : collection) {
if(i == n) {
foundCount = foundCount + 1
}
if(foundCount > 1) {
return true
}
}
return false
}
print foundMoreThanOnce(collection, n)
One of many possible Scala solutions.
def foundMoreThanOnce[A](collection: Seq[A], target: A): Boolean =
collection.dropWhile(_ != target).indexOf(target,1) > 0
Or a slight variation...
collection.dropWhile(target.!=).drop(1).contains(target)
Scans the collection only until the 2nd target element is found.
Not sure about groovy, but if possible for you to use Java 8 then there is a possibility
collection.stream().filter(z -> {return z ==2;} ).limit(2)
the limit will stop the stream processing as soon as it get 2nd occurrence of 2.
You can use it as below, to ensure there are exact two occurrences
Long occ = collection.stream().filter(z -> {return z ==2;} ).limit(2).count();
if(occ == 2)
return true;

junit.framework.ComparisonFailure: value but value is equal

junit.framework.ComparisonFailure:
value (table=XXX, row=XXX, col=XXX)
expected:<2013-01-18 18:17:13.233099>
but was:<2013-01-18 18:17:13.233099>
at org.dbunit.assertion.JUnitFailureFactory.createFailure(JUnitFailureFactory.java:39)...
my code:
...
IDataSet actualDataSet = conn.createDataSet();
XmlDataSet expectedDataSet = new XmlDataSet(getClass().getResourceAsStream("/data.xml"));
Assertion.assertEquals(expectedDataSet, actualDataSet);
...
conn - connection to database PostgreSql 7.1
What is wrong?
Hard to say without more information, but it looks like there may be a problem with the class that represents the value in "table=XXX, row=XXX, col=XXX". What datatype is that? Some "Date"-like class? Does it correctly implement equals()?
A common problem with JUnit et al. is to use assertEquals on types where equals() does not compare by value - then comparison always yields false. This looks like one of those cases.
org.dbunit.dataset.datatype.TimestampDataType.typeCast()
cast to Timestamp and then other class compare objects. I don't undestend why it's doesn't work.
To avoid this problem I excluded column:
String[] actualTablenames = actualDataSet.getTableNames();
for (int i = 0; i < actualTableNames.length; i++) {
ITable expectedTable = expectedDataSet.getTable(actualTableNames[i]);
...
ITable filteredActualTable = DefaultColumnFilter.excludedColumnsTable(actualTable, new String[]{"changetime"});

How to query using GremlinPipeline and PipeFunctions in Java?

In a graph model I have a vertex called timeCategory with childs year-vertices, month-vertices and day-vertices. I am able to identify a year with the edge-label with IS_YEAR, a month with IS_MONTH, etc.
I want to do a query that returns all vertices of a given year range similarly to the following code:
GremlinPipeline yearPipe = new GremlinPipeline(timeCategory).out("IS_YEAR").property("year")
.filter(new PipeFunction<Integer, Boolean>() {
public Boolean compute(Integer i)
{
return i < 2013 && i >= 2011;
}
});
for(Object v : yearPipe) {
//v is an Integer, but i need the vertex
System.out.println(v);
}
... this works great for printing all property-values (the years as integers), but what I need is a list of all VERTICES which year-properties are between a given range.
My second question is about making a intersection from values in pipes.
For example: I have three pipes, a yearpipe, a monthpipe, and daypipe, and the pipes containg vertices that identifies a year, month, or day.
Is it possible to get all outgoing vertices to one special date...
Semi-Code: allVertices2012-01-01 = yearpipe.out() AND monthpipe.out() AND daypipe.out
sure, i can do some compares in some for-each-loops, but i wanted to know if there is a (simple) gremlin - way to do it better.
There are two solutions to your problem. Here it is in Gremlin-Groovy:
timeCategory.out('IS_YEAR').filter{year = it.getProperty('year'); year < 2013 && year >= 2011}
-OR-
timeCategory.out('IS_YEAR').property('year').filter{it < 2013 && it >= 2011}.back(1)
Here is your answer in Gremlin-Java code (for the second representation above):
GremlinPipeline yearPipe = new GremlinPipeline(timeCategory).out("IS_YEAR").property("year")
.filter(new PipeFunction<Integer, Boolean>() {
public Boolean compute(Integer i)
{
if(i<2013 && i>=2011)
return true;
else
return false;
}
}).back(1);
Okay after some short-tutorials reading, I figuered out that the param on .back(x) should be 2... so, with .back(2) you will get your vertices.
btw. the examples provided at http://markorodriguez.com are much better for a gremlin quick start then these on github-wiki, in my opinion.
To my second question: I found out there is a topic on gremling-users, that describes pretty well my problem:
http://groups.google.com/group/gremlin-users/browse_thread/thread/d245b1a25ac1fac8/514931b1e3bf9e30?lnk=gst&q=intersect#514931b1e3bf9e30