UninstallWMISchemaExecute (0x8004401e) when updating VisualSVN on Windows XP

The problem

On the attempt to update VisualSVN on my Windows XP I struggled with the following exception quite a long time:

Custom action UninstallWMISchemaExecute failed: Diese Datei ist keine gültige MOF-Datei. (0x8004401e)
Screenshot of UninstallWMISchemaExecute-Exception (0x8004401e) when updating VisualSVN on Windows XP

UninstallWMISchemaExecute when updating VisualSVN

I was never faced with WMI before so I started from scratch and choosed to try’n’error. A great help was the artikel found in [1] and after a while I succeeded—but: I still have no clue why my solution worked, nor could I assure that it is side-effect-free. So use on your own risk!

The solution

  1. Disable the WMI service
    sc config winmgmt start= disabled 
    (make sure there is a blank between 'start' and 'disabled')
  2. Stop the WMI service
    net stop winmgmt
  3. Go to %windir%/System32/wbem and rename the repository-folder
    cd C:\WINDOWS\System32\wbem
    rename Repository Repository-old
  4. Find the *.mof-file in %windir%/System32/wbem which belongs to VisualSVN
    In my case the file was named “6E9A2709F6EB23A5E2F059ACD767AD78.mof”. Inside there were multiple occurences of the string “VisualSVN”—which I found by using Notepad++’s search-in-files-funktionality [2]. Note that the Windows search won’t lead to any useable results since Windows doesn’t do a text-search on *.mof-files by default.
  5. Remove the file found in step 4
  6. Search the registry on occurences of “VisualSVN” and remove every found item
    I guess especially the key “Autorecover MOFs” in

    HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\WBEM\CIMOM

    was an entry which recreated the faulty *.mof all over again.

  7. Enabled the WMI service
    sc config winmgmt start= auto
  8. Start the VisualSVN-Installation

Reference

  1. [1] http://blog.technical-life.at/2011/09/nice-to-know-wmi-steuerung-reparieren
  2. [2] http://npp-community.tuxfamily.org/documentation/notepad-user-manual/searching/searching-files

Selenium 2 / WebDriver—is element present ?

When switching from Selenium 1 to Selenium 2/WebDriver you will notice bitterly that there is no isElementPresent()-method anymore.

Solutions found on the Internet

To fix that issue, one of the most shown solutions on the Internet is the usage of driver#findElement(By) and a try-/catch-statement:

public boolean isElementPresent(String id) {
	boolean present;
	try {
		driver.findElement(By.id(id));
		present = true;
	} catch (NoSuchElementException e) {
		present = false;
	}
	return present;
}

Not very elegant. In addition the JavaDoc of WebElement#findElementy(By) states explicitly, that this method shouldn’t be used “to look for non-present elements”. Instead WebElement#findElements(By) should be used:

public boolean isElementPresent(String id) {
	return driver.findElements(By.id(id)).size() != 0;
}

Although this solution avoids the need of the try/catch-statement, it still lacks in the timeout/implicit waiting functionality Selenium 2 ships with. Every time this method is called, the WebDriver tries to find the element until the given timeout is reached. Therefore our test would wait a certain period of time (to be precise the value set by implicitlyWait) whenever this method is about to return ‘false’.

To get ahead of that, you can explicitly set the timeout:

public boolean isElementPresent(String id, WebDriver driver) {
	boolean present;
	
	driver.manage().timeouts().implicitlyWait(0, TimeUnit.SECONDS);
	boolean present = driver.findElements( By.id(id) ).size() != 0;
	driver.manage().timeouts().implicitlyWait(1000, TimeUnit.SECONDS);
	
	return present;
}

Problem when using the Page-Object-Pattern

The big dissapointment: when using the Page-Object-Pattern in conjunction with the @FindBy-Annotation you are constrained to implement the WebElement’s id at least twice:

@FindBy(id="fooId")
private WebElement webelement;

public void testSome() {
	...
	isElementPresent("fooId", driver);
	...
}

So if “fooId” changes its value, you have to fix that in your code on multiple positions. That should be avoided.

A (half-way clean) solution

I tried to overcome that problem by passing the WebElement directly to my isElementPresent-Method. As a result, I’m able to hold the id on one single position in my code. As a drawback (or advantage) I’m unable to use the id in my isElementPresent-Method anymore. This is caused by the absence of a suitable way in the WebElement’s API to get the by-value (eg. By.id(“foo”)) which is used to find the element. Therefore using WebDriver#findElements(By) gone out of reach.

Finally I step back to the solution I preliminary declared as “not very elegant”: I use a try-/catch-statement in which I call a method on the webelement which throws an NoSuchElementException in case the element is not present:

public static boolean isElementPresent(WebDriver webdriver, WebElement webelement) {	
	boolean exists = false;

	webdriver.manage().timeouts().implicitlyWait(0, TimeUnit.MILLISECONDS);

	try {
		webelement.getTagName();
		exists = true;
	} catch (NoSuchElementException e) {
		// nothing to do.
	}

	webdriver.manage().timeouts().implicitlyWait(1000, TimeUnit.MILLISECONDS);

	return exists;
}

Note:

  • If I have to deliberate about whether avoiding the try/catch-statement or avoiding to code the ids mulitple times, I actually prefer the last one.
  • If your value for implicitly wait differs from 1000, calling this method will obviously overwrite the current value.

A quick refactoring using TestNG’s expectedExceptions

I recently crossed a TestNG-test which looked like this:

@Test
public void noResultsTest() {
	// test
	String query = " ";
	Exception exception = null;
	List foos = null;
	try {
		foos = barService.search(query);
	} catch (SystemError e) {
		// input was wrong
		exception = e;
	}

	// assert
	Assert.assertNotNull(exception, "There was an exception");
	Assert.assertNull(foos);
}

Obviously this test should check that barService#search throws an Exception in case the input is a blank.

But there are a few things to mention:

  • TestNG is capable of checking if an expected exception was thrown in a test. Simply use @Test(expectedExceptions={..}).
  • The check that Assert.assertNull(foos) holds true is useless. Either no exception was thrown and Assert.assertNotNull(exception, "There was an exception") will fail or an exception was thrown and foos will not be assigned with any value.

So the test could be rewritten like this:

@Test(expectedExceptions={ SystemError.class })
public void keineBerufeTest2() throws SystemError {
	foos = barService.search(" ");
}

Fail instead of Skip a Test when TestNG’s DataProvider throws an Exception

A quite tricky problem I have been faced with was a failing TestNG-DataProvider which threw an exception because of corrupt test data. The critical point was that neither the Maven Surefire Plugin nor the Eclipe-TestNG-Plugin failed dependent tests. These tests were only skipped. That’s problematic because when the test data gets corrupt (e.g. due to an update) I actually want to be informed explicitly—this information shouldn’t just be swallowed. But the only indicator for a failure was the amount of skipped test which Surefire prints after each run. A position which could be missed easily in a large console output.

The problem

So I constructed a minimal working example with a DataProvider that just throws a NullPointerException and a test that does nothing but depending on the broken DataProvider. Then I took the sources of TestNG and turned on my debugger. I finally got to the class org.testng.internal.Invoker: there’s a method invokeTestMethods(..) in which I found the following code:

if (bag.hasErrors()) {
    failureCount = handleInvocationResults(testMethod, bag.errorResults, null, failureCount, expectedExceptionHolder, true, true /* collect results */);
    ITestResult tr = registerSkippedTestResult(testMethod, instances[0], start, bag.errorResults.get(0).getThrowable());
    result.add(tr);
    continue;
}

Now consider the bag-instance has errors (and the internal hold errorResult-instance also says explicitly that the status is “failure”). The method call registerSkippedTestResult(..) changes that to a skip! Obviously I located the reason for my problem—although the intention of this code is still not clear to me…

Solution 1: “Selftest”-Method in DataProvider

The (easiest and somehow most naive) solution is to provide a self test which invokes the DataProvider directly. The tests which depend on the DataProvider will still be skipped but the additional self test bypasses the TestNG-mechanism and throws an exception directly. Hence TestNG fails the test run as it should be.

@Test
public void selftest() {
    TestDataProvider.createTestcases();
}

The benefit of this solution is its simplicity and its robustness: no future releases of TestNG can break this approach (except a change which ignores exceptions occurring in test methods, but I can’t hardly believe that will ever happen). The drawback is that you have to modify your code because of an issue in TestNG (I really don’t like being forced to make changes in my code because of problems in third party libraries). Furthermore there are additional runtime costs to consider—the DataProvider is called at least once more than actually needed. Depending on the DataProviders logic a more or less critical fact.

Solution 2: Return an empty array

Cédric Beust (the developer behind TestNG) gave in [1] a solution how to handle this issue. The trick is to surround the failable code in the DataProvider with a try..catch and return an empty array in the catch-clause:

@DataProvider(name="testcases")
public static Object[][] testcases() {
    try {
        return createTestcases(); // throws an exception
    } catch (Throwable e) {
        return new Object[][] {{}};
    }
}

The solution adopted to Iterators:

@DataProvider(name="testcases")
public static Iterator testcases() {
    try {
        return createTestcases(); // throws an exception
    } catch (Throwable e) {
        return Arrays.asList(new Object[][] {{}}).iterator();
    }
}

The big pro of this approach is its lightweight. There isn’t much code to write and the solution is somehow easy to adopt for other DataProvider. Again the drawback is that you have to modify your code because of an issue in TestNG. Furthermore without any documentation every developer would wonder about the strange looking statement inside the catch-clause, as well as about the widely disfavored coding style “catching a Throwable”. Finally the answer why this solution works is something I guess only Céderic Beust understands. By the way: using an empty list doesn’t interestingly do the job for me…

@DataProvider(name="testcases") 
public static Iterator testcases() {
    try {
        return createTestcases(); // throws an exception
    } catch (Throwable e) {
        return Collections.emptyList().iterator(); // DOESN'T WORK !!!
    }
}

Solution 3: Exception-Iterator

Another approach is limited to DataProviders which returns an Iterator. Therefore you create an “ExceptionIterator” which simply throws an Exception when using it:

public class ExceptionIterator implements Iterator {
    private Throwable e;

    public ExceptionIterator(Throwable e) {
        this.e = e;
    }

    @Override
    public boolean hasNext() {
        throw new RuntimeException(e);
    }

    @Override
    public Object[] next() {
        throw new RuntimeException(e);			
    }

    @Override
        public void remove() {
        throw new RuntimeException(e);
    }
}

In case of a failure while retrieving the test data, the ExceptionIterator is being used:

@DataProvider(name="testcases")
public static Iterator testcases() {
    try {
        return createTestcases(); // throws an exception
    } catch (Throwable e) {
        return new ExceptionIterator(e);
    }
}

The pros and cons of this solution are mainly equal to solution “Return an empty array” as the approaches are very similar. One benefit is that it is more stable against changes/updates of TestNG. If in some future release the reason whyever solution 2 works gets broken, this solution will still going to perform well. A disadvantage is the approach itself: an Iterator which only throws Exceptions isn’t a piece of code one could be proud of.

Solution 4: FailListener

TestNG gives the ability to register listeners to your test execution [2]. So you can code a “FailListener” which switches every skipped test to a failed one:

public class FailListener extends TestListenerAdapter {
    @Override
    public void onTestSkipped(ITestResult tr) {
        tr.setStatus(ITestResult.FAILURE);
    }
}

The listener can be attached to the test class like this (for some other ways, see [2]):

@Listeners({FailListener.class})
public class TestNGTest { .. }

One of the big benefits is the loose coupling: test code and workaround-code are separated in two independent classes. This also supports DRY (“Don’t repeat yourself”) since no try…catches-blocks (like in the other solutions) are needed. But on the other hand setting the ITestResult to fail like this must be named a dirty hack. What if in a future release the given TestResult is a clone of the original one? Changes on that instance wouldn’t be recognized by TestNG and the whole solution could be dropped. Furthermore all skipped tests are marked as fail even if they are supposed to be skipped. So you ban the usage of skip indirectly in your test environment. That’s especially problematic because although the listener is attached to a class it is called for all tests in the same test suite!

Conclusion

In this post I discussed 4 different approaches to solve a TestNG-issue related to exceptions occurring in DataProviders. Depending tests are skipped instead of being marked as fail. All approaches have their pros and cons so that the given circumstances will determine which solution helps the best. For me solution 2, “Return an empty array” did the job.

Reference

  1. [1] http://markmail.org/message/54dr2wnte6kdfnqv#query:+page:1+mid:wbzu3xs2icdr7sqp+state:results
  2. [2] http://testng.org/doc/documentation-main.html#testng-listeners