views:

174

answers:

4

I've written a function to return the time_t value corresponding to midnight on a given day. When there is no midnight for a given day, it returns the earliest time available; that situation can occur, for example, when Egypt enters daylight-saving time. This year, the time change takes effect at midnight on the night of April 29, so the clock goes directly from 23:59 to 01:00.

Now I'm writing unit tests for this function, and one of the tests should replicate the Egypt scenario. In Unix, I can accomplish it like this:

putenv("TZ", "Egypt", true);
tzset();

After doing that, further calls to localtime behave as if they're in Egypt instead of Minnesota, and my tests pass. Merely setting the environment variable doesn't have any effect on Windows, though. What can I do to make the unit test think it's somewhere else without affecting the rest of the programs running on the system?

A: 

Have you seen the SetTimeZoneInformation Win32 API function?

LBushkin
Doesn't that change the time zone for the entire OS? I want something limited to the current process (or thread), suitable for use in a unit test.
Rob Kennedy
@Rob: Yes, it affects the entire machine. To my knowledge, there's not thread-local version. However, if it's just for unit testing purposes then that may still be ok if you restore the original time zone in your test teardown method.
LBushkin
Perhaps my employer has a different philosophy about unit tests than you do. If something changes system-wide settings, it's no longer classified as a unit test, and it won't get run as part of the build process. Many people could be using the same build server, and their tests shouldn't interfere with each other.
Rob Kennedy
A: 

I used setlocale(LC_ALL, "deu_aut") to switch the language/country settings to Austria - declared in locale.h. Sadly i haven't found a language/country string for egypt, but perhaps this gives you a hint.

Christian Ammer
The language and country for Egypt is `ar_EG` (for *Arabic*). But those settings don't affect the time zone. They can affect the format used to display the current time, but that's not really the same thing.
Rob Kennedy
A: 

I have exactly the same requirement:

->some processes must be stuck to UTC and others to some timezone different from the Windows system timezone

After months of (interrupted) study I fall to the conclusion that on Windows it is only possible to set "UTC" or "current" system time zone. So only the following may be done:

     - set TZ="UTC" 
     - unset TZ
Alex
+1  A: 

Use Isolation/Mocking framework - the only one I know of at the moment is Isolator++ which is currently in beta, I'm sure that you can get a copy by asking for one from the good people of Typemock.

Dror Helper