blob: 305d3d0a6b7df6555f022cc5775541a128f3f937 [file] [log] [blame]
henrike@webrtc.org47be73b2014-05-13 18:00:261/*
2 * Copyright 2004 The WebRTC Project Authors. All rights reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
11#ifndef WEBRTC_BASE_TESTUTILS_H__
12#define WEBRTC_BASE_TESTUTILS_H__
13
14// Utilities for testing rtc infrastructure in unittests
15
16#if defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID)
17#include <X11/Xlib.h>
18#include <X11/extensions/Xrandr.h>
19
20// X defines a few macros that stomp on types that gunit.h uses.
21#undef None
22#undef Bool
23#endif
24
andresp@webrtc.orgf35e2aa2015-02-12 11:54:2625#include <algorithm>
henrike@webrtc.org47be73b2014-05-13 18:00:2626#include <map>
jbauch1286d0e2016-04-26 10:13:2227#include <memory>
henrike@webrtc.org47be73b2014-05-13 18:00:2628#include <vector>
tfarina91638602015-11-11 07:44:3029#include "webrtc/base/arraysize.h"
henrike@webrtc.org47be73b2014-05-13 18:00:2630#include "webrtc/base/asyncsocket.h"
nisse0a6a5602017-01-18 15:20:5531#include "webrtc/base/checks.h"
henrike@webrtc.org47be73b2014-05-13 18:00:2632#include "webrtc/base/gunit.h"
33#include "webrtc/base/nethelpers.h"
henrike@webrtc.org698ee5a2014-05-15 16:33:0434#include "webrtc/base/pathutils.h"
henrike@webrtc.org47be73b2014-05-13 18:00:2635#include "webrtc/base/stream.h"
36#include "webrtc/base/stringencode.h"
37#include "webrtc/base/stringutils.h"
38#include "webrtc/base/thread.h"
39
40namespace testing {
41
42using namespace rtc;
43
44///////////////////////////////////////////////////////////////////////////////
45// StreamSink - Monitor asynchronously signalled events from StreamInterface
46// or AsyncSocket (which should probably be a StreamInterface.
47///////////////////////////////////////////////////////////////////////////////
48
49// Note: Any event that is an error is treaded as SSE_ERROR instead of that
50// event.
51
52enum StreamSinkEvent {
53 SSE_OPEN = SE_OPEN,
54 SSE_READ = SE_READ,
55 SSE_WRITE = SE_WRITE,
56 SSE_CLOSE = SE_CLOSE,
57 SSE_ERROR = 16
58};
59
60class StreamSink : public sigslot::has_slots<> {
61 public:
62 void Monitor(StreamInterface* stream) {
63 stream->SignalEvent.connect(this, &StreamSink::OnEvent);
64 events_.erase(stream);
65 }
66 void Unmonitor(StreamInterface* stream) {
67 stream->SignalEvent.disconnect(this);
68 // In case you forgot to unmonitor a previous object with this address
69 events_.erase(stream);
70 }
71 bool Check(StreamInterface* stream, StreamSinkEvent event, bool reset = true) {
72 return DoCheck(stream, event, reset);
73 }
74 int Events(StreamInterface* stream, bool reset = true) {
75 return DoEvents(stream, reset);
76 }
77
78 void Monitor(AsyncSocket* socket) {
79 socket->SignalConnectEvent.connect(this, &StreamSink::OnConnectEvent);
80 socket->SignalReadEvent.connect(this, &StreamSink::OnReadEvent);
81 socket->SignalWriteEvent.connect(this, &StreamSink::OnWriteEvent);
82 socket->SignalCloseEvent.connect(this, &StreamSink::OnCloseEvent);
83 // In case you forgot to unmonitor a previous object with this address
84 events_.erase(socket);
85 }
86 void Unmonitor(AsyncSocket* socket) {
87 socket->SignalConnectEvent.disconnect(this);
88 socket->SignalReadEvent.disconnect(this);
89 socket->SignalWriteEvent.disconnect(this);
90 socket->SignalCloseEvent.disconnect(this);
91 events_.erase(socket);
92 }
93 bool Check(AsyncSocket* socket, StreamSinkEvent event, bool reset = true) {
94 return DoCheck(socket, event, reset);
95 }
96 int Events(AsyncSocket* socket, bool reset = true) {
97 return DoEvents(socket, reset);
98 }
99
100 private:
101 typedef std::map<void*,int> EventMap;
102
103 void OnEvent(StreamInterface* stream, int events, int error) {
104 if (error) {
105 events = SSE_ERROR;
106 }
107 AddEvents(stream, events);
108 }
109 void OnConnectEvent(AsyncSocket* socket) {
110 AddEvents(socket, SSE_OPEN);
111 }
112 void OnReadEvent(AsyncSocket* socket) {
113 AddEvents(socket, SSE_READ);
114 }
115 void OnWriteEvent(AsyncSocket* socket) {
116 AddEvents(socket, SSE_WRITE);
117 }
118 void OnCloseEvent(AsyncSocket* socket, int error) {
119 AddEvents(socket, (0 == error) ? SSE_CLOSE : SSE_ERROR);
120 }
121
122 void AddEvents(void* obj, int events) {
123 EventMap::iterator it = events_.find(obj);
124 if (events_.end() == it) {
125 events_.insert(EventMap::value_type(obj, events));
126 } else {
127 it->second |= events;
128 }
129 }
130 bool DoCheck(void* obj, StreamSinkEvent event, bool reset) {
131 EventMap::iterator it = events_.find(obj);
132 if ((events_.end() == it) || (0 == (it->second & event))) {
133 return false;
134 }
135 if (reset) {
136 it->second &= ~event;
137 }
138 return true;
139 }
140 int DoEvents(void* obj, bool reset) {
141 EventMap::iterator it = events_.find(obj);
142 if (events_.end() == it)
143 return 0;
144 int events = it->second;
145 if (reset) {
146 it->second = 0;
147 }
148 return events;
149 }
150
151 EventMap events_;
152};
153
154///////////////////////////////////////////////////////////////////////////////
155// StreamSource - Implements stream interface and simulates asynchronous
156// events on the stream, without a network. Also buffers written data.
157///////////////////////////////////////////////////////////////////////////////
158
159class StreamSource : public StreamInterface {
160public:
161 StreamSource() {
162 Clear();
163 }
164
165 void Clear() {
166 readable_data_.clear();
167 written_data_.clear();
168 state_ = SS_CLOSED;
169 read_block_ = 0;
170 write_block_ = SIZE_UNKNOWN;
171 }
172 void QueueString(const char* data) {
173 QueueData(data, strlen(data));
174 }
175 void QueueStringF(const char* format, ...) {
176 va_list args;
177 va_start(args, format);
178 char buffer[1024];
179 size_t len = vsprintfn(buffer, sizeof(buffer), format, args);
nisse0a6a5602017-01-18 15:20:55180 RTC_CHECK(len < sizeof(buffer) - 1);
henrike@webrtc.org47be73b2014-05-13 18:00:26181 va_end(args);
182 QueueData(buffer, len);
183 }
184 void QueueData(const char* data, size_t len) {
185 readable_data_.insert(readable_data_.end(), data, data + len);
186 if ((SS_OPEN == state_) && (readable_data_.size() == len)) {
187 SignalEvent(this, SE_READ, 0);
188 }
189 }
190 std::string ReadData() {
191 std::string data;
192 // avoid accessing written_data_[0] if it is undefined
193 if (written_data_.size() > 0) {
194 data.insert(0, &written_data_[0], written_data_.size());
195 }
196 written_data_.clear();
197 return data;
198 }
199 void SetState(StreamState state) {
200 int events = 0;
201 if ((SS_OPENING == state_) && (SS_OPEN == state)) {
202 events |= SE_OPEN;
203 if (!readable_data_.empty()) {
204 events |= SE_READ;
205 }
206 } else if ((SS_CLOSED != state_) && (SS_CLOSED == state)) {
207 events |= SE_CLOSE;
208 }
209 state_ = state;
210 if (events) {
211 SignalEvent(this, events, 0);
212 }
213 }
214 // Will cause Read to block when there are pos bytes in the read queue.
215 void SetReadBlock(size_t pos) { read_block_ = pos; }
216 // Will cause Write to block when there are pos bytes in the write queue.
217 void SetWriteBlock(size_t pos) { write_block_ = pos; }
218
219 virtual StreamState GetState() const { return state_; }
220 virtual StreamResult Read(void* buffer, size_t buffer_len,
221 size_t* read, int* error) {
222 if (SS_CLOSED == state_) {
223 if (error) *error = -1;
224 return SR_ERROR;
225 }
226 if ((SS_OPENING == state_) || (readable_data_.size() <= read_block_)) {
227 return SR_BLOCK;
228 }
andresp@webrtc.orgf35e2aa2015-02-12 11:54:26229 size_t count = std::min(buffer_len, readable_data_.size() - read_block_);
henrike@webrtc.org47be73b2014-05-13 18:00:26230 memcpy(buffer, &readable_data_[0], count);
231 size_t new_size = readable_data_.size() - count;
232 // Avoid undefined access beyond the last element of the vector.
233 // This only happens when new_size is 0.
234 if (count < readable_data_.size()) {
235 memmove(&readable_data_[0], &readable_data_[count], new_size);
236 }
237 readable_data_.resize(new_size);
238 if (read) *read = count;
239 return SR_SUCCESS;
240 }
241 virtual StreamResult Write(const void* data, size_t data_len,
242 size_t* written, int* error) {
243 if (SS_CLOSED == state_) {
244 if (error) *error = -1;
245 return SR_ERROR;
246 }
247 if (SS_OPENING == state_) {
248 return SR_BLOCK;
249 }
250 if (SIZE_UNKNOWN != write_block_) {
251 if (written_data_.size() >= write_block_) {
252 return SR_BLOCK;
253 }
254 if (data_len > (write_block_ - written_data_.size())) {
255 data_len = write_block_ - written_data_.size();
256 }
257 }
258 if (written) *written = data_len;
259 const char* cdata = static_cast<const char*>(data);
260 written_data_.insert(written_data_.end(), cdata, cdata + data_len);
261 return SR_SUCCESS;
262 }
263 virtual void Close() { state_ = SS_CLOSED; }
264
265private:
266 typedef std::vector<char> Buffer;
267 Buffer readable_data_, written_data_;
268 StreamState state_;
269 size_t read_block_, write_block_;
270};
271
272///////////////////////////////////////////////////////////////////////////////
273// SocketTestClient
274// Creates a simulated client for testing. Works on real and virtual networks.
275///////////////////////////////////////////////////////////////////////////////
276
277class SocketTestClient : public sigslot::has_slots<> {
278public:
deadbeef16378412017-02-27 22:06:41279 SocketTestClient() { Init(nullptr, AF_INET); }
280 SocketTestClient(AsyncSocket* socket) {
281 Init(socket, socket->GetLocalAddress().family());
henrike@webrtc.org47be73b2014-05-13 18:00:26282 }
283 SocketTestClient(const SocketAddress& address) {
deadbeef16378412017-02-27 22:06:41284 Init(nullptr, address.family());
henrike@webrtc.org47be73b2014-05-13 18:00:26285 socket_->Connect(address);
286 }
287
288 AsyncSocket* socket() { return socket_.get(); }
289
290 void QueueString(const char* data) {
291 QueueData(data, strlen(data));
292 }
293 void QueueStringF(const char* format, ...) {
294 va_list args;
295 va_start(args, format);
296 char buffer[1024];
297 size_t len = vsprintfn(buffer, sizeof(buffer), format, args);
nisse0a6a5602017-01-18 15:20:55298 RTC_CHECK(len < sizeof(buffer) - 1);
henrike@webrtc.org47be73b2014-05-13 18:00:26299 va_end(args);
300 QueueData(buffer, len);
301 }
302 void QueueData(const char* data, size_t len) {
303 send_buffer_.insert(send_buffer_.end(), data, data + len);
304 if (Socket::CS_CONNECTED == socket_->GetState()) {
305 Flush();
306 }
307 }
308 std::string ReadData() {
309 std::string data(&recv_buffer_[0], recv_buffer_.size());
310 recv_buffer_.clear();
311 return data;
312 }
313
314 bool IsConnected() const {
315 return (Socket::CS_CONNECTED == socket_->GetState());
316 }
317 bool IsClosed() const {
318 return (Socket::CS_CLOSED == socket_->GetState());
319 }
320
321private:
322 typedef std::vector<char> Buffer;
323
324 void Init(AsyncSocket* socket, int family) {
325 if (!socket) {
326 socket = Thread::Current()->socketserver()
327 ->CreateAsyncSocket(family, SOCK_STREAM);
328 }
329 socket_.reset(socket);
330 socket_->SignalConnectEvent.connect(this,
331 &SocketTestClient::OnConnectEvent);
332 socket_->SignalReadEvent.connect(this, &SocketTestClient::OnReadEvent);
333 socket_->SignalWriteEvent.connect(this, &SocketTestClient::OnWriteEvent);
334 socket_->SignalCloseEvent.connect(this, &SocketTestClient::OnCloseEvent);
335 }
336
337 void Flush() {
338 size_t sent = 0;
339 while (sent < send_buffer_.size()) {
340 int result = socket_->Send(&send_buffer_[sent],
341 send_buffer_.size() - sent);
342 if (result > 0) {
343 sent += result;
344 } else {
345 break;
346 }
347 }
348 size_t new_size = send_buffer_.size() - sent;
349 memmove(&send_buffer_[0], &send_buffer_[sent], new_size);
350 send_buffer_.resize(new_size);
351 }
352
353 void OnConnectEvent(AsyncSocket* socket) {
354 if (!send_buffer_.empty()) {
355 Flush();
356 }
357 }
358 void OnReadEvent(AsyncSocket* socket) {
359 char data[64 * 1024];
Stefan Holmer06ceeec2016-05-23 16:19:26360 int result = socket_->Recv(data, arraysize(data), nullptr);
henrike@webrtc.org47be73b2014-05-13 18:00:26361 if (result > 0) {
362 recv_buffer_.insert(recv_buffer_.end(), data, data + result);
363 }
364 }
365 void OnWriteEvent(AsyncSocket* socket) {
366 if (!send_buffer_.empty()) {
367 Flush();
368 }
369 }
370 void OnCloseEvent(AsyncSocket* socket, int error) {
371 }
372
jbauch1286d0e2016-04-26 10:13:22373 std::unique_ptr<AsyncSocket> socket_;
henrike@webrtc.org47be73b2014-05-13 18:00:26374 Buffer send_buffer_, recv_buffer_;
375};
376
377///////////////////////////////////////////////////////////////////////////////
378// SocketTestServer
379// Creates a simulated server for testing. Works on real and virtual networks.
380///////////////////////////////////////////////////////////////////////////////
381
382class SocketTestServer : public sigslot::has_slots<> {
383 public:
384 SocketTestServer(const SocketAddress& address)
385 : socket_(Thread::Current()->socketserver()
386 ->CreateAsyncSocket(address.family(), SOCK_STREAM))
387 {
388 socket_->SignalReadEvent.connect(this, &SocketTestServer::OnReadEvent);
389 socket_->Bind(address);
390 socket_->Listen(5);
391 }
392 virtual ~SocketTestServer() {
393 clear();
394 }
395
396 size_t size() const { return clients_.size(); }
397 SocketTestClient* client(size_t index) const { return clients_[index]; }
398 SocketTestClient* operator[](size_t index) const { return client(index); }
399
400 void clear() {
401 for (size_t i=0; i<clients_.size(); ++i) {
402 delete clients_[i];
403 }
404 clients_.clear();
405 }
406
407 private:
408 void OnReadEvent(AsyncSocket* socket) {
deadbeef16378412017-02-27 22:06:41409 AsyncSocket* accepted = static_cast<AsyncSocket*>(socket_->Accept(nullptr));
henrike@webrtc.org47be73b2014-05-13 18:00:26410 if (!accepted)
411 return;
412 clients_.push_back(new SocketTestClient(accepted));
413 }
414
jbauch1286d0e2016-04-26 10:13:22415 std::unique_ptr<AsyncSocket> socket_;
henrike@webrtc.org47be73b2014-05-13 18:00:26416 std::vector<SocketTestClient*> clients_;
417};
418
419///////////////////////////////////////////////////////////////////////////////
henrike@webrtc.org47be73b2014-05-13 18:00:26420// Unittest predicates which are similar to STREQ, but for raw memory
421///////////////////////////////////////////////////////////////////////////////
422
423inline AssertionResult CmpHelperMemEq(const char* expected_expression,
424 const char* expected_length_expression,
425 const char* actual_expression,
426 const char* actual_length_expression,
427 const void* expected,
428 size_t expected_length,
429 const void* actual,
430 size_t actual_length)
431{
432 if ((expected_length == actual_length)
433 && (0 == memcmp(expected, actual, expected_length))) {
434 return AssertionSuccess();
435 }
436
437 Message msg;
438 msg << "Value of: " << actual_expression
439 << " [" << actual_length_expression << "]";
440 if (true) { //!actual_value.Equals(actual_expression)) {
441 size_t buffer_size = actual_length * 2 + 1;
442 char* buffer = STACK_ARRAY(char, buffer_size);
443 hex_encode(buffer, buffer_size,
444 reinterpret_cast<const char*>(actual), actual_length);
445 msg << "\n Actual: " << buffer << " [" << actual_length << "]";
446 }
447
448 msg << "\nExpected: " << expected_expression
449 << " [" << expected_length_expression << "]";
450 if (true) { //!expected_value.Equals(expected_expression)) {
451 size_t buffer_size = expected_length * 2 + 1;
452 char* buffer = STACK_ARRAY(char, buffer_size);
453 hex_encode(buffer, buffer_size,
454 reinterpret_cast<const char*>(expected), expected_length);
455 msg << "\nWhich is: " << buffer << " [" << expected_length << "]";
456 }
457
458 return AssertionFailure(msg);
459}
460
henrike@webrtc.org47be73b2014-05-13 18:00:26461#define EXPECT_MEMEQ(expected, expected_length, actual, actual_length) \
462 EXPECT_PRED_FORMAT4(::testing::CmpHelperMemEq, expected, expected_length, \
463 actual, actual_length)
464
465#define ASSERT_MEMEQ(expected, expected_length, actual, actual_length) \
466 ASSERT_PRED_FORMAT4(::testing::CmpHelperMemEq, expected, expected_length, \
467 actual, actual_length)
468
henrike@webrtc.org47be73b2014-05-13 18:00:26469///////////////////////////////////////////////////////////////////////////////
470// Helpers for initializing constant memory with integers in a particular byte
471// order
472///////////////////////////////////////////////////////////////////////////////
473
Peter Boström07e22e62015-10-07 10:23:21474#define BYTE_CAST(x) static_cast<uint8_t>((x)&0xFF)
henrike@webrtc.org47be73b2014-05-13 18:00:26475
476// Declare a N-bit integer as a little-endian sequence of bytes
Peter Boström07e22e62015-10-07 10:23:21477#define LE16(x) BYTE_CAST(((uint16_t)x) >> 0), BYTE_CAST(((uint16_t)x) >> 8)
henrike@webrtc.org47be73b2014-05-13 18:00:26478
Peter Boström07e22e62015-10-07 10:23:21479#define LE32(x) \
480 BYTE_CAST(((uint32_t)x) >> 0), BYTE_CAST(((uint32_t)x) >> 8), \
481 BYTE_CAST(((uint32_t)x) >> 16), BYTE_CAST(((uint32_t)x) >> 24)
henrike@webrtc.org47be73b2014-05-13 18:00:26482
Peter Boström07e22e62015-10-07 10:23:21483#define LE64(x) \
484 BYTE_CAST(((uint64_t)x) >> 0), BYTE_CAST(((uint64_t)x) >> 8), \
485 BYTE_CAST(((uint64_t)x) >> 16), BYTE_CAST(((uint64_t)x) >> 24), \
486 BYTE_CAST(((uint64_t)x) >> 32), BYTE_CAST(((uint64_t)x) >> 40), \
487 BYTE_CAST(((uint64_t)x) >> 48), BYTE_CAST(((uint64_t)x) >> 56)
henrike@webrtc.org47be73b2014-05-13 18:00:26488
489// Declare a N-bit integer as a big-endian (Internet) sequence of bytes
Peter Boström07e22e62015-10-07 10:23:21490#define BE16(x) BYTE_CAST(((uint16_t)x) >> 8), BYTE_CAST(((uint16_t)x) >> 0)
henrike@webrtc.org47be73b2014-05-13 18:00:26491
Peter Boström07e22e62015-10-07 10:23:21492#define BE32(x) \
493 BYTE_CAST(((uint32_t)x) >> 24), BYTE_CAST(((uint32_t)x) >> 16), \
494 BYTE_CAST(((uint32_t)x) >> 8), BYTE_CAST(((uint32_t)x) >> 0)
henrike@webrtc.org47be73b2014-05-13 18:00:26495
Peter Boström07e22e62015-10-07 10:23:21496#define BE64(x) \
497 BYTE_CAST(((uint64_t)x) >> 56), BYTE_CAST(((uint64_t)x) >> 48), \
498 BYTE_CAST(((uint64_t)x) >> 40), BYTE_CAST(((uint64_t)x) >> 32), \
499 BYTE_CAST(((uint64_t)x) >> 24), BYTE_CAST(((uint64_t)x) >> 16), \
500 BYTE_CAST(((uint64_t)x) >> 8), BYTE_CAST(((uint64_t)x) >> 0)
henrike@webrtc.org47be73b2014-05-13 18:00:26501
502// Declare a N-bit integer as a this-endian (local machine) sequence of bytes
503#ifndef BIG_ENDIAN
504#define BIG_ENDIAN 1
505#endif // BIG_ENDIAN
506
507#if BIG_ENDIAN
508#define TE16 BE16
509#define TE32 BE32
510#define TE64 BE64
511#else // !BIG_ENDIAN
512#define TE16 LE16
513#define TE32 LE32
514#define TE64 LE64
515#endif // !BIG_ENDIAN
516
517///////////////////////////////////////////////////////////////////////////////
518
519// Helpers for determining if X/screencasting is available (on linux).
520
521#define MAYBE_SKIP_SCREENCAST_TEST() \
522 if (!testing::IsScreencastingAvailable()) { \
523 LOG(LS_WARNING) << "Skipping test, since it doesn't have the requisite " \
524 << "X environment for screen capture."; \
525 return; \
526 } \
527
528#if defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID)
529struct XDisplay {
deadbeef16378412017-02-27 22:06:41530 XDisplay() : display_(XOpenDisplay(nullptr)) {}
henrike@webrtc.org47be73b2014-05-13 18:00:26531 ~XDisplay() { if (display_) XCloseDisplay(display_); }
deadbeef16378412017-02-27 22:06:41532 bool IsValid() const { return display_ != nullptr; }
henrike@webrtc.org47be73b2014-05-13 18:00:26533 operator Display*() { return display_; }
534 private:
535 Display* display_;
536};
537#endif
538
539// Returns true if screencasting is available. When false, anything that uses
540// screencasting features may fail.
541inline bool IsScreencastingAvailable() {
542#if defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID)
543 XDisplay display;
544 if (!display.IsValid()) {
545 LOG(LS_WARNING) << "No X Display available.";
546 return false;
547 }
548 int ignored_int, major_version, minor_version;
549 if (!XRRQueryExtension(display, &ignored_int, &ignored_int) ||
550 !XRRQueryVersion(display, &major_version, &minor_version) ||
551 major_version < 1 ||
552 (major_version < 2 && minor_version < 3)) {
553 LOG(LS_WARNING) << "XRandr version: " << major_version << "."
554 << minor_version;
555 LOG(LS_WARNING) << "XRandr is not supported or is too old (pre 1.3).";
556 return false;
557 }
558#endif
559 return true;
560}
561} // namespace testing
562
563#endif // WEBRTC_BASE_TESTUTILS_H__