I have an auto-reset event object created like this:
handle = CreateEvent(NULL, true, false, NULL);
…and (for some unit testing purposes) I want to check if it’s signalled at a certain point. I’m aware of the ‘correct’ way of using events – this is purely for a diagnostic harness.
For a manual reset event I can just use…
bool signalled = WaitForSingleObjectEx(handle, 0, true) != WAIT_TIMEOUT;
…but for auto-reset events that has the side-effect of resetting them. I guess I could try this, but I have a feeling that there should be a less dangerous way…?
bool isSignalled(HANDLE handle)
{
bool signalled = WaitForSingleObjectEx(handle, 0, true) != WAIT_TIMEOUT;
// warning - event is now reset. Maybe need to wrap this in a critical section or similar?
if (signalled)
SetEvent(handle);
return signalled;
}
I don’t see a simple way to do it. You could “mock” the event for testing purposes.
Wrap the event in an C++ object, and change all the code to use its methods.
Then you’ll want to use some sort of reference counted pointer that can be passed around and copied the way the original HANDLE can be:
Replace all your code that uses the raw HANDLE with a MockEventPtr.
And so on.
Now, for your diagnostic harness, you can extend MockEvent to keep track of the state and expose a method to show the current state.
This is untested code. In real code, I’d wrap the CRITICAL_SECTION, too. Note that the result of IsSignaled may be obsolete the moment you get it, if another thread changes the state. I’m assuming this is for testing code that will check at a time when the state should be a certain way.