Remove code duplication in test fixtures
[libt2n] / test / test_fixtures.hxx
CommitLineData
307b5e74
TJ
1/*
2Copyright (C) 2010 by Intra2net AG - Thomas Jarosch
3
4The software in this package is distributed under the GNU General
5Public License version 2 (with a special exception described below).
6
7A copy of GNU General Public License (GPL) is included in this distribution,
8in the file COPYING.GPL.
9
10As a special exception, if other files instantiate templates or use macros
11or inline functions from this file, or you compile this file and link it
12with other works to produce a work based on this file, this file
13does not by itself cause the resulting work to be covered
14by the GNU General Public License.
15
16However the source code for this file must still be made available
17in accordance with section (3) of the GNU General Public License.
18
19This exception does not invalidate any other reasons why a work based
20on this file might be covered by the GNU General Public License.
21*/
22#ifndef __LIBT2N_TEST_FIXTURES
23#define __LIBT2N_TEST_FIXTURES
24
25#include <sys/wait.h>
26#include <sys/types.h>
27#include <signal.h>
28
df94ded3
TJ
29#include <socket_server.hxx>
30#include <string>
31
307b5e74
TJ
32class KillChildOnShutdownFixture
33{
34protected:
35 pid_t child_pid;
36
df94ded3
TJ
37 // this is an evil hack to get access to real_write, don't ever do this in an app!!!
38 class real_write_connection: public libt2n::socket_server_connection
39 {
40 public:
41 void real_write(const std::string& data)
42 { socket_write(data); }
43 };
44
45 //
46 // common functions used by some tests
47 //
48 void send_hello(std::string hello_string, libt2n::socket_server* ss, int conn_id)
49 {
50 libt2n::server_connection *sc=ss->get_connection(conn_id);
51 sc->write(hello_string);
52 }
53
54 void send_raw_socket(std::string hello_string, libt2n::socket_server* ss, int conn_id)
55 {
56 libt2n::socket_server_connection *ssc=dynamic_cast<libt2n::socket_server_connection*>(ss->get_connection(conn_id));
57
58 // this is an evil hack to get access to real_write, don't ever do this in an app!!!
59 real_write_connection *rwc=(real_write_connection*)ssc;
60 rwc->real_write(hello_string);
61 }
62
307b5e74
TJ
63public:
64 KillChildOnShutdownFixture()
65 : child_pid(0)
66 {
67 // Work around Boost.test reporting killed childs as "fatal error".
68 // Can be ignored with boost 1.40.0+, need to check after upgrade
69 signal(SIGCHLD, SIG_IGN);
70 }
71
72 ~KillChildOnShutdownFixture()
73 {
74 // make sure the server-child is dead before the next test runs
75 if (child_pid)
76 {
77 // std::cout << "Killing child with pid: " << child_pid << std::endl;
78 kill(child_pid, SIGKILL);
79
80 int status = 0;
81 waitpid(child_pid, &status, 0);
82 }
83 }
84};
85
86#endif