Search code examples
c++linuxtdd

Missing capabilities for unit test


I've implemented a C++ Class that will execute something in a timed cycle using a thread. The thread is set to be scheduled with the SCHED_DEADLINE scheduler of the Linux kernel. To setup the Scheduler the process running this must have certain Linux capabilities.

My question is, how to test this?

I can of course make a unit test and create the threat, do some counting an exit the test after a time to validate the cycle counter but that only works if the unit test is allowed to apply the right scheduler. If not, the default scheduler applies and the timing of the cyclic loops will be immediate and therefore executes a different behaviour.

How would you test this scenario?

Some Code Example:

void thread_handler() {

  // setup SCHED_DEADLINE Parameters

  while (running) {
 
    // execute application logic

    sched_yield();

  }
}

Solution

  • There two separate units to test here. First the cyclic execution of code and second the strategy with the os interface. The first unit would look like this:

      class CyclicThread : public std::thread {
    
        public:
    
          CyclicThread(Strategy& strategy) : 
            std::thread(bind(&CyclicThread::worker, this)),
            strategy(strategy) { }
    
          add_task(std::function<void()> handler) {
             ...
          }
    
        private:
    
          Strategy& strategy;
          void worker() {
    
            while (running) {
              execute_handler()
              strategy.yield();
            }
    
          }
      }
    

    This is fairly easy to test with a mock object of the strategy.

    The Deadline scheduling strategy looks like this:

    
    class DeadlineStrategy {
    
      public:
    
        void yield() {
          sched_yield();
        }
    
    }
    

    This class can also be tested fairly easy by mocking the sched_yield() system call.