Showing posts with label Google Testing. Show all posts
Showing posts with label Google Testing. Show all posts

Thursday, January 8, 2009

Google Testing Blog: Interfacing with hard-to-test third-party code

by Miško Hevery

Shahar asks an excellent question about how to deal with frameworks which we use in our projects, but which were not written with testability in mind.
Hi Misko, First I would like to thank you for the "Guide to Writing Testable Code", which really helped me to think about better ways to organize my code and architecture. Trying to apply the guide to the code I'm working on, I came up with some difficulties. Our code is based on external frameworks and libraries. Being dependent on external frameworks makes it harder to write tests, since test setup is much more complex. It's not just a single class we're using, but rather a whole bunch of classes, base classes, definitions and configuration files. Can you provide some tips about using external libraries or frameworks, in a manner that will allow easy testing of the code?

-- Thanks, Shahar

There are two different kind of situations you can get yourself into:


  1. Either your code calls a third-party library (such as you calling into LDAP authentication, or JDBC driver)

  2. Or a third party library calls you and forces you to implement an interface or extend a base class (such as when using servlets).


Unless these APIs are written with testability in mind, they will hamper your ability to write tests.

Calling Third-Party Libraries

I always try to separate myself from third party library with a Facade and an Adapter. Facade is an interface which has a simplified view of the third-party API. Let me give you an example. Have a look at javax.naming.ldap. It is a collection of several interfaces and classes, with a complex way in which you have to call them. If your code depends on this interface you will drown in mocking hell. Now I don't know why the API is so complex, but I do know that my application only needs a fraction of these calls. I also know that many of these calls are configuration specific and outside of bootstrapping code these APIs are cluttering what I have to mock out.

I start from the other end. I ask myself this question. 'What would an ideal API look like for my application?' The key here is 'my application' An application which only needs to authenticate will have a very different 'ideal API' than an application which needs to manage the LDAP. Because we are focusing on our application the resulting API is significantly simplified. It is very possible that for most applications the ideal interface may be something along these lines.
interface Authenticator {
boolean authenticate(String username,
String password);
}

As you can see this interface is a lot simpler to mock and work with than the original one as a result it is a lot more testable. In essence the ideal interfaces are what separates the testable world from the legacy world.

Once we have an ideal interface all we have to do is implement the adapter which bridges our ideal interface with the actual one. This adapter may be a pain to test, but at least the pain is in a single location.

The benefit of this is that:

  • We can easily implement an InMemoryAuthenticator for running our application in the QA environment.

  • If the third-party APIs change than those changes only affect our adapter code.

  • If we now have to authenticate against a Kerberos or Windows registry the implementation is straight forward.

  • We are less likely to introduce a usage bug since calling the ideal API is simpler than calling the original API.


Plugging into an Existing Framework

Let's take servlets as an example of hard to test framework. Why are servlets hard to test?

  • Servlets require a no argument constructor which prevents us from using dependency injection. See how to think about the new operator.

  • Servlets pass around HttpServletRequest and HttpServletResponse which are very hard to instantiate or mock.


At a high level I use the same strategy of separating myself from the servlet APIs. I implement my actions in a separate class
class LoginPage {
Authenticator authenticator;
boolean success;
String errorMessage;
LoginPage(Authenticator authenticator) {
this.authenticator = authenticator;
}

String execute(Map<String, String> parameters,
String cookie) {
// do some work
success = ...;
errorMessage = ...;
}

String render(Writer writer) {
if (success)
return "redirect URL";
else
writer.write(...);
}
}

The code above is easy to test because:

  • It does not inherit from any base class.

  • Dependency injection allows us to inject mock authenticator (Unlike the no argument constructor in servlets).

  • The work phase is separated from the rendering phase. It is really hard to assert anything useful on the Writer but we can assert on the state of the LoginPage, such as success and errorMessage.

  • The input parameters to the LoginPage are very easy to instantiate. (Map<String, String>, String for cookie, or a StringWriter for the writer).


What we have achieved is that all of our application logic is in the LoginPage and all of the untestable mess is in the LoginServlet which acts like an adapter. We can than test the LoginPage in depth. The LoginSevlet is not so simple, and in most cases I just don't bother testing it since there can only be wiring bug in that code. There should be no application logic in the LoginServlet since we have moved all of the application logic to LoginPage.

Let's look at the adapter class:
class LoginServlet extends HttpServlet {
Provider<LoginPage> loginPageProvider;

// no arg constructor required by
// Servlet Framework
LoginServlet() {
this(Global.injector
.getProvider(LoginPage.class));
}

// Dependency injected constructor used for testing
LoginServlet(Provider<LoginPage> loginPageProvider) {
this.loginPageProvider = loginPageProvider;
}

service(HttpServletRequest req,
HttpServletResponse resp) {
LoginPage page = loginPageProvider.get();
page.execute(req.getParameterMap(),
req.getCookies());
String redirect = page.render(resp.getWriter())
if (redirect != null)
resp.sendRedirect(redirect);
}
}

Notice the use of two constructors. One fully dependency injected and the other no argument. If I write a test I will use the dependency injected constructor which will than allow me to mock out all of my dependencies.

Also notice that the no argument constructor is forcing me to use global state, which is very bad, but in the case of servlets I have no choice. However, I make sure that only servlets access the global state and the rest of my application is unaware of this global variable and uses proper dependency injection techniques.

BTW there are many frameworks out there which sit on top of servlets and which provide you a very testable APIs. They all achieve this by separating you from the servlet implementation and from HttpServletRequest and HttpServletResponse. For example Waffle and WebWork
[NFGB] Link - from Google Testing Blog
Related From Google Blogs:
Static Methods are Death to Testability
GTAC Videos and Slides Available
TotT: Mockers of the (C++) World, Delight!
Announcing Google C++ Mocking Framework

Saturday, December 20, 2008

Static Methods are Death to Testability

by Miško Hevery

Recently many of you, after reading Guide to Testability, wrote to telling me there is nothing wrong with static methods. After all what can be easier to test than Math.abs()! And Math.abs() is static method! If abs() was on instance method, one would have to instantiate the object first, and that may prove to be a problem. (See how to think about the new operator, and class does real work)

The basic issue with static methods is they are procedural code. I have no idea how to unit-test procedural code. Unit-testing assumes that I can instantiate a piece of my application in isolation. During the instantiation I wire the dependencies with mocks/friendlies which replace the real dependencies. With procedural programing there is nothing to "wire" since there are no objects, the code and data are separate.

Here is another way of thinking about it. Unit-testing needs seams, seams is where we prevent the execution of normal code path and is how we achieve isolation of the class under test. seams work through polymorphism, we override/implement class/interface and than wire the class under test differently in order to take control of the execution flow. With static methods there is nothing to override. Yes, static methods are easy to call, but if the static method calls another static method there is no way to overrider the called method dependency.

Lets do a mental exercise. Suppose your application has nothing but static methods. (Yes, code like that is possible to write, it is called procedural programming.) Now imagine the call graph of that application. If you try to execute a leaf method, you will have no issue setting up its state, and asserting all of the corner cases. The reason is that a leaf method makes no further calls. As you move further away from the leaves and closer to the root main() method it will be harder and harder to set up the state in your test and harder to assert things. Many things will become impossible to assert. Your tests will get progressively larger. Once you reach the main() method you no longer have a unit-test (as your unit is the whole application) you now have a scenario test. Imagine that the application you are trying to test is a word processor. There is not much you can assert from the main method.

We have already covered that global state is bad and how it makes your application hard to understand. If your application has no global state than all of the input for your static method must come from its arguments. Chances are very good that you can move the method as an instance method to one of the method's arguments. (As in method(a,b) becomes a.method(b).) Once you move it you realized that that is where the method should have been to begin with. The use of static methods becomes even worse problem when the static methods start accessing the global state of the application. What about methods which take no arguments? Well, either methodX() returns a constant in which case there is nothing to test; it accesses global state, which is bad; or it is a factory.

Sometimes a static methods is a factory for other objects. This further exuberates the testing problem. In tests we rely on the fact that we can wire objects differently replacing important dependencies with mocks. Once a new operator is called we can not override the method with a sub-class. A caller of such a static factory is permanently bound to the concrete classes which the static factory method produced. In other words the damage of the static method is far beyond the static method itself. Butting object graph wiring and construction code into static method is extra bad, since object graph wiring is how we isolate things for testing.

"So leaf methods are ok to be static but other methods should not be?" I like to go a step further and simply say, static methods are not OK. The issue is that a methods starts off being a leaf and over time more and more code is added to them and they lose their positions as a leafs. It is way to easy to turn a leaf method into none-leaf method, the other way around is not so easy. Therefore a static leaf method is a slippery slope which is waiting to grow and become a problem. Static methods are procedural! In OO language stick to OO. And as far as Math.abs(-5) goes, I think Java got it wrong. I really want to write -5.abs(). Ruby got that one right.
[NFGB] Link - from Google Testing Blog
Related From Google Blogs:
Really new in Labs this time: SMS Text Messaging for chat
Net neutrality and the benefits of caching
Eric Schmidt talks technology and the economy on "Meet the Press"
Creating change with your homepage

Sunday, December 14, 2008

GTAC Videos and Slides Available

Posted by Lydia Ash, GTAC Conference Chair

The Google Test Automation Conference 2008 was a smashing success, and in no small part due to all of our presenters and participants. A wonderful thank you from all of us at Google to everyone that participated! The tone of the conference really struck me as I watched how everyone came together around various topics. I don't think we would have had trouble keeping the conversations going if there was an entire day dedicated to the moderated discussions.

We were able to get the slide decks from our presenters. These are listed below with their video link.
We will be evaluating what location the next GTAC should be held, and your comments will help shape the next conference. Building on the successes in the past, next year should be even better! Stay tuned for a Save the Date notice sometime in the spring.

Opening Remarks - Lydia Ash
Video: http://www.youtube.com/watch?v=l5QmHXcNk4g

The Future of Testing - James A. Whittaker
Video coming soon...

Advances in Automated Software Testing Technologies - Elfriede Dustin and Marcus Borch
Video: http://www.youtube.com/watch?v=HEpSdSyU03I

Boosting Your Testing Productivity with Groovy - Andres Almiray
Video: http://www.youtube.com/watch?v=UvWTfVCWKJY
Slides: http://www.slideshare.net/aalmiray/gtac-boosting-your-testing-productivity-with-groovy/

Taming the Beast: How to Test an AJAX Application - Markus Clermont and John Thomas
Video: http://www.youtube.com/watch?v=5jjrTBFZWgk
Slides: http://docs.google.com/Presentation?id=dczwht9g_62gccsc9gg

The New Genomics: Software Development at Petabyte Scale - Matt Wood
Video: http://www.youtube.com/watch?v=A64WKH9gNI8
Slides part 1: http://docs.google.com/Presentation?id=dczwht9g_3318qqfb6f5
Slides part 2: http://docs.google.com/Presentation?id=dczwht9g_393d7zg4xcm

Using Cloud Computing to Automate Full-Scale System Tests - Marc-Elian Bégin and Charles Loomis
Video: http://www.youtube.com/watch?v=atyq-41Gnjc
Slides: http://docs.google.com/Presentation?id=dczwht9g_251gcv8cbfv

Practicing Testability in the Real World - Vishal Chowdhary
Video: http://www.youtube.com/watch?v=hL829wNaF78
Slides: http://docs.google.com/Presentation?id=dczwht9g_0hgd2w5rz

Context-Driven Test Automation: How to Build the System you Really Need - Pete Schneider
Video: http://www.youtube.com/watch?v=N9sm_zcpUEw
Slides: http://docs.google.com/Presentation?id=dczwht9g_236ccxj32fd

Automated Model-Based Testing of Web Applications - Atif M. Memon and Oluwaseun Akinmade
Video: http://www.youtube.com/watch?v=6LdsIVvxISU
Slides: http://www.cs.umd.edu/~atif/GTAC08/

The Value of Small Tests - Christopher Semturs
Video: http://www.youtube.com/watch?v=MpG2i_6nkUg
Slides: http://docs.google.com/Presentation?id=dckk962d_332cxtcsmhg

JInjector: A Coverage and End-To-End Testing Framework for J2ME and RIM - Julian Harty, Olivier Gaillard, and Michele Sama
Video: http://www.youtube.com/watch?v=B2v5jQ9NLVg
Slides: http://docs.google.com/Presentation?id=dczwht9g_82d7w8bqd9

Atom Publishing Protocol: Testing your Server Implementation - David Calavera
Video: http://www.youtube.com/watch?v=uRmWTfT91uQ
Slides: http://thinkincode.net/gtac_atomPub_testing_your_server_implementation.pdf

Simple Tools to Fight the Bigger Quality Battle: Continuous Integration Using Batch Files
and Task Scheduler - Komal Joshi and Patrick Martin
Video: http://www.youtube.com/watch?v=wgP7ejMBCCU
Slides: http://docs.google.com/Presentation?id=dczwht9g_141czcvc7md

[NFGB] Link - from Google Testing Blog
Related From Google Blogs:
Fast PDF viewing right in your browser
Google Chrome (BETA)
YouTube Google Desktop Gadget
Your blog, your data

Friday, December 12, 2008

Mockers of the (C++) World, Delight!

by Zhanyong Wan, Software Engineer

Life is unfair. You work every bit as hard as Joe the Java programmer next to you. Yet as a C++ programmer, you don't get to play with all the fancy programming tools Joe takes for granted.

In particular, without a good mocking framework, mock objects in C++ have to be rolled by hand. Boy, is that tedious! (Not to mention how error-prone it is.) Why should you endure this?

Dread no more. Google Mock is finally here to help! It's a Google-originated open-source framework for creating and using C++ mocks. Inspired by jMock and EasyMock, Google Mock is easy to use, yet flexible and extensible. All you need to get started is the ability to count from 0 to 10 and use an editor.

Think you can do it? Let's try this simple example: you have a ShoppingCart class that gets the tax rate from a server, and you want to test that it remembers to disconnect from the server even when the server has generated an error. It's easy to write the test using a mock tax server, which implements this interface:

class TaxServer {
// Returns the tax rate of a location
// (by postal code) or -1 on error.
virtual double FetchTaxRate(
const string& postal_code) = 0;
virtual void CloseConnection() = 0;
};


ShoppingCart:


class MockTaxServer : public TaxServer { // #1
MOCK_METHOD1(FetchTaxRate, double(const string&));
MOCK_METHOD0(CloseConnection, void());
};

TEST(ShoppingCartTest,
StillCallsCloseIfServerErrorOccurs) {
MockTaxServer mock_taxserver; // #2
EXPECT_CALL(mock_taxserver, FetchTaxRate(_))
.WillOnce(Return(-1)); // #3
EXPECT_CALL(mock_taxserver, CloseConnection());
ShoppingCart cart(&mock_taxserver); // #4
cart.CalculateTax(); // Calls FetchTaxRate()
// and CloseConnection().
} // #5


  • Derive the mock class from the interface. For each virtual method, count how many arguments it has, name the result n, and define it using MOCK_METHODn, whose arguments are the name and type of the method.
  • Create an instance of the mock class. It will be used where you would normally use a real object.
  • Set expectations on the mock object (How will it be used? What will it do?). For example, the first EXPECT_CALL says that FetchTaxRate() will be called and will return an error. The underscore (_) is a matcher that says the argument can be anything. Google Mock has many matchers you can use to precisely specify what the argument should be like. You can also define your own matcher or use an exact value.
  • Exercise code that uses the mock object. You'll get an error immediately if a mock method is called more times than expected or with the wrong arguments.

  • When the mock object is destroyed, it checks that all expectations on it have been satisfied.

  • You can also use Google Mock for rapid prototyping – and get a better design. To find out more, visit the project homepage at http://code.google.com/p/googlemock/. Now, be the first one on your block to use Google Mock and prepare to be envied. Did I say life is unfair?

    Remember to download this episode and post it in your office!
    Toilet-Friendly Version
    [NFGB] Link - from Google Testing Blog
    Related From Google Blogs:
    Spice up your inbox with colors and themes
    Say hello to Gmail voice and video chat
    Street View: A year in review, and what's new
    Open Source Developers @ Google Speaker Series: Amit Singh

    Announcing Google C++ Mocking Framework

    Posted by Zhanyong Wan, Software Engineer

    Five months ago we open-sourced Google C++ Testing Framework to help C++ developers write better tests. Enthusiastic users have embraced it and sent in numerous encouraging comments and suggestions, as well as patches to make it more useful. It was a truly gratifying experience for us.

    Today, we are excited to release Google C++ Mocking Framework (Google Mock for short) under the new BSD license. When used with Google Test, it lets you easily create and use mock objects in C++ tests and rapid prototypes. If you aren't sure what mocks are or why you'll need them, our Why Google Mock? article will help explain why this is so exciting, and the Testing on the Toilet episode posted nearby on this blog gives a more light-hearted overview. In short, this technique can greatly improve the design and testability of software systems, as shown in this OOPSLA paper.

    We are happily using Google Mock in more than 100 projects at Google. It works on Linux, Windows, and Mac OS X. Its benefits include:
    • Simple, declarative syntax for defining mocks
    • Rich set of matchers for validating function arguments
    • Intuitive syntax for controlling the behavior of a mock
    • Automatic verification of expectations
    • Easy extensibility through new user-defined matchers and actions
    Our users inside Google have appreciated that Google Mock is easy and even fun to use, and is an effective tool for improving software quality. We hope you'll like it too. Interested? Please take a few minutes to read the documentation and download Google Mock. Be warned, though: mocking is addictive, so proceed at your own risk.

    And... we'd love to hear from you! If you have any questions or feedback, please meet us on the Google Mock Discussion Group. Happy mocking!
    [NFGB] Link - from Google Testing Blog
    Related From Google Blogs:
    Google Chrome (BETA)
    More Adventures from SciPy: Jenny Qing Qian
    Get your Gmail stickers
    Gmail on your Google Desktop

    Friday, November 28, 2008

    Guide to Writing Testable Code

    It is with great pleasure that I have been able to finally open-source the Guide to Writing Testable Code.

    I am including the first page here for you, but do come and check it out in detail.



    To keep our code at Google in the best possible shape we provided our software engineers with these constant reminders. Now, we are happy to share them with the world.

    Many thanks to these folks for inspiration and hours of hard work getting this guide done:

    Flaw #1: Constructor does Real Work

    Warning Signs

    • new keyword in a constructor or at field declaration
    • Static method calls in a constructor or at field declaration
    • Anything more than field assignment in constructors
    • Object not fully initialized after the constructor finishes (watch out for initialize methods)
    • Control flow (conditional or looping logic) in a constructor
    • Code does complex object graph construction inside a constructor rather than using a factory or builder
    • Adding or using an initialization block

    Flaw #2: Digging into Collaborators

    Warning Signs

    • Objects are passed in but never used directly (only used to get access to other objects)
    • Law of Demeter violation: method call chain walks an object graph with more than one dot (.)
    • Suspicious names: context, environment, principal, container, or manager

    Flaw #3: Brittle Global State & Singletons

    Warning Signs

    • Adding or using singletons
    • Adding or using static fields or static methods
    • Adding or using static initialization blocks
    • Adding or using registries
    • Adding or using service locators

    Flaw #4: Class Does Too Much

    Warning Signs

    • Summing up what the class does includes the word "and"
    • Class would be challenging for new team members to read and quickly "get it"
    • Class has fields that are only used in some methods
    • Class has static methods that only operate on parameters

    [NFGB] Link - from Google Testing Blog
    Related From Google Blogs:
    A sneak peek at Gmail on Android
    New in Labs: Advanced IMAP Controls
    LIFE Photo Archive available on Google Image Search
    New in Labs: Stop sending mail you later regret

    Thursday, November 27, 2008

    Online Machine Learning Testing == Extreme Testing

    Posted by Alek Icev, Test Engineering Manager

    As you may know our core vision is to build "The perfect search engine that would understand exactly what you mean and give back exactly what you want.". In order to do that we learn from our data, we learn from the past and we love Machine Learning. Everyday we are trying to answer the following questions.
    • Is this email spam?
    • Is this search result relevant?
    • What product category does that query belong to?
    • What is the ad that users are most likely to click on for the query "flowers"?
    • Is this click fraudulent?
    • Is this ad likely to result in a purchase (not merely a click)?
    • Is this image pornographic?
    • Does this page contain malware? Should this query bring up a maps onebox?
    Solving many problems require Machine Learning techniques. On all of them we can build prediction models that will learn from the past and try to give the most precise answers to our users. We use variety of Machine Learning algorithms at Google and we are experimenting with numerous old and new advancements in this field in order to find the most accurate, fast and reliable solution for the different problems that we are attacking. Of course one the biggest challenges that we are facing in the Test Engineering community is how are we going to test these algorithms. The amount of the data that Google generates goes beyond all of the known boundaries of environments where the current Machine Learning Solutions were being crafted and tested. We want to open discussion around the ideas how to test different online machine algorithms. From time to time we will present an algorithm and some ideas how to test it and solicit the feedback from the wider audience i.e. try to build a wisdom of the crowds over the testing ideas.

    So let's look at the Stochastic Gradient Descent Algorithm

    Where X is the set of input values of Xi ,W is set of the importance factors(weights) of every value Xi. A positive weight means that that risk factor increases the probability of the outcome, while a negative weight means that that risk factor decreases the probability of that outcome. t is the target output value, η is the learning rate(the role of the learning rate is to control the level to which the weights are modified at every iteration and f(z) is the output generated by the function that maps large input domain to a small set of output values in this case. The function f(z) in this case is the logistic function:

    f(z)=

    z = x0w0 + x1w1 + x2w2 + ... + xkwk

    The logistic function has nice characteristics since it can take any input, and basically squash it to 0 or 1. Ideal for predicting probabilities on events that are dependent on multiple factors(Xi) each with different importance weights(Wi). The Stochastic Gradient Descent provides fast convergence to find the optimal minimums of the error(E) that the function is making on the prediction as well as if there are multiple local minimums the algorithms guarantees converging to the global minimum of the prediction error. So let's go back now into the real online world where we want to give answers (predictions) to our users in milliseconds and ask the question how are we going to design automated tests for the Stochastic Gradient Descent Algorithm embedded into a live online prediction system. The environment is pretty agile and dynamic, the code is being changed every hour, you want your tests to run on 24/7 basis, you want to detect errors upstream in the development process, but you don't want to block the development process with tests that are running days, on the other side you want to release new features fast, but the release process has to be error prone(imagine the world with google being down for 5 mins, that is a global catastrophe, isn't it?!

    So let's look at some of the test strategies:

    Should we try to train the model(set of the importance factors) and test the model with the subset of the training data? What if this takes far more than hours, maybe days to do that? Should we try to reduce the set of importance factors (Xi) and get the convergence(E->0) on the reduced model?

    Should we try to reduce the training data set(the variety of set of values for X as an input to the algorithm) and keep the original model and get the convergence by any price? Should we be happy with reducing both the model size and the training set? Are we going to worry for over-fitting in the test environment? Given the original data is online data and evolves fast, are we going to be satisfied with fixed data test set or change the input test data frequently? What are the triggers that will make you do so? What else should we do?

    Drop us a note, all ideas are more than welcome.


    [NFGB] Link - from Google Testing Blog
    Related From Google Blogs:
    Syncing your Google Calendar
    Tip: Your email, wherever you are on the web, with Toolbar
    Triple silken pumpkin pie takes the prize
    Photo albums on orkut– the control is in your hands

    Tuesday, November 18, 2008

    TotT: Finding Data Races in C++

    If you've got some multi-threaded code, you may have data races in it. Data races are hard to find and reproduce – usually they will not occur in testing but will fire once a month in production.

    For example, you ask each of your two interns to bring you a bottle of beer. This will usually result in your getting two bottles (perhaps empty), but in a rare situation that the interns collide near the fridge, you may get fewer bottles.

    4 int bottles_of_beer = 0;
    5 void Intern1() { bottles_of_beer++; } // Intern1 forgot to use Mutex.
    6 void Intern2() { bottles_of_beer++; } // Intern2 copied from Intern1.
    7 int main() {
    8 // Folks, bring me one bottle of beer each, please.
    9 ClosureThread intern1(NewPermanentCallback(Intern1)),
    10 intern2(NewPermanentCallback(Intern2));
    11 intern1.SetJoinable(true); intern2.SetJoinable(true);
    12 intern1.Start(); intern2.Start();
    13 intern1.Join(); intern2.Join();
    14 CHECK_EQ(2, bottles_of_beer) << "Who didn't bring me my beer!?";
    15 }



    Want to find data races in your code? Run your program under Helgrind!

    $ helgrind path/to/your/program
    Possible data race during read of size 4 at 0x5429C8
    at 0x400523: Intern2() tott.cc:6

    by 0x400913: _FunctionResultCallback_0_0::Run() ...
    by 0x4026BB: ClosureThread::Run() ...
    ...
    Location 0x5429C8 has never been protected by any lock
    Location 0x5429C8 is 0 bytes inside global var "bottles_of_beer"
    declared at tott.cc:4



    Helgrind will also detect deadlocks for you.

    Helgrind is a tool based on Valgrind. Valgrind is a binary translation framework which has other useful tools such as a memory debugger and a cache simulator. Related TotT episodes will follow.

    No beer was wasted in the making of this TotT.

    Remember to download this episode of Testing on the Toilet and post it in your office.
    [NFGB] Link - from Google Testing Blog
    Related From Google Blogs:
    Better targeting your indic language site
    Voice and video chat now in Gmail
    Drum roll please: Introducing SketchUp 7
    Sites goes international

    Thursday, November 6, 2008

    Partial Automation: Keeping humans in the loop

    Legaspi, Test Engineering Manager

    One of the challenges of automation is achieving complete automation. Ideally, complete or total automation would not require any human intervention or verification yet this is a difficult level to achieve. Investing Engineering time to completely automate tests is expensive and, many times, has diminishing returns. Rather than trying to achieve complete automation, investing in ways to make the most out of the automated test and the human time is time better spent.

    Effective test report
    Consider an automated UI test... Routinely, automated UI tests result in false negatives due to timing issues, the complexity of the steps taken, and other factors. These have to be investigated which can be time consuming. A thorough report can be created for automated UI tests to present log information, error reports, screen shots of the state of the application when the test failed, and an easy way to re-run the test in question. A human can make use of the information provided and effectively investigate the possible issue. If we can reduce the amount of work that someone has to do to investigate a test failure, the UI tests become more valuable and the human plays a much more important role as a "verifier." Had the report not provided any information for the failed test, the human would have spent, in some cases, hours investigating the issue rather than continuing to automate or run exploratory tests which would be of more value. Is there a way to maximize what people do well, while also maximizing the use of automation?

    Applying human intelligence
    What about tests that require a human eye? There are many arguments about tests that require a human make a judgment about the appearance of rendered UI objects. Machines are great at running tests that return in a firm pass or fail but for tests that require opinion or judgment, the human has an advantage. We've been experimenting with image comparison tests. Screen shots of a golden version of the application under test are compared to screen shots of the current release candidate to verify that the application continues to render properly and that the UI "looks good". Although image comparison techniques can determine if the screen shots are different, they cannot help determine if the difference is "important". The human comes back into the picture to complement the automated test. To make effective use of a person's time, the test results should be organized and well presented. For image comparison tests, a report which shows the golden and release candidate screen shots side-by-side with clearly highlighted differences or allows you to replace the golden screen shot is key. A tester can quickly navigate the reported differences and determine if they are actual failures or acceptable differences. Frequently, an application's UI will change which will result in expected image differences. If the differences are expected changes, the tester should be able to replace the golden with the new image with the click of a button for future comparison.

    Aside from test automation, efficiency can also be improved by streamlining the various components of the process. This includes test environment setup, test data retrieval, and test execution. Release cycles tighten and so should the testing processes. Automating the environment setup can be a major time saver and allow for added time to run in depth tests. Creating continuous builds to run automated tests ahead of time and preparing environments overnight results in added testing time.

    Automated tests are rarely bullet proof, they are prone to errors and false failures. In some cases, creating an infrastructure to make test analysis easy for humans, is much more effective than trying to engineer tests to automatically "understand" the UI. We coined this, "Partial Automation." We found that by having a person in the loop dramatically reduces the time spent trying to over engineer the automated tests. Obviously, there are trade-offs to this approach and one size doesn't fit all. We believe that automation does not always need to mean complete automation; we automate as much as you can and consider how human judgment can be used efficiently.
    Link - from Google Testing Blog
    Related From Google Blogs:
    Online petition for an organic farm at the White House
    RTKM: Read the KML Manual!
    Tip: Your email, wherever you are on the web, with Toolbar
    New in Labs: Calendar and Docs gadgets

    Friday, October 31, 2008

    TotT: Contain Your Environment

    Many modules must access elements of their environment that are too heavyweight for use in tests, for example, the file system or network. To keep tests lightweight, we mock out these elements. But what if no mockable interface is available, or the existing interfaces pull in extraneous dependencies? In such cases we can introduce a mediator interface that's directly associated with your module (usually as a public inner class). We call this mediator an "Env" (for environment); this name helps readers of your class recognize the purpose of this interface.

    For example, consider a class that cleans the file system underlying a storage system:


    // Deletes files that are no longer reachable via our storage system's
    // metadata.
    class FileCleaner {
    public:
    class Env {
    public:
    virtual bool MatchFiles(const char* pattern, vector* filenames) = 0;
    virtual bool BulkDelete(const vector& filenames) = 0;
    virtual MetadataReader* NewMetadataReader() = 0;
    virtual ~Env();
    };
    // Constructs a FileCleaner. Uses "env" to access files and metadata.
    FileCleaner(Env* env, QuotaManager* qm);
    // Deletes files that are not reachable via metadata.
    // Returns true on success.
    bool CleanOnce();
    };



    FileCleaner::Env lets us test FileCleaner without accessing the real file system or metadata. It also makes it easy to simulate various kinds of failures, for example, of the file system:


    class NoFileSystemEnv : public FileCleaner::Env {
    virtual bool MatchFiles(const char* pattern, vector* filenames) {
    match_files_called_ = true;
    return false;
    }
    ...
    };

    TEST(FileCleanerTest, FileCleaningFailsWhenFileSystemFails) {
    NoFileSystemEnv* env = new NoFileSystemEnv();
    FileCleaner cleaner(env, new MockQuotaManager());
    ASSERT_FALSE(cleaner.CleanOnce());
    ASSERT_TRUE(env->match_files_called_);
    }



    An Env object is particularly useful for restricting access to other modules or systems, for example, when those modules have overly-wide interfaces. This has the additional benefit of reducing your class's dependencies. However, be careful to keep the "real" Env implementation simple, lest you introduce hard-to-find bugs in the Env. The methods of your "real" Env implementation should just delegate to other, well-tested methods.

    The most important benefits of an Env are that it documents how your class accesses its environment and it encourages future modifications to your module to keep tests small by extending and mocking out the Env.

    Remember to download this episode of Testing on the Toilet and post it in your office.

    Link - from Google Testing Blog
    Related:
    The stories behind the apps
    Clicks, conversions, and Christmas 2008
    The sandbox...it lives!

    Tuesday, October 28, 2008

    GUI Testing: Don't Sleep Without Synchronization

    Posted by Patrick Zembrod, Software Engineer in Test, Sweden

    So you're working on TheFinalApp - the ultimate end-user application, with lots of good features and a really neat GUI. You have a team that's keen on testing and a level of unit test coverage that others only dream of. The star of the show is your suite of automatic GUI end-to-end tests — your team doesn't have to manually test every release candidate.

    Life would be good if only the GUI tests weren't so flaky. Every once and again, your test case clicks a menu item too early, while the menu is still opening. Or it double-clicks to open a tree node, tries to verify the open too early, then retries, which closes the node (oops). You have tried adding sleep statements, which has helped somewhat, but has also slowed down your tests.

    Why all this pain? Because GUIs are not designed to synchronize with other computer programs. They are designed to synchronize with human beings, which are not like computers:


    • Humans act much more slowly. Well-honed GUI test robots drive GUIs at near theoretical maximum speed.

    • Humans are much better at observing the GUI, and they react intelligently to what they see.
    • Humans extract more meaningful information from a GUI.

    In contrast to testing a server, where you usually find enough methods or messages in the server API to synchronize the testing with the server, a GUI application usually lacks these means of synchronization. As a result, a running automated GUI test often consists of one long sequence of race conditions between the automated test and the application under test.

    GUI test synchronization boils down to the question: Is the app under test finished with what it's doing? "What it's doing" may be small, like displaying a combo box, or big, like a business transaction. Whatever "it" is, the test must be able to tell whether "it" is finished. Maybe you want to test something while "it" is underway, like verify that the browser icon is rotating while a page is loading. Maybe you want to deliberately click the "Submit" button again in the middle of a transaction to verify that nothing bad happens. But usually, you want to wait until "it" is done.

    How to find out whether "it" is done? Ask! Let your test case ask your GUI app. In other words: provide one or several test hooks suitable for your synchronization needs.

    The questions to ask depend on the type, platform, and architecture of your application. Here are three questions that worked for me when dealing with a single-threaded Win32 MFC database app:

    The first is a question for the OS. The Win32 API provides a function to wait while a process has pending input events:
    DWORD WaitForInputIdle(HANDLE hProcess, DWORD dwMilliseconds). Choosing the shortest possible timeout (dwMilliseconds = 1) effectively turns this from a wait-for to a check-if function, so you can explicitly control the waiting loop; for example, to combine several different check functions. Reasoning: If the GUI app has pending input, it's surely not ready for new input.

    The second question is: Is the GUI app's message queue empty? I did this with a test hook, in this case a WM_USER message; it could perhaps also be done by calling PeekMessage() in the GUI app's process context via CreateRemoteThread(). Reasoning: If the GUI app still has messages in its queue, it's not yet ready for new input.

    The third is more like sending a probe than a question, but again using a test hook. The test framework resets a certain flag in the GUI app (synchronously) and then (asynchronously) posts a WM_USER message into the app's message queue that, upon being processed, sets this flag. Now the test framework checks periodically (and synchronously again) to see whether the flag has been set. Once it has, you know the posted message has been processed. Reasoning: When the posted message (the probe) has been processed, then surely messages and events sent earlier to the GUI app have been processed. Of course, for multi-threaded applications this might be more complex.

    These three synchronization techniques resulted in fast and stable test execution, without any test flakiness due to timing issues. All without sleeps, except in the synchronization loop.

    Applying this idea to different platforms requires finding the right questions to ask and the right way to ask them. I'd be interested to hear if someone has done something similar, e.g. for an Ajax application. A query into the server to check if any XML responses are pending, perhaps?

    Link - from Google Testing Blog
    Related:
    Greater access to voting information
    Hispanic College Fund scholars visit Google D.C.
    Separate metrics for Google and search partners are now available
    YouTube - CPG Brands continuing innovation

    Friday, October 24, 2008

    Where Have all the "new" Operators Gone?

    (the other title: Your Application has a Wiring Problem)

    In My main() Method Is Better Than Yours we looked into what a main() method should look like. There we introduced a clear separation between (1) the responsibility of constructing the object graph and (2) the responsibility of running the application. The reason that this separation is important was outlined in How to Think About the "new" Operator. So let us look at where have all of the new operators gone...

    Before we go further I want you to visualize your application in your mind. Think of the components of your application as physical boxes which need to be wired together to work. The wires are the references one component has to another. In an ideal application you can change the behavior of the application just by wiring the components differently. For example instead of instantiating LDAPAuthenticator you instantiate KerberosAuthenticator and you wire the KerberosAuthenticator to appropriate components which need to know about Authenticator. That is the basic idea. By removing the new operators from the application logic you have separated the responsibility of wiring the components from the application logic, and this is highly desirable. So now the problem becomes, where have all the new operators gone?

    First lets look at a manual wiring process. In the main() method we asked the ServerFactory to build us a Server (in our case a Jetty Web Server) Now, server needs to be wired together with servlets. The servlets, in turn, need to be wired with their services and so on. Notice that the factory bellow is full of "new" operators. We are new-ing the components and we are passing the references of one component to another to create the wiring. This is the instantiation and wiring activity I asked you to visualize above. (Full source):

      public Server buildServer() {
    Server server = new Server();

    SocketConnector socketConnector
    = new SocketConnector();
    socketConnector.setPort(8080);
    server.addConnector(socketConnector);

    new ServletBuilder(server)
    .addServlet("/calc", new CalculatorServlet(
    new Calculator()))
    .addServlet("/time", new TimeServlet(
    new Provider() {
    public Date get() {
    return new Date();
    }
    }));

    return server;
    }

    When I first suggest to people that application logic should not instantiate its own dependencies, I get two common objections which are myths:

    1. "So now each class needs a factory, therefore I have twice as many classes!" Heavens No! Notice how our ServerFactory acted as a factory for many different classes. Looking at it I counted 7 or so classes which we instantiated in order to wire up our application. So it is not true that we have one to one correspondence. In theory you only need one Factory per object lifetime. You need one factory for all long-lived objects (your singletons) and one for all request-lifetime objects and so on. Now in practice we further split those by related concepts. (But that is a discussion for a separate blog article.) The important thing to realize is that: yes, you will have few more classes, but it will be no where close to doubling your load.

    2. "If each object asks for its dependencies, than I will have to pass those dependencies through all of the callers. This will make it really hard to add new dependencies to the classes." The myth here is that call-graph and instantiation-graph are one and the same. We looked into this myth in Where have all the Singletons Gone. Notice that the Jetty server calls the TimeServlet which calls the Date. If the constructor of Date or TimeServlet all of a sudden needed a new argument it would not effect any of the callers. The only code which would have to change is factory class above. This is because we have isolated the instantiation/wiring problem into this factory class. So in reality this makes it easier to add dependencies not harder.


    Now there are few important things to remember. Factories should have no logic! Just instantiation/wiring (so you will probably not have any conditionals or loops). I should be able to call the factory to create a server in a unit test without any access to the file-system, threads or any other expensive CPU or I/O operations. Factory creates the server, but does not run it. The other thing you want to keep in mind is that the wiring process is often controlled by the command line arguments. This makes is so that your application can behave differently depending what you pass in on a command line. The difference in behavior is not conditionals sprinkled throughout your code-base but rather a different way of wiring your application up.

    Finally, here are few thoughts on my love/hate of Singletons (mentioned here and here) First a little review of singletons. A singleton with a lower case 's' is a good singleton and simply means a single instance of some class. A Singleton with an upper case 'S' is a design pattern which is a singleton (one instance of some class) with a global "instance" variable which makes it accessible from anywhere. It is the global instance variable which makes it globally accessible , which turns a singleton into a Singleton. So singleton is acceptable, and sometimes very helpful for a design, but Singleton relies on mutable global state, which inhibits testability and makes a brittle, hard to test design. Now notice that our factory created a whole bunch of singletons as in a single instance of something . Also notice how those singletons got explicitly passed into the services that needed them. So if you need a singleton you simply create a single instance of it in the factory and than pass that instance into all of the components which need them. There is no need for the global variable.

    For example a common use of Singleton is for a DB connection pool. In our example you would simply instantiate a new DBConnectionPool class in the top-most factory (above) which is responsible for creating the long-lived objects. Now lets say that both CalculatorServlet and TimeServlet would need a connection pool. In that case we would simply pass the same instance of the DBConnectionPool into each of the places where it is needed. Notice we have a singleton (DBConnectionPool) but we don't have any global variables associated with that singleton.
      public Server buildServer() {
    Server server = new Server();

    SocketConnector socketConnector
    = new SocketConnector();
    socketConnector.setPort(8080);
    server.addConnector(socketConnector);

    DBConnectionPool pool = new DBConnectionPool();
    new ServletBuilder(server)
    .addServlet("/calc", new CalculatorServlet(
    pool,
    new Calculator()))
    .addServlet("/time", new TimeServlet(
    pool,
    new Provider() {
    public Date get() {
    return new Date();
    }
    }));

    return server;
    }
    Related:

    Wednesday, October 22, 2008

    Dependency Injection Myth: Reference Passing

    by Miško Hevery

    After reading the article on Singletons (the design anti-pattern) and how they are really global variables and dependency injection suggestion to simply pass in the reference to the singleton in a constructor (instead of looking them up in global state), many people incorrectly concluded that now they will have to pass the singleton all over the place. Let me demonstrate the myth with the following example.

    Let's say that you have a LoginPage which uses the UserRepository for authentication. The UserRepository in turn uses Database Singleton to get a hold of the global reference to the database connection, like this:

    class UserRepository {
    private static final BY_USERNAME_SQL = "Select ...";

    User loadUser(String user) {
    Database db = Database.getInstance();
    return db.query(BY_USERNAME_SQL, user);
    }
    }

    class LoginPage {
    UserRepository repo = new UserRepository();

    login(String user, String pwd) {
    User user = repo.loadUser(user);
    if (user == null user.checkPassword(pwd)) {
    throw new IllegalLoginException();
    }
    }
    }

    The first thought is that if you follow the advice of dependency injection you will have to pass in the Database into the LoginPage just so you can pass it to the UserRepository. The argument goes that this kind of coding will make the code hard to maintain, and understand. Let's see what it would look like after we get rid of the global variable Singleton Database look up.

    First, lets have a look at the UserRepository.

    class UserRepository {
    private static final BY_USERNAME_SQL = "Select ...";
    private final Database db;

    UserRepository(Database db) {
    this.db = db;
    }

    User loadUser(String user) {
    return db.query(BY_USERNAME_SQL, user);
    }
    }

    Notice how the removal of Singleton global look up has cleaned up the code. This code is now easy to test since in a test we can instantiate a new UserRepository and pass in a fake database connection into the constructor. This improves testability. Before, we had no way to intercept the calls to the Database and hence could never test against a Database fake. Not only did we have no way of intercepting the calls to Database, we did not even know by looking at the API that Database is involved. (see Singletons are Pathological Lairs) I hope everyone would agree that this change of explicitly passing in a Database reference greatly improves the code.

    Now lets look what happens to the LoginPage...

    class LoginPage {
    UserRepository repo;

    LoginPage(Database db) {
    repo = new UserRepository(db);
    }

    login(String user, String pwd) {
    User user = repo.loadUser(user);
    if (user == null user.checkPassword(pwd)) {
    throw new IllegalLoginException();
    }
    }
    }

    Since UserRepository can no longer do a global look-up to get a hold of the Database it musk ask for it in the constructor. Since LoginPage is doing the construction it now needs to ask for the Databse so that it can pass it to the constructor of the UserRepository. The myth we are describing here says that this makes code hard to understand and maintain. Guess what?! The myth is correct! The code as it stands now is hard to maintain and understand. Does that mean that dependency injection is wrong? NO! it means that you only did half of the work! In how to think about the new operator we go into the details why it is important to separate your business logic from the new operators. Notice how the LoginPage violates this. It calls a new on UserRepository. The issue here is that LoginPage is breaking a the Law of Demeter. LoginPage is asking for the Database even though it itself has no need for the Database (This greatly hinders testability as explained here). You can tell since LoginPage does not invoke any method on the Database. This code, like the myth suggest, is bad! So how do we fix that?

    We fix it by doing more Dependency Injection.

    class LoginPage {
    UserRepository repo;

    LoginPage(UserRepository repo) {
    this.repo = repo;
    }

    login(String user, String pwd) {
    User user = repo.loadUser(user);
    if (user == null user.checkPassword(pwd)) {
    throw new IllegalLoginException();
    }
    }
    }

    LoginPage needs UserRepository. So instead of trying to construct the UserRepository itself, it should simply ask for the UserRepository in the constructor. The fact that UserRepository needs a reference to Database is not a concern of the LoginPage. Neither is it a concern of LoginPage how to construct a UserRepository. Notice how this LoginPage is now cleaner and easier to test. To test we can simply instantiate a LoginPage and pass in a fake UserRepository with which we can emulate what happens on successful login as well as on unsuccessful login and or exceptions. It also nicely takes care of the concern of this myth. Notice that every object simply knows about the objects it directly interacts with. There is no passing of objects reference just to get them into the right location where they are needed. If you get yourself into this myth then all it means is that you have not fully applied dependency injection.

    So here are the two rules of Dependency Injection:

    • Always ask for a reference! (don't create, or look-up a reference in global space aka Singleton design anti-pattern)
    • If you are asking for something which you are not directly using, than you are violating a Law of Demeter. Which really means that you are either trying to create the object yourself or the parameter should be passed in through the constructor instead of through a method call. (We can go more into this in another blog post)

    So where have all the new operators gone you ask? Well we have already answered that question here. And with that I hope we have put the myth to rest!

    BTW, for those of you which are wondering why this is a common misconception the reason is that people incorrectly assume that the constructor dependency graph and the call graph are inherently identical (see this post). If you construct your objects in-line (as most developers do, see thinking about the new operator) then yes the two graphs are very similar. However, if you separate the object graph instantiation from the its execution, than the two graphs are independent. This independence is what allows us to inject the dependencies directly where they are needed without passing the reference through the intermediary collaborators.


    Link - from Google Testing Blog
    Related:
    Test Engineering at Google
    TotT: Floating-Point Comparison
    Bioneers, Day Three
    New in Labs: Canned Responses

    Sunday, October 19, 2008

    My main() Method Is Better Than Yours

    By Miško Hevery

    People are good at turning concrete examples into generalization. The other way around, it does not work so well. So when I write about general concepts it is hard for people to know how to translate the general concept into concrete code. To remedy this I will try to show few examples of how to build a web application from ground up. But I can't fit all of that into a single blog post ... So lets get started at the beginning...

    Here is what your main method should look like (no matter how complex your application) if you are using GUICE: (src)

    public static void main(String[] args)
    throws Exception {
    // Creation Phase
    Injector injector = Guice.createInjector(
    new CalculatorServerModule(args));
    Server server = injector.getInstance(Server.class);
    // Run Phase
    server.start();
    }

    Or if you want to do manual dependency injection: (src)
    public static void main(String[] args)
    throws Exception {
    // Creation Phase
    Server server = new ServerFactory(args)
    .createServer();
    // Run Phase
    server.start();
    }

    The truth is I don't know how to test the main method. The main method is static and as a result there are no places where we can inject test-doubles. (I know we can fight static with static, but we already said that global state is bad here, here and here). The reason we can't test this is that the moment you execute the main method the whole application runs, and that is not what we want and there is nothing we can do to prevent that.

    But the method is so short that I don't bother testing it since it has some really cool properties:

    1. Notice how the creation-phase contains the code which builds the object graph of the application. The last line runs the application. The separation is very important. We can test the ServerFactory in isolation. Passing it different arguments and than asserting that the correct object graph got built. But, in order to do that the Factory class should do nothing but object graph construction. The object constructors better do nothing but field assignments. No reading of files, starting of threads, or any other work which would cause problems in unit-test. All we do is simply instantiate some graph of objects. The graph construction is controlled by the command line arguments which we passed into the constructor. So we can test creation-phase in isolation with unit-test. (Same applies for GUICE example)

    2. The last line gets the application running. Here is where you can do all of your fun threads, file IO etc code. However, because the application is build from lots of objects collaborating together it is easy to test each object in isolation. In test I just instantiate the Server and pass in some test doubles in the constructor to mock out the not so interesting/hard to test code.


    As you can see we have a clear separation of the object graph construction responsibility from the application logic code. If you were to examine the code in more detail you would find that all of the new operators have migrated from the run-phase to creation-phase (See How to Think About the "new" Operator) And that is very important. New operator in application code is enemy of testing, but new in tests and factories is your friend. (The reason is that in tests we want to use test-doubles which are usually a subclass or an implementation of the parent class. If application code calls new than you can never replace that new with a subclass or different implementation.) The key is that the object creation responsibility and the the application code are two different responsibilities and they should not be mixed. Especially in the main method!

    A good way to think about this is that you want to design your application such that you can control the application behavior by controlling the way you wire the objects together (Object collaborator graph). Whether you wire in a InMemory, File or Database repository, PopServer or IMAPServer, LDAP or file based authentication. All these different behaviors should manifest themselves as different object graphs. The knowledge of how to wire the objects together should be stored in your factory class. If you want to prevent something from running in a test, you don't place an if statement in front of it. Instead you wire up a different graph of objects. You wire NullAthenticator in place of LDAPAuthenticator. Wiring your objects differently is how the tests determines what gets run and what gets mocked out. This is why it is important for the tests to have control of the new operators (or putting it differently the application code does not have the new operators). This is why we don't know how to test the main method. Main method is static and hence procedural. I don't know how to test procedural code since there is nothing to wire differently. I can't wire the call graph different in procedural world to prevent things from executing, the call graph is determined at compile time.

    In my experience that main method usually is some of the scariest code I have seen. Full of singleton initialization and threads. Completely untestable. What you want is that each object simply declares its dependencies in its constructor. (Here is the list of things I need to know about) Then when you start to write the Factory it will practically write itself. You simply try to new the object you need to return, which declares its dependencies, you in turn try to new those dependencies, etc... If there are some singletons you just have to make sure that you call the new operator only once. But more on factories in our next blog post...

    Link - from Google Testing Blog
    Related:
    Root Cause of Singletons
    TotT: Sleeping != Synchronization
    Where Have All the Singletons Gone?
    Singletons are Pathological Liars