libevent: add parallel test with TCP and UNIX domain sockets
[nit.git] / lib / libevent / libevent_test.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 module libevent_test
16
17 import libevent
18 import pthreads
19
20 redef class Sys
21
22 var testing_id: Int is lazy do
23 var id = "NIT_TESTING_ID".environ
24 return if id.is_empty then 0 else id.to_i
25 end
26
27 # Config for test sockets
28 var tcp_addr = "localhost"
29 var tcp_port: Int = 20000 + testing_id
30 var unix_socket_path = "/tmp/libevent_test{testing_id}.sck"
31 end
32
33 class TestConnectionFactory
34 super ConnectionFactory
35
36 redef fun spawn_connection(buf, address)
37 do
38 print "[Server] New client: {address}"
39
40 var conn = new TestConnection(buf)
41 print "[Server] Write: Hi"
42 conn.write "Hi\n"
43 return conn
44 end
45 end
46
47 class TestConnection
48 super Connection
49
50 redef fun read_callback(content)
51 do
52 0.2.sleep # Forcing the server output after the client output
53 printn "[Server] Read: {content}"
54 end
55 end
56
57 class ServerThread
58 super Thread
59
60 redef fun main
61 do
62 var event_base = new NativeEventBase
63 var factory = new TestConnectionFactory(event_base)
64
65 # Bind TCP socket
66 factory.bind_tcp(tcp_addr, tcp_port)
67
68 # Bind UNIX domain socket
69 factory.bind_unix unix_socket_path
70
71 event_base.dispatch
72 event_base.free
73
74 return null
75 end
76 end
77
78 redef fun system(cmd)
79 do
80 if testing_id == 0 then print "[Client] {cmd}"
81 return super(cmd)
82 end
83
84 # First, launch a server in the background
85 var server = new ServerThread
86 server.start
87 0.1.sleep
88
89 # Test what should succeed
90 system "echo 'Hello TCP' | nc -N {tcp_addr} {tcp_port}"
91 system "echo 'Hello UNIX' | nc -NU {unix_socket_path}"
92
93 1.0.sleep
94 exit 0