Avoid double call to write/send in test
[metaproxy-moved-to-github.git] / src / test_pipe.cpp
1 /* $Id: test_pipe.cpp,v 1.10 2007-02-21 14:01:27 adam Exp $
2    Copyright (c) 2005-2007, Index Data.
3
4    See the LICENSE file for details
5  */
6
7 #include "config.hpp"
8 #include <errno.h>
9 #include <yazpp/socket-manager.h>
10
11 #if HAVE_UNISTD_H
12 #include <unistd.h>
13 #endif
14
15 #ifdef WIN32
16 #include <winsock.h>
17 #endif
18
19 #if HAVE_SYS_SOCKET_H
20 #include <sys/socket.h>
21 #endif
22
23 #include <iostream>
24 #include <stdexcept>
25
26 #include "util.hpp"
27 #include "pipe.hpp"
28
29 #define BOOST_AUTO_TEST_MAIN
30 #include <boost/test/auto_unit_test.hpp>
31
32 using namespace boost::unit_test;
33 namespace mp = metaproxy_1;
34
35 class Timer : public yazpp_1::ISocketObserver {
36 private:
37     yazpp_1::ISocketObservable *m_obs;
38     mp::Pipe m_pipe;
39     bool m_data;
40     bool m_timeout;
41 public:
42     Timer(yazpp_1::ISocketObservable *obs, int duration);
43     void socketNotify(int event);
44     bool timeout() { return m_timeout; };
45     bool data() { return m_data; };
46 };
47
48
49 Timer::Timer(yazpp_1::ISocketObservable *obs,
50                                  int duration) : 
51     m_obs(obs), m_pipe(9122), m_data(false), m_timeout(false)
52 {
53     obs->addObserver(m_pipe.read_fd(), this);
54     obs->maskObserver(this, yazpp_1::SOCKET_OBSERVE_READ);
55     obs->timeoutObserver(this, duration);
56 #ifdef WIN32
57     int r = send(m_pipe.write_fd(), "", 1, 0);
58 #else
59     int r = write(m_pipe.write_fd(), "", 1);
60 #endif
61     if (r == -1)
62     {
63         std::cout << "Error write: "<< strerror(errno) << std::endl;
64     }
65     BOOST_CHECK_EQUAL(r, 1);
66 }
67
68 void Timer::socketNotify(int event)
69 {
70     if (event & yazpp_1::SOCKET_OBSERVE_READ)
71     {
72         m_data = true;
73         char buf[3];
74 #ifdef WIN32
75         int r = recv(m_pipe.read_fd(), buf, 1, 0);
76 #else
77         int r = read(m_pipe.read_fd(), buf, 1);
78 #endif
79         if (r == -1)
80         {
81             std::cout << "Error read: "<< strerror(errno) << std::endl;
82         }
83     }
84     else if (event && yazpp_1::SOCKET_OBSERVE_TIMEOUT)
85     {
86         m_timeout = true;
87         m_obs->deleteObserver(this);
88     }
89 }
90
91 BOOST_AUTO_UNIT_TEST( test_pipe_1 )
92 {
93     yazpp_1::SocketManager mySocketManager;
94     
95     Timer t(&mySocketManager, 1);
96
97     while (mySocketManager.processEvent() > 0)
98         if (t.timeout())
99             break;
100     BOOST_CHECK(t.timeout());
101     BOOST_CHECK(t.data());
102 }
103
104 /*
105  * Local variables:
106  * c-basic-offset: 4
107  * indent-tabs-mode: nil
108  * c-file-style: "stroustrup"
109  * End:
110  * vim: shiftwidth=4 tabstop=8 expandtab
111  */