Question may sound novice. But here i am everytime i try writing iphone5 in my cucumber feature file it parameterises the 5. I dont want this to happen and want it to just treat iphone5 as a string.
The line in my feature file causing this is:
Then upload iPhone5 image "xxxx.png"
which then gets following step definition:
#And("^then upload iPhone(\\d+) image \"([^\"]*)\"$")
public void then_upload_iPhone_image(int arg1, String arg2) throws Throwable {
// Express the Regexp above with the code you wish you had
throw new PendingException();
}
Just remove regex for the digit and remove the parameter from the method.
#Given("^I upload to iphone5$")
public void I_upload_to_iphone() throws Throwable {
// Express the Regexp above with the code you wish you had
throw new PendingException();
}
in your case
#And("^then upload iPhone5 image \"([^\"]*)\"$")
public void then_upload_iPhone_image(String arg2) throws Throwable {
// Express the Regexp above with the code you wish you had
throw new PendingException();
}
Related
I am performing instrumentation testing, in that I am invoking one of the activities which call 2 APIs when activity is created.
Now I want to write instrumentation test cases for this activity, where I have to mock the API response with mockWebServer of mockito. My mocking code works fine when I call one single API, but it fails when two APIs are getting called simultaneously.
Even there is another scenario let's say, we have API to fetch recent message data, but before that, we always authenticate the user by sending refresh token.
In such cases, we need to call API which authenticates the user and then another API to fetch message data. Hence we need to call 2 APIs one after another, let's say in a single method. How will I mock authentication API response and messages API response while writing test cases of that single method?
How should I deal with this issue? Is there any other approach to deal with such a situation where we need to call more than one API at the same time?
Also, I have used SystemClock.sleep(4000); as my callbacks were getting performed asynchronously.
Below is my code to mock API:
public class MyAPIActivityTest {
#Rule
public InstantTaskExecutorRule mInstantTaskExecutorRule = new InstantTaskExecutorRule();
#Rule
public ActivityTestRule<MyAPIActivity> myAPIActivityTestRule = new ActivityTestRule<>(MyAPIActivity.class, true, false);
MockWebServer mockWebServer;
#Before
public void setUp() {
MockitoAnnotations.initMocks(this);
}
#Test
public void checkVisibilityOfTaskListMockedValidData() throws Exception {
myAPIActivityTestRule.launchActivity(null);
String fileName = "json_files/valid_api_response.json";
mockWebServer = new MockWebServer();
int PORT_NUMBER = 50205;
mockWebServer.start(PORT_NUMBER);
ApiUrls.BASE_QUERY_URL = mockWebServer.url("/").toString();
mockWebServer.enqueue(new MockResponse()
.setBody(getStringFromFile(getContext(), fileName)));
SystemClock.sleep(4000);
Assert.assertEquals(View.VISIBLE, myAPIActivityTestRule.IvDataIsPresent.getVisibility());
Assert.assertEquals(View.GONE, myAPIActivityTestRule.IvDataNotPresent.getVisibility());
}
#After
public void tearDown() throws Exception {
mockWebServer.shutdown();
}
public static String convertStreamToString(InputStream inputStream) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line).append(StringCharacters.NEW_LINE);
}
reader.close();
return stringBuilder.toString();
}
public static String getStringFromFile(Context context, String filePath) throws Exception {
final InputStream stream = context.getResources().getAssets().open(filePath);
String text = convertStreamToString(stream);
stream.close();
return text;
}
}
Any help is appreciated. Thanks in advance.
I want to get the specific error message of ANTLR4's parser.
And I found that there are two way to handle error: errorListener and errorHandler.
// set error handler
parser.removeErrorListeners();
parser.addErrorListener(new QueryErrorListener());
parser.setErrorHandler(new BailErrorStrategy());
But I'm confused about the difference between them.
I found that, errorListener can get the specific error message, but it can only print it or log it, can't throw a exception.
The implemention of errorListener as bellow:
public class QueryErrorListener extends BaseErrorListener {
private static final Logger LOGGER = LoggerFactory.getLogger(QueryDispatcher.class);
#Override
public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol,
int line, int charPositionInLine, String msg,
RecognitionException e)
{
List<String> stack = ((Parser)recognizer).getRuleInvocationStack(); Collections.reverse(stack);
String errorMessage = "line "+line+":"+charPositionInLine+" at "+
offendingSymbol+": "+msg;
LOGGER.error("rule stack: "+stack);
LOGGER.error(errorMessage);
QueryParseErrorStrategy queryParseErrorStrategy = new QueryParseErrorStrategy();
}
}
At the same time, the errorHandler can only throw a exception ParseCancellationException without any specific message.
public class BailErrorStrategy extends DefaultErrorStrategy {
/** Instead of recovering from exception {#code e}, re-throw it wrapped
* in a {#link ParseCancellationException} so it is not caught by the
* rule function catches. Use {#link Exception#getCause()} to get the
* original {#link RecognitionException}.
*/
#Override
public void recover(Parser recognizer, RecognitionException e) {
for (ParserRuleContext context = recognizer.getContext(); context != null; context = context.getParent()) {
context.exception = e;
}
throw new ParseCancellationException(e);
}
/** Make sure we don't attempt to recover inline; if the parser
* successfully recovers, it won't throw an exception.
*/
#Override
public Token recoverInline(Parser recognizer)
throws RecognitionException
{
InputMismatchException e = new InputMismatchException(recognizer);
for (ParserRuleContext context = recognizer.getContext(); context != null; context = context.getParent()) {
context.exception = e;
}
throw new ParseCancellationException(e);
}
/** Make sure we don't attempt to recover from problems in subrules. */
#Override
public void sync(Parser recognizer) { }
}
I've try to find a solution, add a transfer method to get detail message from ParseCancellationException, as bellow.
I found that I can get some message from a Token object of RecognitionException, but I can only find the line/charPositionInLine/offendingSymbol message, I don't know where is the detail message, like "missing 'xxx', expect 'yyy'"
public class ANTLRExceptionTransfer {
public static SemanticException transfer(RecognitionException re) {
String errorMsg = "";
Recognizer<?, ?> recognizer = re.getRecognizer();
Token offendingSymbol = re.getOffendingToken();
int line = offendingSymbol.getLine();
int charPositionInLine = offendingSymbol.getCharPositionInLine();
// ????????
String msg = "";
List<String> stack = ((Parser)recognizer).getRuleInvocationStack();
Collections.reverse(stack);
String errorMessage = "rule stack: "+stack;
errorMessage = "\nline "+line+":"+charPositionInLine+" at "+
offendingSymbol+": "+msg;
return new SemanticException(errorMessage);
}
}
Is it the right way to use errorHandler?
How can I get a exception with specific error message?
I find the setErrorHandler name a bit confusing. It should be consistent with what you can set there. It's for setting an error strategy (which is of course also some kind of handling...).
Both error listener and error strategy are means for the application to deal with parse errors. The error listener gets called for each encountered error and allows the application to collect them (e.g. to show them in a GUI). You'll get a pre-generated error message or can create an own one from the passed in parameters.
The error strategy is a class that determines how to continue after an error was found. The default stategy is to try to sync to the input stream and continue with parsing. Sometimes however you want the parser to stop immediately and avoid lengthy operations after an error was found. This so-called bail-out strategy is another class in ANTLR4, usually used for SLL parsing. See one of my projects for how that's used.
The thrown ParseCancellationException in the bail-out error strategy is an exception without any additional info. It's not meant for error handling (in the sense of sending it to the application/user, you have the error handler for that), but instead to throw an exception that's not one of the usual parser exceptions, in order to bypass all error catching and find a way out of the ongoing parse run as quick as possible. You have to catch this exception in your own code or it will bubble up to the root context of your application (and might cause the application to quit, depending on the target language).
I am working on a JavaFx application, there i have a script that extract a zip followed by some other operation like updating files etc.
I want to have a textArea that displays whats going on in background, like "Zip extracting...", "Updating xyz file" etc.
Till now i have tried following way:
MyTask<String> task;
task = new MyTask<String>() {
#Override
protected String call() throws Exception {
File path = new File(exportTo.getAbsolutePath());
updateMessage("Extracting modular app to target directory...");
patcher.unZip(appPath.getAbsolutePath(), path.getAbsolutePath());
if (path.exists()) {
AppInfo info = getAppInfo();
patcher.patchAndroid(info, resourceZip, new File(path.getAbsolutePath() + "/" + appPath.getName().substring(0, appPath.getName().lastIndexOf("."))), this);
showOkAlert("Build completed!");
} else {
showOkAlert("Modular app folder not found");
}
return "";
}
#Override
protected void updateProgress(double workDone, double max) {
patcher.reportLogs(message);
}
private String message;
#Override
public void updateMessage(final String message) {
Platform.runLater(() -> patcher.reportLogs(message));
this.message = message;
//updateProgress(0, 0);
}
};
task.run();
MyTask class
abstract class MyTask<T> extends Task<T> {
abstract public void updateMessage(String message);
}
I have tried using updateProgress method, Platform.runLater() but nothing is working.
All the message i printed in textArea are printed after all operation is done.
Please help.
As javadoc for Task states you need to manually create a Thread to execute your Task:
Thread th = new Thread(task);
th.start();
Currently your task is being run on Application UI thread and blocks UI updates.
I have a Spring application integrated with ibatis.
I am calling some third party application from where I am getting a String message (a message is combination of messages, there are Strings concatenated with \ delimiter to concatenate the different messages from the third party) as output.
I have to filter this output based on String matching. There are some 150 other Strings. If the output message contains any string out of 150 messages, i have to add some functionality.
I need suggestions to implement it. I am thinking to put 150 Strings in table as the count may increase in future. The Output may contain either no message out of this 150, or any number of combinations with these 150 messages.
I am new to Spring. please tell me how to get these messages from database, since i do not have an id to fetch them or shall I get all of them as list and then compare the output string from the third party. Also please tell me If it wise to keep these messages in database or I can keep them in some property file as well, which one will be better in performance.
Thanks in advance.
Ok, let's start with some possibilities:
IF you will only be adding a few messages in the future and only do so with new releases, then storing the messages in an enum would be a viable choice:
enum ErrorMessage {
SOME_MESSAGE("something, bla bla"),
SOME_OTHER_MESSAGE("something_else"),
...;
private String message;
private ErrorMessage(String message) {
this.message = message;
}
public static ErrorMessage getByErrorMessage(String message) {
for(ErrorMessage errorMessage: message) {
if (errorMessage.message.equals(message)) {
return errorMessage;
}
}
return null;
}
public static boolean exists(String message) {
return getByErrorMessage(message) != null;
}
}
Please note that this version is quite primitive and could be improved by adding all the messages into a static Set:
static Set<String> messagesCache = new Hashset<String>();
//in constructor:
messagesCache.add( message );
// better exists() method:
public static boolean exists(String message) {
return messagesCache.contains(message);
}
Or, as with other solutions, you could only store the actual hashcode of your strings. A hashcode is simple a numeric representation of your string and will be unique enough for you to identify it. Same solution as above:
static Set<String> messagesHashCodes = new Hashset<String>();
//in constructor:
messagesHashCodes .add( message.hashCode() );
// better exists() method:
public static boolean exists(String message) {
return messagesHashCodes .contains(message.hashCode());
}
(Of course, it would be a good idea to check for null values, etc.)
The enum version has one big advantage, if you want to have DIFFERENT actions taken for some of the actions, you can code them into the enum, for example...
SOME_MESSAGE_REQUIRING_AN_ACTION("...") {
#Override
public void doAction(StringBuilder finalString) {
...doSomething.
}
}
...
public void doAction(StringBuilder finalString) {
finalString.append( this.message );
finalString.append( SOME_SEPERATOR );
}
public void static doAction(StringBuilder builder, String errorMessage) {
if (exists(errorMessage)) {
}
}
In this example, you CAN override the doAction method in each enum value, if it should do more/something else than append the message to the StringBuilder. It would also be a nice touch to add some "NULL_MESSAGE" to the enum List that does nothing and is only there to allow easier handling:
UNKNOWN_MESSAGE(null) {
#Override
public void doAction(StringBuilder finalString) {
// do nothing here
}
}
public static ErrorMessage getByErrorMessage(String message) {
for(ErrorMessage errorMessage: message) {
if (errorMessage.message != null && errorMessage.message.equals(message)) {
return errorMessage;
}
}
return UNKNOWN_MESSAGE;
}
This way, you can simple give every single string into your enum method doAction(StringBuilder, String) and get the result: If a message fits, it is added (and some other action taken), if not, it will be ignored, null checks included.
On the other hand, if you messages change quite often, then you might not do a release for such a change but keep the values in a database. In this case, I would use the hashCode() of the message as an id (as I said, unique enough, typically) and load the whole thing into memory when the application starts, allowing you, for example, to build again a Set of hashcodes to compare your errorMessages' hashcodes against.
protected void init() {
// load all error Messages from the database
// put them into a Map<String, String> (hashCode -> Value) or even just a Set<String> (hashcodes)
}
I have created dummy project to figure out how Cucumber for android works and followed the "tutorial" here
https://www.jetbrains.com/idea/help/enabling-cucumber-support-in-project.html
I am using IntelliJ IDEA IDE as you can see and my feature looks like this:
Feature: Testing
Scenario: Testiranje
Given I am on the 'New Pet' page
And I press "Registrer"
Then I should go to the "Registrer" page
Given I am on the new pet page
And Java file:
public class ProradiStepDefs
{
#Given("^I am on the 'New Pet' page$")
public void I_am_on_the_New_Pet_page() throws Throwable
{
}
#And("^I press \\\"([^\\\"]*)\\\"$")
public void I_press(String arg1) throws Throwable
{
System.out.println(arg1);
}
#Then("^I should go to the \\\"([^\\\"]*)\\\" page$")
public void I_should_go_to_the_page(String arg1) throws Throwable
{
System.out.println(arg1);
throw new PendingException();
}
#Given("I am on the new pet page")
public void I_am_on_the_new_pet_page() throws Throwable
{
}
}
And when I start Cucumber java tests I got this in console:
1 Scenarios (1 undefined)
4 Steps (4 undefined)
0m0.000s
You can implement missing steps with the snippets below:
Given("^I am on the 'New Pet' page$", () -> {
// Write code here that turns the phrase above into concrete actions
throw new PendingException();
});
Given("^I press \"([^\"]*)\"$", (String arg1) -> {
// Write code here that turns the phrase above into concrete actions
throw new PendingException();
});
Then("^I should go to the \"([^\"]*)\" page$", (String arg1) -> {
// Write code here that turns the phrase above into concrete actions
throw new PendingException();
});
Given("^I am on the new pet page$", () -> {
// Write code here that turns the phrase above into concrete actions
throw new PendingException();
});
Process finished with exit code 0
Try to run tests with option -r features