Assertion Error While Testing the Pipeline Apache Beam - unit-testing

While testing the pipeline I got this error even the error log shows that the objects are equal:
public void testGenerateUserPageViews() throws Exception{
final PCollection<SessionModel> input = p.apply(Create.of(SESSION_MODEL));
final PCollection<UserPageViews> output = input.apply(ParDo.of(new GenerateUserPageViews()));
PAssert.that(output).containsInAnyOrder(USER_PAGEVIEWS);
p.run().waitUntilFinish();
}
java.lang.AssertionError: ParDo(GenerateUserPageViews)/ParMultiDo(GenerateUserPageViews).output:
Expected: iterable over [<com.userprofile.models.UserPageViews#e1688b19>] in any order
but: Not matched: <com.userprofile.models.UserPageViews#e1688b19>
at org.apache.beam.sdk.testing.PAssert$PAssertionSite.capture(PAssert.java:174)
at org.apache.beam.sdk.testing.PAssert.that(PAssert.java:416)
at org.apache.beam.sdk.testing.PAssert.that(PAssert.java:408)
at

I would guess that com.userprofile.models.UserPageViews does not have a fully implemented equals or hashCode method.

The solution is that I replace String variable with "" value in place of null. But I still don't understand why the object reference are the same in both cases.

Related

Cast OWL-S condition to SWRL

I want to cast some OWL-S conditions to SWRL, the cast is done but the result manipulation returns nullpointerexception. Here the code :
final OWLIndividualList<Condition> cs = service.getProfile().getConditions();
final ArrayList<ArrayList<URI>> conditions = new ArrayList<ArrayList<URI>>();
for (final Condition<?> c : cs){
if (c.canCastTo(Condition.SWRL.class)){ // is it a SWRL condition?
final Condition.SWRL sc = c.castTo(Condition.SWRL.class);
for (final Atom a : sc.getBody()){...........
the last line returns :
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
Can anyone help me to deal with this?
This issue is not linked to the java code but to the OWLS-S file syntaxe.
you can resolve this issue by replacing:
<expr:expressionBody rdf:parseType="Literal">
which hold the SWRL precondition (or eventually the result), by:
<expr:expressionObject>

No value at JSON path

How to write mockMVC test for the below JSON which has combination of String and Array.
{
"id":1,
"firstName":"NPA",
"lastName":"TAS",
"mobile":"123454321",
"email":"ABCD#GMAIL.COM",
"accounts":[
{
"id":1,
"balance":"$1000",
"custid":"1",
"accNbr":"12345"
}
]
}
My code:
#Test
public void testJson() throws Exception {
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
mockMvc.perform(get("/acc/1")
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(jsonPath("$.accounts.id", Matchers.is(1)))
.andExpect(jsonPath("$.accounts.balance", Matchers.is("$1000")))
.andExpect(jsonPath("$.accounts.accNbr", Matchers.is("12345")))
.andExpect(jsonPath("$.accounts.custid", Matchers.is("1")))
.andExpect(jsonPath("$.*", Matchers.hasSize(4)));
}
i get the exception
No value at JSON path "$.accounts.id", exception:
Expected to find an object with property ['accounts'] in path $ but found 'net.minidev.json.JSONArray'. This is not a json object according to the JsonProvider: 'com.jayway.jsonpath.spi.json.JsonSmartJsonProvider'.
However, if i try using $.accounts[0].id i get exception
No value at JSON path "$.accounts[0].id", exception:
Expected to find an object with property ['accounts'] in path $ but found 'net.minidev.json.JSONArray'. This is not a json object according to the JsonProvider: 'com.jayway.jsonpath.spi.json.JsonSmartJsonProvider'.
The accounts attribute is an array so this: $.accounts.id would have to use an indexer such as: $.accounts[0].id.
From the docs:
[<number> (, <number>)] Array index or indexes
If you are uncertain about which index to use then you can filter the JSON and assert on the filtered account sub document. For example:
$.accounts[?(#.id == 1)].balance: returns $1000
$.accounts[?(#.accNbr == 12345)].id: returns 1
... etc
Plenty more details in the docs and you can use the use the JsonPath evaluator to play around with this.
As #glytching and I have mentioned, there is an array and it should work with $.accounts[0].id.
If you still encounter a problem, I would try to print the result your console:
MvcResult result = mockMvc.perform(MockMvcRequestBuilders
.get("/acc/1").accept(MediaType.APPLICATION_JSON)).andReturn();
String content = result.getResponse().getContentAsString();

rest-assured expected doesn't match

I try
#Test
public void testGetSingleUser() {
given().expect().
statusCode(200).contentType(ContentType.JSON).
body("_testingString", equalTo("got it")).when().
get("http://localhost:8080/getIt");
}
But always got this error message
java.lang.AssertionError : JSON path _testingString dosen't match.
Expected : "got it" got : [got it]
how to ignore "" and [] problem
Thanks
Note: This is untested code snippet but while looking at your error trace it may help you.
try
equalTo(Arrays.asList("got it"))
instead of
equalTo("got it")
When you receive a error saying, same like that:
JSON path total doesn't match.
Expected: 2000
Actual: <[2000]>
It means that your result(Actual:) is coming inside an array.
Hence, you should use a rest-assured-command(for example, hasItem) that verifies values 'inside an array'.
My code below illustrate a solution for this situation:
RestAssuredWebTestClient
.given()
.webTestClient(mockedWebClient)
.queryParam("cost", 1000)
.when()
.get(TEMPL_AGGREG_DATE)
.then()
.log()
.everything()
.statusCode(OK.value())
.body("_id", hasItem(project2.getStartDate()))
.body("total", hasItem((int)project2.getEstimatedCost()))
.body(matchesJsonSchemaInClasspath("contracts/aggregations/CostsGroupByStartDate.json"))
;

Mocked class not accepting instance of Carbon

I am trying to test a method with PhpUnit and Mockery. In the process of specifying a method should be called with arguments my test fails.
TEST:
$this->eventRepo = \Mockery::mock('Path\To\EventRepository');
$start = Carbon::createFromFormat('Ymd-H-i-s', '20141211-09-21-00');
$end = Carbon::createFromFormat('Ymd-H-i-s', '20141211-09-19-00');
$this->eventRepo
->shouldReceive('findEvent')
->withArgs([
$start,
$end,
'1',
'1234567891'
])
->andReturn($callEvent);
REAL CODE:
$start = Carbon::createFromFormat('Ymd-H-i-s', '20141211-09-20-00');
$end = Carbon::createFromFormat('Ymd-H-i-s', '20141211-09-20-00');
$event = $this->eventRepo->findEvent(
$start->subSeconds(60),
$end->addSeconds(60),
$id,
$number
);
ERROR FROM TEST:
Mockery\Exception\NoMatchingExpectationException: No matching handler found for EventRepo::findEvent(object(Carbon\Carbon), object(Carbon\Carbon), "1", "1234567891"). Either the method was unexpected or its arguments matched no expected argument list for this method
$this->eventRepo is a mocked in the test. The real code runs correctly. After the error displays, it, I guess var_dump()'s a instance of Carbon.
I have no idea what could be causing this. I tried googling it but not knowing what to google made that pretty worthless. Has anyone run into this before?
When using an object in with() or withArgs(), phpunit performs an === check. This means that it'll look for the exact same instance of the class, not just any instance of Carbon.
In this case, it means that findEvent() is receiving an instance of Carbon, but not the exact same instance that you have in the actual code.

Testing NullOject in Grails Application

Using grails 2.2.1 and having an issue with a service method which takes a NullObject as opposed to null.
The unit test is failing with the following exception;
| java.lang.NullPointerException: Cannot get property 'class' on null object
at grails.test.GrailsMock$_createMock_closure1_closure2.doCall(GrailsMock.groovy:105)
at grails.test.GrailsMock$_createMock_closure1.doCall(GrailsMock.groovy:103)
The cacheService Unit test is as follows;
#Test
public void shouldCacheForCacheTypeJbossNullableObject() {
grailsApplication.config.domain.cache = "jbosscache"
cacheService.jbossCacheService = jbossMock.createMock()
cacheService.cacheWithNullable( at, ct, key, null )
jbossMock.verify()
}
The cacheService looks like this;
#Override
void cacheWithNullable(Token token, String type, String key, Object value)
{
if(!value)
{
jbossCacheService.cache(token, type, key, new NullObject())
}
}
Please note: some of the logic has been removed for clarity.
The jbossCacheService test case has 100% test coverage and operates as expected to ensure that nulls are not applied to cache. However, the cacheService test fails with NPE and I cant get this method test so that I can mock the return service or apply demands.
Any help is appreciated.
Looks like the NullObject is a class-less class! So in the GrailsMock.class the following line of code is failing at line 105 will fail
if (it != null) {
if (it.class instanceof Class) {
Which will mean the NullOject will pass the null check but fail on the instanceof. So the unit test will never pass with this logic. Might open an JIRA with Grails for a better explanation.