Writing a unit test for a singleton implementation

Idan Arye GenericNPC at gmail.com
Wed May 15 15:21:58 PDT 2013


On Wednesday, 15 May 2013 at 21:52:40 UTC, Dmitry Olshansky wrote:
> Sleep in concurrency code that aims to synchronize something is 
> always bad idea (=BUG).

Don't say "always". Only a Sith deals in absolutes. Sure, 
`sleep()` in concurrent code is a bad idea because it can cause 
race conditions. But I *want* to (almost)cause a race condition 
here - that's the whole point of this unit test, to guarantee 
that the singleton implementation is immune to race conditions.

Crashing your car into a brick wall is usually a bad idea, but 
not always. When they want to test the car's safety systems, they 
crash it into a wall on purpose. The fact that driving safety 
rules save lives does not mean the crash test team has to stick 
to those rules - that would defeat the purpose of the crash test.

> Sleep is a tool used to give up thread execution resources to 
> avoid spinning on something wasting cycles. Use semaphore or 
> analogous primitives to coordinate, see other posts.

In my second version of the unit test(after reading Diggory's 
comment) I used a `Barrier` to coordinate, and it gave me 50% 
accuracy - That is, when I took the synchronization out of the 
implementation the unit test failed 50% of the times. I still 
need the `sleep()` to make sure the threads are getting mixed.

> One word - it's a stress test (smoke test). It should be a kind 
> of loop that executes for as long as you can allow it. Days 
> later if it didn't fail usually you either decide that it 
> should be "good enough" or keep running them.

Why in the world would I want to make a unit test for days, 
waiting for a race condition that might not happen, when I can 
easily force a race condition?

If we return to the car's crash test example - when a crash test 
team wants to test a car, do they give alcohol to a team member 
and make him drive around while following him with measure 
devices? Ofcourse not - they simply drive the car directly to the 
brick wall.


More information about the Digitalmars-d mailing list