Arquillian Does Not Execute More Than 4 Tests - jboss-arquillian

This one is a bit of a headscratcher: I have an Arquillian test class with 8 tests. If I execute 4 of them at once, all of them work, but if I add even one other test, the last one fails. If I execute all 8 of them, the last 4 fail. If I change the the order, still the last 4 fail. There is no rhyme nor reason to which ones get executed and which one fails besides that.
(The same holds true if I put half of the tests in another class. Then both classes execute fine on their own, but if they are started as part of the same run configuration, the second one will fail all its tests.)
The error occurs inside the #Before method, so here it is:
#PersistenceContext
private EntityManager em;
#Inject
private UserTransaction transaction;
#Before
public void setUp() throws Exception {
Assert.assertNotNull("EntityManager cannot be null!", this.em);
this.transaction.begin();
this.em.createNativeQuery(MY_SCRIPT_1).executeUpdate();
this.em.createNativeQuery(MY_SCRIPT_2).executeUpdate();
this.transaction.commit();
}
Where MY_SCRIPT_X is a bunch of code, but the relevant portion might be:
-- MY_SCRIPT_1
DROP SCHEMA IF EXISTS scheme1 CASCADE;
DROP SCHEMA IF EXISTS scheme2 CASCADE;
DROP SCHEMA IF EXISTS public CASCADE;
CREATE SCHEMA public;
-- MY_SCRIPT_2
CREATE TABLE scheme1.dbconfig (
propkey character varying NOT NULL,
propvalue character varying NOT NULL,
CONSTRAINT dbconfig_pkey PRIMARY KEY (propkey)
);
COMMENT ON TABLE scheme1.dbconfig IS 'global database configuration properties';
INSERT INTO scheme1.dbconfig VALUES
('initialized', true),
('version', 2);
The error does not occur if I use only one big script [em.createNativeQuery(MY_SCRIPT_1 + MY_SCRIPT_2)], even though the table scheme1.dbconfig is only referenced in one of the files.
All I get as an error message is:
09:20:18,243 ERROR [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] (default task-24) ERROR: relation "scheme1.dbconfig" does not exist
Position: 169
I have no idea where position 169 is (ignoring all comments, the 169th position should be between the R and the O of propkey, which seems odd). But I checked the database after executing the entire class and getting the above error, and the table scheme1.dbconfig does indeed exist.
I know, it's an oddly specific problem, but does anybody what the problem might be (or even how to debug it further)?
Some more infos:
database: PostgreSQL
Hibernate: 4.3.5
container: Wildfly 8.1.0.Final
And all it needs for my to reproduce the bug is (the beans.xml is an default empty file, and the persistence.xml has only the jta-data-source):
#RunWith(Arquillian.class)
public class BugTest {
private static final String CLEANUP_SCRIPT = "DROP SCHEMA IF EXISTS scheme1 CASCADE; "
+ "DROP SCHEMA IF EXISTS public CASCADE; "
+ "CREATE SCHEMA public AUTHORIZATION testdba;";
private static final String CREATE_SCRIPT = "CREATE SCHEMA scheme1; "
+ "CREATE TABLE scheme1.dbconfig ( propkey character varying NOT NULL, propvalue character varying NOT NULL, CONSTRAINT dbconfig_pkey PRIMARY KEY (propkey) ); "
+ "INSERT INTO scheme1.dbconfig VALUES ('initialized', true), ('version', 2);";
#Deployment
public static Archive<?> createDeployment() {
return ShrinkWrap.create(JavaArchive.class).addAsManifestResource("META-INF/beans.xml", "beans.xml")
.addAsManifestResource("META-INF/persistence.xml", "persistence.xml");
}
#PersistenceContext
private EntityManager em;
#Inject
private UserTransaction transaction;
#Before
public void setUp() throws Exception {
this.transaction.begin();
this.em.createNativeQuery(CLEANUP_SCRIPT).executeUpdate();
this.em.createNativeQuery(CREATE_SCRIPT).executeUpdate();
this.transaction.commit();
}
// since an exception gets thrown in the setUp() method, these are not called
// they are only needed because the exception gets thrown for more than
// four tests methods
#Test public void test1() { }
#Test public void test2() { }
#Test public void test3() { }
#Test public void test4() { }
#Test public void test5() { }
#Test public void test6() { }
#Test public void test7() { }
#Test public void test8() { }
}

I ran over that problem again and again and again in the previous two years. The only thing that reliable works are the following:
using one script instead of two; in this case, I'll concatenate the two files before executing
not initializing every time; I'll test if one of the schemata is present and hope and pray that the previous tests left the database in an usable condition (good luck debugging using this one)

No, Arquillian will run as many tests as you need in a single file, or at least until JUnit (or TestNG) stop running. Here are some examples from Apache DeltaSpike with more than four tests running:
https://github.com/apache/deltaspike/blob/master/deltaspike/core/impl/src/test/java/org/apache/deltaspike/test/core/impl/exception/control/handler/CallingHandlersTest.java
https://github.com/apache/deltaspike/blob/master/deltaspike/modules/data/impl/src/test/java/org/apache/deltaspike/data/impl/handler/EntityRepositoryHandlerTest.java
https://github.com/apache/deltaspike/blob/master/deltaspike/core/impl/src/test/java/org/apache/deltaspike/test/core/api/message/MessageContextTest.java
You must have something in your setup that is causing the problem.

Related

testNG priorities not followed

In the testNG.xml file, I have 10+ test classes (within a test-suite tag) for regression testing. I, then, have ordered the automated tests of several test classes in a particular sequence by using the priority=xxx in #Test annotation. The priority values within a particular class are sequential - but each test class has different ranges. For example:
testClass1 : values are from 1-10
testClass2 : values are from 11-23
testClass3 : values are from 31-38
.
.
.
lastTestClass : values are from 10201-10215
The purpose of this is to have a particular sequence in which the 10+ test-classes are executed. There is one test-class that I need to be executed towards the end of the test execution - so, the priorities in that class range from 10201-10215. However, this particular test-class gets tested right after the 1st class with priorities from 1-10.
Instead of using priority, I would recommend you to use dependencies. They will run your tests in a strict order, never running the depended before the dependent, even if you are running in parallel.
I understand you have the different ranges in different classes, so in dependOnMethods you would have to specify the root of the test you are referencing:
#Test( description = "Values are from 1-10")
public void values_1_10() {
someTest();
}
#Test( description = "Values are from 21-23",
dependsOnMethods = { "com.project.test.RangeToTen.values_1_10" })
public void values_21_23() {
someTest();
}
If you have more than one test in each range then you can use dependsOnGroups:
#Test( enabled = true,
description = "Values are from 1-10")
public void values_1_10_A() {
someTest();
}
#Test( enabled = true,
description = "Values are from 1-10")
public void values_1_10_B() {
someTest();
}
#Test( enabled = true,
description = "Values are from 1-10",
dependsOnGroups = { "group_1_10" })
public void values_21_23_A() {
someTest();
}
#Test( enabled = true,
description = "Values are from 1-10",
dependsOnGroups = { "group_1_10" })
public void values_21_23_B() {
someTest();
}
You can also do the same with more options from the testng.xml:
https://testng.org/doc/documentation-main.html#dependencies-in-xml
Another option you have is to use the "preserve order":
https://www.seleniumeasy.com/testng-tutorials/preserve-order-in-testng
But as Anton mention, that could bring you troubles if you ever want to run in parallel, so I recommend you using dependencies.
Designing your tests to be run in specific order is a bad practice. You might want to run tests in parallel in future - and having dependencies on order will stop you from doing that.
Consider using TestNG listeners instead:
It looks like you are trying to implement some kind of tearDown process after tests.
If this is the case - you can implement ITestListener and use onFinish method to run some code after all of your tests were executed.
Also, this TestNG annotation might work for your case:
org.testng.annotations.AfterSuite

How to persist/read-back Run Configuration parameters in Intellij plugin

I'm making a basic IntelliJ plugin that lets a user define Run Configuration (following the tutorial at [1]), and use said Run Configurations to execute the file open in the editor on a remote server.
My Run Configuration is simple (3 text fields), and I have it all working, however, after editing the Run Configuration, and click "Apply" or "OK" after changing values, the entered values are lost.
What is the correct way to persist and read-back values (both when the Run Configuration is re-opened as well as when the Run Configuration's Runner invoked)? It looks like I could try to create a custom persistence using [2], however, it seems like the Plugin framework should have a way to handle this already or at least hooks for when Apply/OK is pressed.
[1] https://www.jetbrains.org/intellij/sdk/docs/tutorials/run_configurations.html
[2] https://www.jetbrains.org/intellij/sdk/docs/basics/persisting_state_of_components.html
Hopefully, this post is a bit more clear to those new to IntelliJ plugin development and illustrates how persisting/loading Run Configurations can be achieved. Please read through the code comments as this is where much of the explanation takes place.
Also now that SettingsEditorImpl is my custom implementation of the SettingsEditor abstract class, and likewise, RunConfigurationImpl is my custom implementation of the RunConfigiration abstract class.
The first thing to do is to expose the form fields via custom getters on your SettingsEditorImpl (ie. getHost())
public class SettingsEditorImpl extends SettingsEditor<RunConfigurationImpl> {
private JPanel configurationPanel; // This is the outer-most JPanel
private JTextField hostJTextField;
public SettingsEditorImpl() {
super();
}
#NotNull
#Override
protected JComponent createEditor() {
return configurationPanel;
}
/* Gets the Form fields value */
private String getHost() {
return hostJTextField.getText();
}
/* Copy value FROM your custom runConfiguration back INTO the Form UI; This is to load previously saved values into the Form when it's opened. */
#Override
protected void resetEditorFrom(RunConfigurationImpl runConfiguration) {
hostJTextField.setText(StringUtils.defaultIfBlank(runConfiguration.getHost(), RUN_CONFIGURATION_HOST_DEFAULT));
}
/* Sync the value from the Form UI INTO the RunConfiguration which is what the rest of your code will interact with. This requires a way to set this value on your custom RunConfiguration, ie. RunConfigurationImpl##setHost(host) */
#Override
protected void applyEditorTo(RunConfigurationImpl runConfiguration) throws ConfigurationException {
runConfiguration.setHost(getHost());
}
}
So now, the custom SettingsEditor, which backs the Form UI, is set up to Sync field values In and Out of itself. Remember, the custom RunConfiguration is what is going to actually represent this configuration; the SettingsEditor implementation just represents the FORM (a subtle difference, but important).
Now we need a custom RunConfiguration ...
/* Annotate the class with #State and #Storage, which is used to define how this RunConfiguration's data will be persisted/loaded. */
#State(
name = Constants.PLUGIN_NAME,
storages = {#Storage(Constants.PLUGIN_NAME + "__run-configuration.xml")}
)
public class RunConfigurationImpl extends RunConfigurationBase {
// Its good to 'namespace' keys to your component;
public static final String KEY_HOST = Constants.PLUGIN_NAME + ".host";
private String host;
public RunConfigurationImpl(Project project, ConfigurationFactory factory, String name) {
super(project, factory, name);
}
/* Return an instances of the custom SettingsEditor ... see class defined above */
#NotNull
#Override
public SettingsEditor<? extends RunConfiguration> getConfigurationEditor() {
return new SettingsEditorImpl();
}
/* Return null, else we'll get a Startup/Connection tab in our Run Configuration UI in IntelliJ */
#Nullable
#Override
public SettingsEditor<ConfigurationPerRunnerSettings> getRunnerSettingsEditor(ProgramRunner runner) {
return null;
}
/* This is a pretty cool method. Every time SettingsEditor#applyEditorTo() is changed the values in this class, this method is run and can check/validate any fields! If RuntimeConfigurationException is thrown, the exceptions message is shown at the bottom of the Run Configuration UI in IntelliJ! */
#Override
public void checkConfiguration() throws RuntimeConfigurationException {
if (!StringUtils.startsWithAny(getHost(), "http://", "https://")) {
throw new RuntimeConfigurationException("Invalid host");
}
}
#Nullable
#Override
public RunProfileState getState(#NotNull Executor executor, #NotNull ExecutionEnvironment executionEnvironment) throws ExecutionException {
return null;
}
/* This READS any prior persisted configuration from the State/Storage defined by this classes annotations ... see above.
You must manually read and populate the fields using JDOMExternalizerUtil.readField(..).
This method is invoked at the "right time" by the plugin framework. You dont need to call this.
*/
#Override
public void readExternal(Element element) throws InvalidDataException {
super.readExternal(element);
host = JDOMExternalizerUtil.readField(element, KEY_HOST);
}
/* This WRITES/persists configurations TO the State/Storage defined by this classes annotations ... see above.
You must manually read and populate the fields using JDOMExternalizerUtil.writeField(..).
This method is invoked at the "right time" by the plugin framework. You dont need to call this.
*/
#Override
public void writeExternal(Element element) throws WriteExternalException {
super.writeExternal(element);
JDOMExternalizerUtil.writeField(element, KEY_HOST, host);
}
/* This method is what's used by the rest of the plugin code to access the configured 'host' value. The host field (variable) is written by
1. when writeExternal(..) loads a value from a persisted config.
2. when SettingsEditor#applyEditorTo(..) is called when the Form itself changes.
*/
public String getHost() {
return host;
}
/* This method sets the value, and is primarily used by the custom SettingEditor's SettingsEditor#applyEditorTo(..) method call */
public void setHost(String host) {
this.host = host;
}
}
To read these configuration values elsewhere, say for example a custom ProgramRunner, you would do something like:
final RunConfigurationImpl runConfiguration = (RunConfigurationImpl) executionEnvironment.getRunnerAndConfigurationSettings().getConfiguration();
runConfiguration.getHost(); // Returns the configured host value
See com.intellij.execution.configurations.RunConfigurationBase#readExternal as well as com.intellij.execution.configurations.RunConfigurationBase#loadState and com.intellij.execution.configurations.RunConfigurationBase#writeExternal

arquillian warp timing out instead of executing AfterPhase (or AfterServlet, BeforePhase or BeforeServlet for that matter)

I am just getting started with Arquillian Warp and seems to have hit a stumbling block.
I have a basic UI Test for a registration page
#WarpTest
#RunWith(Arquillian.class)
public class TestProfileEdit extends AbstractUsersTest {
#Drone
FirefoxDriver browser;
#Page
EditProfilePage editProfilePage;
#Page
LoginPage loginPage;
#ArquillianResource
private URL baseURL;
#Deployment
public static Archive<?> createLoginDeployment() throws IOException {
// trimmed for brevity
}
#Before
public void setup() throws MalformedURLException{
final URL loginURL = new URL(baseURL, "login.jsf");
browser.navigate().to(loginURL);
loginPage.login("test#domain.com", "password");
final URL pageURL = new URL(baseURL, "profile/edit.jsf");
System.out.println(pageURL.toExternalForm());
browser.navigate().to(pageURL);
}
#After
public void tearDown() {
browser.manage().deleteAllCookies();
}
#Test
#RunAsClient
public void testSaveData() {
editProfilePage.getDialog().setFirstName("Test First Name");
Warp.execute(new ClientAction() {
#Override
public void action() {
editProfilePage.getDialog().save();
}
}).verify(new TestProfileOnServer());
}
#SuppressWarnings("serial")
public static class TestProfileOnServer extends ServerAssertion {
#Inject
private EntityManager em;
#Inject
private Identity identity;
#Inject
Credentials credentials;
#AfterPhase(Phase.RENDER_RESPONSE)
public void testSavedUserProfile() {
System.out.println("RUNNING TEST");
String username = identity.getUser().getId();
TypedQuery<UserProfile> q = em.createQuery(
"SELECT u from UserProfile u where u.userIdentity.name like :username", UserProfile.class);
UserProfile p;
p = q.setParameter("username", username).getSingleResult();
assertEquals("Test First Name", p.getFirstName());
}
}
}
I have tried the various combinations on testSavedUserProfile() method with absolutely no luck in getting that to trigger.
The test always ends with
java.lang.IllegalStateException: java.util.concurrent.ExecutionException: org.jboss.arquillian.warp.client.execution.AssertionHolder$ServerResponseTimeoutException
I can see the page getting posted and redirected correctly on the firefox window that gets opened up. I tried to get it to not redirect etc. and nothing has helped.
I feel like I am missing something basic and simple but no idea what!
Any help much appreciated.
Thanks.
I've recently encountered a similar problem with Arquillian Warp.
One of the reasons my code didn't get called was that Arquillian merges the server-sde servlet filter into a web archive (WAR) deplyoment only. Neither EAR nor JAR deployments work off the shelf.
For my concrete problem (EAR deployment) I modified the test classes in a way that I merge in the Arquillian filter myself when assembling the tested WAR which in turn is packed into an EAR deployment.
The other problem I ran across was that the AfterServlet event is simply not fired within the unit test execution scope but as part of the servlet filter cleanup code. I believe this logic is totally broken and I build a private fork of the servlet filter which IMHO is handling the logic correctly.

A central location for catching throwables of JUnit tests?

I would like to catch any throwable during a Selenium test e.g. in order to make a screenshot. The only solution I could come up with for now is to separately surround the test steps with a try and catch block in every test method as following:
#Test
public void testYouTubeVideo() throws Throwable {
try {
// My test steps go here
} catch (Throwable t) {
captureScreenshots();
throw t;
}
}
I'm sure there is a better solution for this. I would like a higher, more centralized location for this try-catch-makeScreenshot routine, so that my test would be able to include just the test steps again. Any ideas would be greatly appreciated.
You need to declare a TestRule, probably a TestWatcher or if you want to define the rules more explicitly, ExternalResource. This would look something like:
public class WatchmanTest {
#Rule
public TestRule watchman= new TestWatcher() {
#Override
protected void failed(Description d) {
// take screenshot here
}
};
#Test
public void fails() {
fail();
}
#Test
public void succeeds() {
}
}
The TestWatcher anonymous class can of course be factored out, and just referenced from the test classes.
I solved a similar problem using Spring's AOP. In summary:
Declare the selenium object as a bean
Add an aspect using
#AfterThrowing
The aspect can take the screenshot and save it to a
file with a semirandom generated name.
The aspect also rethrows the exception, with the exception message including the filename so you can look at it afterwards.
I found it more helpful to save the HTML of the page due to flakiness of grabbing screenshots.

Asynchronous callback - gwt

I am using gwt and postgres for my project. On the front end i have few widgets whose data i am trying to save on to tables at the back-end when i click on "save project" button(this also takes the name for the created project).
In the asynchronous callback part i am setting more than one table. But it is not sending the data properly. I am getting the following error:
org.postgresql.util.PSQLException: ERROR: insert or update on table "entitytype" violates foreign key constraint "entitytype_pname_fkey"
Detail: Key (pname)=(Project Name) is not present in table "project".
But when i do the select statement on project table i can see that the project name is present.
Here is how the callback part looks like:
oksave.addClickHandler(new ClickHandler(){
#Override
public void onClick(ClickEvent event) {
if(erasync == null)
erasync = GWT.create(EntityRelationService.class);
AsyncCallback<Void> callback = new AsyncCallback<Void>(){
#Override
public void onFailure(Throwable caught) {
}
#Override
public void onSuccess(Void result){ }
};
erasync.setProjects(projectname, callback);
for(int i = 0; i < boundaryPanel.getWidgetCount(); i++){
top = new Integer(boundaryPanel.getWidget(i).getAbsoluteTop()).toString();
left = new Integer(boundaryPanel.getWidget(i).getAbsoluteLeft()).toString();
if(widgetTitle.startsWith("ATTR")){
type = "regular";
erasync.setEntityAttribute(name1, name, type, top, left, projectname, callback);
} else{
erasync.setEntityType(name, top, left, projectname, callback);
}
}
}
Question:
Is it wrong to set more than one in the asynchronous callback where all the other tables are dependent on a particular table?
when i say setProjects in the above code isn't it first completed and then moved on to the next one?
Please any input will be greatly appreciated.
Thank you.
With that foreign key constraint, you must make sure the erasync.setProjects(...) has completed before you insert the rest of the stuff.
I suggest doing the erasync.setEntityAttribute(...) magic in (or from) an onsuccess callback instead of jumping right to it.
You're firing several request in which (guessing from the error message) really should be called in sequence.
Any time you call more than one rpc call; try to think that you should be able to rearrange them in any order (because that's allmost what actually happens because they're asynchronous)... If running them in reverse order does not make sense; you cannot fire them sequentially!
Two ways to fix your problem:
Nesting:
service.callFirst(someData, new AsyncCallback<Void> callback = new AsyncCallback<Void>(){
#Override
public void onFailure(Throwable caught) {/*Handle errors*/}
#Override
public void onSuccess(Void result){
service.callSecond(someOtherData, new AsyncCallback<Void> callback = new AsyncCallback<Void>(){
/* onSuccess and onFailure for second callback here */
});
}
});
Or creating one service call that does both (Recommended):
service.callFirstAndSecond(someData, someOtherData, new AsyncCallback<Void> callback = new AsyncCallback<Void>(){
#Override
public void onFailure(Throwable caught) {/*Handle errors*/}
#Override
public void onSuccess(Void result){
/* Handle success */
}
});
The second option is most likely going to be much less messy, as several nested asynch callbacks quickly grows quite wide and confusing, also you make just one request.
Because of nature of Async, don't assume setProjects(...) method will be called on the server before setEntityAttribute or setEntityType.
Personally, I prefer to have a Project class which contains all necessary info, for example:
public class Project{
private String projectName;
private List attributes = new ArrayList();
.. other properties
// Getter & Setter methods
}
Then send to the server in one round trip:
Project project = new Project();
project.setProjectName(..);
// Set other properties
erasync.saveProjects(project, callback);