Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Controlling time of QTimer?

Tags:

c++

time

testing

qt

I'm considering rewriting some existing C code using C++ and Qt. In the C code poll is used to check for input from several sources, and each source has a timeout value and some specific behaviour tied to it. For instance

  • after 5 minutes silence on intput0 we assume the other side is dead and we try to re-establish contact
  • we expect clients to connect to socket0
  • once a client has connected to socket0 a call to accept is made (socket1), a client gets one minute to make a request before socket1 is closed down

This sort of thing isn't too difficult test, by using LD_PRELOAD and "hiding" the involved system functions (poll, gettimeofday) one can (somewhat) easily control passage of time and trigger timeouts.

Moving to Qt I was planning on wrapping the filedescriptors in instances of QSocketNotifier and connect the activated(int) signal to a suitable slot. That basically provides a Qt-flavoured poll -- except there are no timeouts!

For timeouts I'm looking at coupling a QTimer to each QSocketNotifier. My experimentation shows this to work, and be rather elegant. However, it's not pleasurable to test. I can't really have tests that sit and wait 5 minutes for a timeout.

How do I go about making the timeouts in this solution testable?

(Or maybe I'm just thinking about this the wrong way, and should do something completely different.)

like image 366
Magnus Avatar asked Oct 17 '25 21:10

Magnus


1 Answers

I believe the question can be paraphrased as "how to mock QTimer?" The answer to this reworded question is "indirectly." You could write your main program with an abstraction over QTimer, which would then be mocked by the test code to emit signals based on test needs instead of based on time.

One particular way of approaching this could be for the test code to disconnect the slot from the QTimer's signal, and connect its own signal in its place.

like image 179
Angew is no longer proud of SO Avatar answered Oct 20 '25 10:10

Angew is no longer proud of SO