Spring Rest Doc junit 5 parameterized Tests support - spring

I read the documentation, but I didn't find anything about whether the parameterized tests functionality of junit 5 is supported. I tried it but unfortunately the result is always overwritten by the next one. Does one of you know if something like the following is possible?
#ParameterizedTest
#ValueSource(strings = { "Hello", "JUnit" })
public void testSnippet(String pseudo) {
this.mockMvc.perform(get("/pseudoCode/{pseudo}", pseudo))
.andExpect(status().isOk())
.andDo(document("locations", pathParameters(
parameterWithName("pseudo").description("It's just pseudo code")
)));
}
I expecting two folders, the first with a sample containing "Hello" as path parameter and the second with "JUnit" as path parameter.
Any suggestions?

You're using the same document identifier for both test executions:
document("locations"
so... the same folder is used for both.

Related

How to quickly write debug output from within a PHP Spec test method

I have inherited some phpspec tests.
The test is testing the value of a method called "getFatalErrors" and reporting failure with:
expected [array:1], but got [array:1].
I would like to see the actual contents of the array.
I have tried to hack the phpspec test class by adding lines like:
<?php
namespace spec;
use MyClass;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
class MyClassSpec extends ObjectBehavior
{
public function it_returns_a_path_problem($args,\XMLFileWrapperTest $testWrapper)
{
echo "foo";
...
var_dump(print_r($this->getFatalErrors()->getWrappedObject(), true));
...
fwrite(STDOUT, "foo");
print_r($this->getFatalErrors()->getWrappedObject(), true)
$this->display("foo");
}
}
--
But I can never get any output to show on my CLI output.
How can I make some arbitrary text appear in my test output so that I 'see' what is going on as I become more familiar with PHPSpec?
Try a different formatter.
When the formatter pretty is selected either in phpspec.yml using the line
formatter.name: pretty
or when executing the test runner with format flag
vendor/bin/phpspec run --format=pretty
then echo output is visible in the terminal.
Have you tried to tail the error log and in your function to add something like
error_log( print_r( $this->getFatalErrors()->getWrappedObject(), 1 ) ); or error_log( print_r( $this->getFatalErrors(), 1 ) ); ?
Usually, it works, as the output is written in your server error log and you can use the terminal or console to tail on that file and see in real time the result.
Just run phpspec with the -v flag, it will be more verbose.
According to the phpspec documentation on Matchers > Inline Matcher, it is possible...
to print a more verbose error message
to do this you can throw
FailureException
So, this implies that it is possible to throw FailureException to output custom messages from within your PHPSpec Example methods.
I tried this and it let me write the phrase "foo message" to my test output:
<?php
namespace spec;
use PhpSpec\ObjectBehavior;
[...]
use PhpSpec\Exception\Example\FailureException;
class MyClassSpec extends ObjectBehavior
{
public function it_tests_something()
{
[...]
throw new FailureException("foo message");
}
}

Spring mvc it, compare payload and header values

We have some intergation tests over #RestController with a common pattern to verify that an Xpath expression exists and that an Http header is set. But I would like to go further and verify that the XPath value is equald or contained into the header.
mvc.perform(..)
.andExpect(xpath("Item/#id/").isIn(header("Location")))
Is it something for that or should I create my own ResultMatcher ?
org.springframework.test.web.servlet.result.MockMvcResultMatchers.xpath(xpathExpress, args) is what you want.
For example:
ResultActions resultActions = mvc.perform(..);
String location = resultActions.andReturn().getResponse().getHeader("Location");
resultActions.andExpect(MockMvcResultMatchers.xpath("Item/#id/", null)
.string(org.hamcrest.Matchers.containsString(location)));
If you need to compare by Node, XMLUnit for Java 2.x offers more usefule Matcher.

Jasmine spyOn with specific arguments

Suppose I have
spyOn($cookieStore,'get').and.returnValue('abc');
This is too general for my use case. Anytime we call
$cookieStore.get('someValue') --> returns 'abc'
$cookieStore.get('anotherValue') --> returns 'abc'
I want to setup a spyOn so I get different returns based on the argument:
$cookieStore.get('someValue') --> returns 'someabc'
$cookieStore.get('anotherValue') --> returns 'anotherabc'
Any suggestions?
You can use callFake:
spyOn($cookieStore,'get').and.callFake(function(arg) {
if (arg === 'someValue'){
return 'someabc';
} else if(arg === 'anotherValue') {
return 'anotherabc';
}
});
To the ones using versions 3 and above of jasmine, you can achieve this by using a syntax similar to sinon stubs:
spyOn(componentInstance, 'myFunction')
.withArgs(myArg1).and.returnValue(myReturnObj1)
.withArgs(myArg2).and.returnValue(myReturnObj2);
details in: https://jasmine.github.io/api/edge/Spy#withArgs
One possible solution is use the expect().toHaveBeenCalledWith() to check the parameters, example:
spyOn($cookieStore,'get').and.returnValue('abc');
$cookieStore.get('someValue') --> returns 'abc';
expect($cookieStore.get).toHaveBeenCalledWith('someValue');
$cookieStore.get('anotherValue') --> returns 'abc'
expect($cookieStore.get).toHaveBeenCalledWith('anotherValue');
Another way of achieving the same result would be.... (Ideal when you are writing unit tests without using a testbed)
declare the spy in root describe block
const storageServiceSpy = jasmine.createSpyObj('StorageService',['getItem']);
and inject this spy in the place of original service in the constructor
service = new StoragePage(storageServiceSpy)
and inside the it() block...
storageServiceSpy.getItem.withArgs('data').and.callFake(() => {})

Jackrabbit XPath Query: UUID with leading number in path

I have what I think is an interesting problem executing queries in Jackrabbit when a node in the query path is a UUID that start with a number.
For example, this query work fine as the second node starts with a letter, 'f':
/*/JCP/feeadeaf-1dae-427f-bf4e-842b07965a93/label//*[#sequence]
This query however does not, if the first 'f' is replaced with '2':
/*/JCP/2eeadeaf-1dae-427f-bf4e-842b07965a93/label//*[#sequence]
The exception:
Encountered "-" at line 1, column 26.
Was expecting one of:
<IntegerLiteral> ...
<DecimalLiteral> ...
<DoubleLiteral> ...
<StringLiteral> ...
... rest omitted for brevity ...
for statement: for $v in /*/JCP/2eeadeaf-1dae-427f-bf4e-842b07965a93/label//*[#sequence] return $v
My code in general
def queryString = queryFor path
def queryManager = session.workspace.queryManager
def query = queryManager.createQuery queryString, Query.XPATH // fails here
query.execute().nodes
I'm aware my query, with the leading asterisk, may not be the best, but I'm just starting out with querying in general. Maybe using another language other than XPATH might work.
I tried the advice in this post, adding a save before creating the query, but no luck
Jackrabbit Running Queries against UUID
Thanks in advance for any input!
A solution that worked was to try and properly escape parts of the query path, namely the individual steps used to build up the path into the repository. The exception message was somewhat misleading, at least to me, as in made me think that the hyphens were part of the root cause. The root problem was that the leading number in the node name created an illegal XPATH query as suggested above.
A solution in this case is to encode the individual steps into the path and build the rest of the query. Resulting in the leading number only being escaped:
/*/JCP/_x0032_eeadeaf-1dae-427f-bf4e-842b07965a93//*[#sequence]
Code that represents a list of steps or a path into the Jackrabbit repository:
import org.apache.commons.lang3.StringUtils;
import org.apache.jackrabbit.util.ISO9075;
class Path {
List<String> steps; //...
public String asQuery() {
return steps.size() > 0 ? "/*" + asPathString(encodedSteps()) + "//*" : "//*";
}
private String asPathString(List<String> steps) {
return '/' + StringUtils.join(steps, '/');
}
private List<String> encodedSteps() {
List<String> encodedSteps = new ArrayList<>();
for (String step : steps) {
encodedSteps.add(ISO9075.encode(step));
}
return encodedSteps;
}
}
Some more notes:
If we escape more of the query string as in:
/_x002a_/JCP/_x0032_eeadeaf-1dae-427f-bf4e-842b07965a93//_x002a_[#sequence]
Or the original path encoded as a whole as in:
_x002f_a_x002f_fffe4dcf0-360c-11e4-ad80-14feb59d0ab5_x002f_2cbae0dc-35e2-11e4-b5d6-14feb59d0ab5_x002f_c
The queries do not produce the wanted results.
Thanks to #matthias_h and #LarsH
An XML element name cannot start with a digit. See the XML spec's rules for STag, Name, and NameStartChar. Therefore, the "XPath expression"
/*/JCP/2eeadeaf-1dae-427f-bf4e-842b07965a93/label//*[#sequence]
is illegal, because the name test 2eead... isn't a legal XML name.
As such, you can't just use any old UUID as an XML element name nor as a name test in XPath. However if you put a legal NameStartChar on the front (such as _), you can probably use any UUID.
I'm not clear on whether you think you already have XML data with an element named <2eead...> (and are trying to query that element's descendants); if so, whatever tool produced it is broken, as it emits illegal XML. On the other hand if the <2eead...> is something that you yourself are creating, then presumably you have the option of modifying the element name to be a legal XML name.

Using OpenNLP (tNER) with Hadoop not returning spans

I am using OpenNLP 1.5.2 with CDH 4 and have an unusual issue.
When I run my jUnit tests, everything passes.
When I run in localJobRunner mode (psuedo or full mode) a lot of the names are not always recognised, and I have 'blank' spans returned, when I was expecting something.
Yes, the names its not finding in local/psuedo/full mode are in my jUnit tests!
Each time I make a call, I pass in a sentence at a time. I tokenise the sentence into a String[] then use these tokens to be found.
an example of what I am calling is:
result = Parser.tokenizedNamedEntityRecognition("PK FRESH IGA PLUS LI PORT KENNEDY WA", nameFinder);
assertEquals("IGA", result);
Where nameFinder is:
InputStream modelIn;
try {
modelIn = new FileInputStream(System.getProperty("user.home") + "pathToModel" + MRConstants.c_namedEntityRecognitionModelFile);
} catch (FileNotFoundException e) {
fail("fail message here");
}
NameFinderME nameFinder = new NameFinderME(new TokenNameFinderModel(modelIn));
in my called method I am doing:
String tokens[] = sentence.split(MRConstants.c_singleSpace);
Span nameSpans[] = nameFinder.find(tokens);
When invoked via my map method, it doesn't always extract the name. I'd say about 20% fail rate.
An example of one of the many trained sentences is:
PK FRESH <START:name> IGA <END> PLUS LI PORT KENNEDY WA
I'm not quite sure why, when I call the same method with the same model, it sometimes works when running in local/psuedo/full mode, but always in jUnit.
Any insights would be appreciated :)
SOLVED: I wasn't clearing adaptive data between documents. Silly mistake on my behalf!

Resources