I spent some time today thinking about the best way of writing unit tests for GUI code. The key is determining whether your rendering code is issuing the correct set / sequence of commands to the graphics subsystem.
At some point, you have to take it on faith that the commands that you issue to the graphics subsystem will result in pixels being painted at the correct positions on the screen. This is not what I’m trying to accomplish in my unit tests; that’s what Microsoft and the device driver writers have to guarantee will happen.
Instead, I would be happy if I could capture a “correct result” in my unit tests. Imagine that you could describe the correct result as an XML document that contains the rendering commands and their parameters. For example:
<DrawEllipse>
<Pen name="Pens.Black"/>
<Rectangle x="1" y="1" width="100" height="100"/>
</DrawEllipse>
Next, imagine that I can intercept the call to Graphics.DrawEllipse( Pen pen, Rectangle rect ). I could then log the method call as XML, which can easily be compared to the correct result using an XML diff tool.
In practice, this is a lot harder than it looks. If you examine the System.Drawing.Graphics class, you’ll find two problems. The first is that the class is sealed, which prevents you from deriving a plug-compatible class from it. However, even if the class wasn’t sealed, you would wouldn’t be able to intercept the methods because methods like DrawEllipse aren’t virtual.
In an ideal world, Microsoft would have defined the interface to the Graphics class via an IGraphics interface. This way, we would be free to cruft up our own plug-compatible implementation that could be used in place of the real Graphics class when we run our unit tests.
One way of solving this problem would be to pull out the ultimate hacker weapons - runtime method interception extensions to the CLR. My project-in-limbo, CLAW, would have let me solve this problem by defining an interception layer between the caller and the real Graphics object.
There is, of course, a simpler way of solving a subset of the UI rendering problem. You can create a Graphics object that wraps the existing Graphics object.
public void DrawEllipse( Pen pen, Rectangle rect ) {
if( Test )
LogCall( pen, rect );
else
Graphics.DrawEllipse( pen, rect );
}
The problem with this approach is, of course, that this only works with code that was compiled explicitly against the surrogate Graphics class. So this technique would only be able to test your custom rendering code, but wouldn’t be able to test whether Framework rendering code was rendering correctly.
Any thoughts about how to solve this problem without resorting to runtime method interception of the real Graphics class would be welcome.Â
6 archived reader comments
Joe Beda (2003-07-31)
Hi John,
Are there any other uses for extending the graphics object that you see besides just logging of commands like this? Would another way to “capture” what is drawn to the screen (in a metafile like way — not as a bitmap) be good enough for what you are doing?
I ask this because providing virtuals is a really dangerous thing. Every time we provide a call out in to user code from the system we create a place where we have to be *super* careful moving forward to maintain backward compatibility. For instance, if we have a control that we ship that calls DrawEllipse, and the developer hooks that to change something else in the system, we may not be able to call DrawPath (or something else) in the next version because the developer is expecting DrawEllipse. While saying “that developer is confused and doing something wrong” and that we should just be able to break the app, we may not have the choice. Does my Mom care that her app stoped working with windows 2010 because some app developer was breaking the rules?
Beyond this, interfaces don’t version that well. Do we really want IGraphics, IGraphics2, IGraphics3, etc?
BradA (who is something of an authority on these things) has this to say about it: http://blogs.gotdotnet.com/BradA/permalink.aspx/bbda1815-f6b8-488a-83a2-22bd6c2f4bf5
“Annotation - The peril. If you ship types with virtual members you are promising to forever abide by subtle and complex observable behaviors and subclass interactions.
I think API designers underestimate their peril. For example, we found that ArrayList item enumeration calls several virtual methods per each MoveNext and Current. Fixing those performance problems could (but probably doesn’t) break user-defined implementations of virtual members on the ArrayList class that are dependent upon virtual method call order/frequency.”
Joe
John Lam (2003-07-31)
Thanks for the comments, Joe!
If you guys can provide a metafile-like experience in V.Next, that would let me do what I’m trying to do. It’s also super-important to allow that metafile format to be serializable as XML (if it isn’t already) so that it reduces the amount of friction required to integrate it with other tools.
I totally agree with your concerns about unsealing Graphics and exposing virtual functions. But what about my interface proposal? While nobody wants to have to support multiple IGraphics interfaces, how are class “interfaces” any better off? With interfaces (and a pluggable abstract factory) I have the ability to substitute a different Graphics object at runtime. This lets me do all sorts of things that are otherwise impossible today.
BTW, I really like the fact that the ASP.NET team chose to define interfaces for both HttpModules and HttpHandlers; this makes it much easier for me to create mock objects for testing UI rendering in ASP.NET.
Joe Beda (2003-07-31)
I make no promises about what we are or aren’t going to ship in V.Next :) (“I have no recollection of that Senator. I can niether confirm nor deny those allegations”)
Generally, classes are preferred over interfaces for a variety of reasons. I’m not the expert here, but versioning is definitely the big reason. Since you can have “default” implementations to go along with a virtual on a base class, you can add new functions in v.Next and provide a default implementation. With an interface, once you ship that interface you are stuck with it forever. You can’t add new methods to that interface.
Also, any time that you pass that interface to the “system” there is an implied contract about how and when the system calls you back on that interface.
I think that in some ways the ASP.Net server model is a lot simpler because the dialog of what gets called when is pretty simple and is set in stone for all time. UI is much more chatty and providing those same types of assurances isn’t nearly so easy.
(As an aside, when I was working on IE, calling out into script or ActiveX objects was something we had to be careful of. We had to protect against all sorts of reentrancy and any time we changed behavior we had app compat bugs. For instance, we had an object (I won’t name names)where on the final release call that object would pump the message loop. This would cause us to be reentered while we were tearing down and could easily lead to crashes. Providing protection in cases like this can be expensive — you trust your code but you *can’t* trust third party code not to do something like that. And this was a Microsoft ActiveX object…)
Joe
Joe Madia (2003-08-01)
Hey John… it occurred to me that since Graphics is derived from MarshalByRef, it’s possible to use a custom RealProxy for interception. Unfortunately, this is a form of runtime interception so it doesn’t actually meet your requirements. Still… it’s pretty fun to play around with:
using System; using System.Drawing; using System.Diagnostics; using System.Runtime.Remoting; using System.Runtime.Remoting.Proxies; using System.Runtime.Remoting.Messaging; using System.Windows.Forms;
namespace GraphicsInterception { public class MainForm : System.Windows.Forms.Form { public MainForm() { Text = “Graphics Interception Test”; }
protected override void OnPaint(PaintEventArgs e) { base.OnPaint (e);
GraphicsProxy graphicsProxy = new GraphicsProxy(e.Graphics); Graphics graphics = (Graphics) graphicsProxy.GetTransparentProxy();
graphics.DrawRectangle(Pens.Black, 20, 20, 120, 120); graphics.DrawEllipse(Pens.Black, 30, 30, 100, 100); }
/// /// The main entry point for the application. /// [STAThread] static void Main() { Application.Run(new MainForm()); } }
public class GraphicsProxy : RealProxy { public GraphicsProxy(Graphics
IN_Target) : base(typeof(Graphics)) {M_Target=IN_Target; }public override IMessage Invoke(IMessage
IN_Message) { IMethodCallMessage methodCallMessage = (IMethodCallMessage)IN_Message;bool firstArg = true;
Debug.Write(“Graphics.” + methodCallMessage.MethodName + “(“); foreach (object argument in methodCallMessage.Args) { if (firstArg == false) { Debug.Write(“, “); } Debug.Write(argument); firstArg = false; } Debug.WriteLine(“);”);
return RemotingServices.ExecuteMessage(
M_Target, (IMethodCallMessage)IN_Message); }private Graphics
M_Target; } }John Lam (2003-08-01)
Thanks for posting that code frag, Joe! I’ll have to check it out on my trip next week and see how well I can get it to work. But it looks really promising!
Phlip (2003-12-21)
I research using automated tests to force code to exist - even if it’s complex GUI code. That means I don’t write code until I can make a test fail because it does not exist.
But this implies I must research ways to ‘get()’ variables that all our libraries and tutorials expect us only to ‘set()’.
To discuss why John’s XML suggestion this is the right motivation but a high risk solution, first we must define some terms.
A “hyperactive” assertion fails when an end-user would have thought the program succeeded.
Because end-users consider late delivery a failure, we like over-active assertions that constrain refactors more aggressively than traditional test-last could. Suppose we replace a device context with a mock object that records all calls, and we use this test and code:
assert_equal“circle, square”, aContext.getReport() … aContext.DrawCircle(…); aContext.DrawSquare(…);Refactors strictly preserve behavior. But what if a re-featurization reverses the order of the calls:
aContext.DrawSquare(…); aContext.DrawCircle(…);
Assuming opaque pens of the same color, users can’t tell the difference. But the test would fail.
In these situations, we must either force the re-featurization to preserve irrelevant behavior, or tweak the test.
If the test covered many miles of GDI calls, then John’s suggestion of using an XML diff tool would be a “bulk assertion”. Bulk assertion hyperactivity only works when you also have much more narrow unit-level tests, and when you have an easy mechanism to transfer failing test results into the reference results.
Now that we know how to avoid this technique becoming a bad thing, here’s how to do it for GDI, via WTL.
Under MS Windows, if you need your List Box control to present anything except a short list of simple strings, you must set its resource declaration to “ownerdraw” mode:
LISTBOX
IDC_LIST_CUSTOMERS, 5,7,79,108,LBS_SORT|LBS_NOINTEGRALHEIGHT|WS_VSCROLL|WS_TABSTOP|LBS_OWNERDRAWFIXED|LBS_HASSTRINGSThen handle OnDrawItem():
BEGIN_MSG_MAP(ProjectDlg)MESSAGE_HANDLER(WM_INITDIALOG, OnInitDialog)MESSAGE_HANDLER(WM_DRAWITEM, OnDrawItem)COMMAND_ID_HANDLER(IDOK, OnClose)COMMAND_ID_HANDLER(IDCANCEL, OnClose)END_MSG_MAP()LRESULT ProjectDlg::OnDrawItem(UINT, WPARAM, LPARAM lParam, BOOL &) { DRAWITEMSTRUCT & aDrawItem = *
reinterpret_cast(lParam);CDCHandle aDC(aDrawItem.hDC);
BOOL worked = aDC.TextOut ( aDrawItem.rcItem.left, aDrawItem.rcItem.top, “whatever” ); assert(worked); return 0; }
Note the TextOut() there does not pull the listbox’s item string; it sends “whatever”. Our goal is to write a test that intercepts this lie.
To test that OnDrawItem() drew something into a device context, we must pass a device context capable of intercepting GDI calls as a stream of commands and recording them. MS Windows calls these streams “MetaFiles”. So the strategy is to calculate the correct size for the MetaFile, create a MetaFile-based Device Context, put it into a DRAWITEMSTRUCT, pass this into the
WM_DRAWITEMhandler, and Close() the MetaFile-based Device Context. That returns a HMETAFILE, which we must check contains the correct records:TEST_(TestDialog,
WM_DRAWITEM) { CListBox aList =m_aDlg.GetDlgItem(IDC_LIST_CUSTOMERS);DWORD style = aList.GetStyle();
CPPUNIT_ASSERT(style &LBS_OWNERDRAWFIXED);CPPUNIT_ASSERT(style &LBS_HASSTRINGS);CDC aDC = aList.GetDC();
// calculate the correct size for the MetaFile
int mmWidth = aDC.GetDeviceCaps(HORZSIZE); int mmHeight = aDC.GetDeviceCaps(VERTSIZE); int pixelsWidth = aDC.GetDeviceCaps(HORZRES); int pixelsHeight = aDC.GetDeviceCaps(VERTRES); int xMmPerPixel = (mmWidth * 100) / pixelsWidth; int yMmPerPixel = (mmHeight * 100) / pixelsHeight;
RECT rc; aList.GetItemRect(0, & rc); rc.left *= xMmPerPixel; rc.top *= yMmPerPixel; rc.right *= xMmPerPixel; rc.bottom *= yMmPerPixel;
// create a MetaFile-based Device Context
CEnhMetaFileDC aDCmeta; aDCmeta.Create(aDC, “sample.emf”, &rc, “test”);
// fake a
WM_DRAWITEMmessageDRAWITEMSTRUCT aDrawItem = {
ODT_LISTBOX}; aDrawItem.CtlID =IDC_LIST_CUSTOMERS; aDrawItem.itemID = 0; aDrawItem.itemAction =ODA_FOCUS; aDrawItem.itemState =ODS_SELECTED; aDrawItem.hwndItem = aList; aDrawItem.hDC = aDCmeta; aDrawItem.rcItem = rc; LPARAM param =reinterpret_cast(&aDrawItem);m_aDlg.SendMessage(WM_DRAWITEM, 0, param);// Closing the DC returns a HMETAFILE
CEnhMetaFile metaFile(aDCmeta.Close());
// inspect the MetaFile for the correct record
std::wstringstream payload;
BOOL worked = EnumEnhMetaFile ( NULL, metaFile, metaFileRecordFunction, &payload, &aDrawItem.rcItem );
CPPUNIT_ASSERT(worked);CPPUNIT_ASSERT(L”Ignatz\tMouse” == payload.str()); }MS Windows depends on a C-style Execute Around Pattern, which requires copious typecasts between void pointers and typed ones. So the best implementation of metaFileRecord() we can hope for is this:
int CALLBACK metaFileRecordFunction ( HDC, HANDLETABLE FAR *, CONST ENHMETARECORD *rec, int, LPARAM param ) { switch (rec->iType) { case
EMR_HEADER: caseEMR_EOF: break;case
EMR_EXTTEXTOUTW: { EMREXTTEXTOUTW const & aTextOut = *reinterpret_cast(rec);std::wstringstream &payload = *
reinterpret_cast(param);char const * p =
reinterpret_cast(rec);p += aTextOut.emrtext.offString;
wchar_tconst * text =reinterpret_cast(p);payload.write(text, aTextOut.emrtext.nChars); } break;
default: assert(false); } return true; }
That extracts the text from a EMREXTTEXTOUTW record. I will never see a EMREXTTEXTOUTA record as long as I use Windows XP here. When I called TextOut(), it was really TextOutA(), but Windows NT-based platforms internally convert all strings to their wide, UCS versions. So p points to that widened string inside the EMREXTTEXTOUTW record; text points to the same place but thru a wide pointer, and payload.write() pushes that wide string into a wide wstringstream. I had to use .write(), not operator<<, because text was not L’\0’ terminated.
The result of all that infrastructure is this line:
CPPUNIT_ASSERT(L”Ignatz Mouse” == payload.str());We could not use
CPPUNIT_ASSERT_EQUAL() because that expects 8-bit strings. Eventually we could provide aCPPUNIT_ASSERT_EQUAL_W() for thesewchar_tsituations.Oh, by the way, the line fails. We must now start providing the correct OnDrawItem implementation, including special cases for selected and focused items. The tests will then constrain the refactors that make clean code out of those special cases.
More important, a few more tests that turn GDI streams into wstringstreams are all we need to promote the code around metaFileRecordFunction() into a fixture that makes assertions regarding GDI calls easy to code. Including tests that call lots of GDI routines, then test them all at once using over-active bulk assertions.
– Phlip