Home | History | Annotate | Download | only in tests
      1 /*
      2  * Copyright (C) 2010 The Android Open Source Project
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  *      http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 
     17 #ifndef TESTHELPERS_H
     18 #define TESTHELPERS_H
     19 
     20 #include <utils/threads.h>
     21 
     22 namespace android {
     23 
     24 class Pipe {
     25 public:
     26     int sendFd;
     27     int receiveFd;
     28 
     29     Pipe() {
     30         int fds[2];
     31         ::pipe(fds);
     32 
     33         receiveFd = fds[0];
     34         sendFd = fds[1];
     35     }
     36 
     37     ~Pipe() {
     38         if (sendFd != -1) {
     39             ::close(sendFd);
     40         }
     41 
     42         if (receiveFd != -1) {
     43             ::close(receiveFd);
     44         }
     45     }
     46 
     47     status_t writeSignal() {
     48         ssize_t nWritten = ::write(sendFd, "*", 1);
     49         return nWritten == 1 ? 0 : -errno;
     50     }
     51 
     52     status_t readSignal() {
     53         char buf[1];
     54         ssize_t nRead = ::read(receiveFd, buf, 1);
     55         return nRead == 1 ? 0 : nRead == 0 ? -EPIPE : -errno;
     56     }
     57 };
     58 
     59 class DelayedTask : public Thread {
     60     int mDelayMillis;
     61 
     62 public:
     63     DelayedTask(int delayMillis) : mDelayMillis(delayMillis) { }
     64 
     65 protected:
     66     virtual ~DelayedTask() { }
     67 
     68     virtual void doTask() = 0;
     69 
     70     virtual bool threadLoop() {
     71         usleep(mDelayMillis * 1000);
     72         doTask();
     73         return false;
     74     }
     75 };
     76 
     77 } // namespace android
     78 
     79 #endif // TESTHELPERS_H
     80