[lcm] 4 new revisions pushed by ashu...@gmail.com on 2014-11-16 22:10 GMT

25 views
Skip to first unread message

l...@googlecode.com

unread,
Nov 16, 2014, 5:11:13 PM11/16/14
to lcm...@googlegroups.com
master moved from d45b3417719b to b8e44c66189d

4 new revisions:

Revision: cdd0c24dc6d1
Author: Albert Huang <ash...@gmail.com>
Date: Mon Nov 10 02:01:46 2014 UTC
Log: testing cleanup....
https://code.google.com/p/lcm/source/detail?r=cdd0c24dc6d1

Revision: 0c3c0705011f
Author: Albert Huang <ash...@gmail.com>
Date: Fri Nov 14 07:03:42 2014 UTC
Log: Convert unit tests to xml output...
https://code.google.com/p/lcm/source/detail?r=0c3c0705011f

Revision: dd4397fa2000
Author: Albert Huang <ash...@gmail.com>
Date: Sun Nov 16 21:14:57 2014 UTC
Log: Start on java LcmTestClient
https://code.google.com/p/lcm/source/detail?r=dd4397fa2000

Revision: b8e44c66189d
Author: Albert Huang <ash...@gmail.com>
Date: Sun Nov 16 21:58:55 2014 UTC
Log: add junit, hamcrest sources...
https://code.google.com/p/lcm/source/detail?r=b8e44c66189d

==============================================================================
Revision: cdd0c24dc6d1
Author: Albert Huang <ash...@gmail.com>
Date: Mon Nov 10 02:01:46 2014 UTC
Log: testing cleanup.
- info() macro automatically insert '\n' at end
- use lcm_handle_timeout(), lcm::LCM::handleTimeout()
- convert cpp/client to use gtest
- convert c/client to use gtest
- convert python/client.py to use unittest module
- remove unnecessary linker flags from compiling cpp/{common,client}.o
- simplify run_tests.py to always use c/server

https://code.google.com/p/lcm/source/detail?r=cdd0c24dc6d1

Added:
/test/c/client.cpp
Deleted:
/test/c/client.c
Modified:
/test/c/Makefile
/test/c/common.c
/test/c/common.h
/test/c/server.c
/test/cpp/Makefile
/test/cpp/client.cpp
/test/cpp/common.cpp
/test/cpp/common.hpp
/test/python/client.py
/test/run_tests.py

=======================================
--- /dev/null
+++ /test/c/client.cpp Mon Nov 10 02:01:46 2014 UTC
@@ -0,0 +1,143 @@
+#include <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+#include <time.h>
+#include <gtest/gtest.h>
+
+#include <lcm/lcm.h>
+
+#include "common.h"
+
+#define info(...) do { printf("c_client: "); printf(__VA_ARGS__);
printf("\n"); } while(0)
+
+static lcm_t* g_lcm = NULL;
+
+// ====================================== node_t test
+#define MAKE_CLIENT_TEST(type, num_iters) \
+\
+static int g_##type##_response_count = 0; \
+\
+static void \
+type##_handler(const lcm_recv_buf_t* rbuf, const char* channel, \
+ const type* msg, void* user) \
+{ \
+ if(!check_##type(msg, g_##type##_response_count + 1)) { \
+ return; \
+ } \
+ g_##type##_response_count++; \
+} \
+\
+static int \
+do_##type##_test(void) \
+{ \
+ type msg; \
+ type##_subscription_t* subs = type##_subscribe(g_lcm, \
+ "test_" #type "_reply", type##_handler, NULL); \
+ g_##type##_response_count = 0; \
+ int result = 1; \
+ int iter; \
+ for(iter=0; iter<num_iters && result; iter++) { \
+ fill_##type(iter, &msg); \
+ type##_publish(g_lcm, "test_" #type, &msg); \
+ if(!lcm_handle_timeout(g_lcm, 500)) { \
+ info(#type " test: Timeout waiting for reply"); \
+ result = 0; \
+ } else if(g_##type##_response_count != iter+1) { \
+ info(#type " test: failed on iteration %d", iter); \
+ result = 0; \
+ } \
+ clear_##type(&msg); \
+ } \
+ type##_unsubscribe(g_lcm, subs); \
+ return result; \
+}
+
+MAKE_CLIENT_TEST(lcmtest2_cross_package_t, 100);
+MAKE_CLIENT_TEST(lcmtest_multidim_array_t, 5);
+MAKE_CLIENT_TEST(lcmtest_node_t, 7);
+MAKE_CLIENT_TEST(lcmtest_primitives_list_t, 100);
+MAKE_CLIENT_TEST(lcmtest_primitives_t, 1000);
+
+// ================================= echo test
+int g_echo_response_count = 0;
+int g_echo_msg_len = 0;
+uint8_t* g_echo_data = NULL;
+
+static void
+echo_handler(const lcm_recv_buf_t *rbuf, const char * channel, void * user)
+{
+ if(rbuf->data_size != g_echo_msg_len)
+ return;
+ if(memcmp(rbuf->data, g_echo_data, rbuf->data_size))
+ return;
+ g_echo_response_count++;
+}
+
+TEST(LCM_C, EchoTest)
+{
+ srand(time(NULL));
+ g_lcm = lcm_create(NULL);
+ ASSERT_TRUE(g_lcm != NULL);
+
+ int maxlen = 10000;
+ int minlen = 10;
+ g_echo_data = (uint8_t*) malloc(maxlen);
+ lcm_subscription_t* subs = lcm_subscribe(g_lcm, "TEST_ECHO_REPLY",
echo_handler, NULL);
+ g_echo_response_count = 0;
+
+ int iter;
+ for(iter=0; iter<100; iter++)
+ {
+ g_echo_msg_len = rand() % (maxlen - minlen) + minlen;
+ int i;
+ for(i=0; i<g_echo_msg_len; i++)
+ g_echo_data[i] = rand() % 256;
+
+ lcm_publish(g_lcm, "TEST_ECHO", g_echo_data, g_echo_msg_len);
+
+ ASSERT_GT(lcm_handle_timeout(g_lcm, 500), 0);
+ ASSERT_EQ(g_echo_response_count, iter+1);
+
+ if(g_echo_response_count != iter+1) {
+ info("echo test failed to receive response on iteration %d",
iter);
+ lcm_unsubscribe(g_lcm, subs);
+ free(g_echo_data);
+ return;
+ }
+ }
+
+ lcm_unsubscribe(g_lcm, subs);
+ free(g_echo_data);
+}
+
+// Typed tests
+TEST(LCM_C, primitives_t)
+{
+ ASSERT_TRUE(g_lcm != NULL);
+ EXPECT_EQ(1, do_lcmtest_primitives_t_test());
+}
+
+TEST(LCM_C, primitives_list_t)
+{
+ ASSERT_TRUE(g_lcm != NULL);
+ EXPECT_EQ(1, do_lcmtest_primitives_list_t_test());
+}
+
+TEST(LCM_C, node_t)
+{
+ ASSERT_TRUE(g_lcm != NULL);
+ EXPECT_EQ(1, do_lcmtest_node_t_test());
+}
+
+TEST(LCM_C, multidim_array_t)
+{
+ ASSERT_TRUE(g_lcm != NULL);
+ EXPECT_EQ(1, do_lcmtest_multidim_array_t_test());
+}
+
+TEST(LCM_C, cross_package)
+{
+ ASSERT_TRUE(g_lcm != NULL);
+ EXPECT_EQ(1, do_lcmtest2_cross_package_t_test());
+ lcm_destroy(g_lcm);
+}
=======================================
--- /test/c/client.c Fri Jan 17 03:04:05 2014 UTC
+++ /dev/null
@@ -1,151 +0,0 @@
-#include <stdio.h>
-#include <string.h>
-#include <stdlib.h>
-#include <time.h>
-
-#include <lcm/lcm.h>
-
-#include "common.h"
-
-#define info(...) do { printf("c_client: "); printf(__VA_ARGS__); }
while(0)
-
-static lcm_t* g_lcm = NULL;
-
-// ====================================== node_t test
-#define MAKE_CLIENT_TEST(type, num_iters) \
-\
-static int g_##type##_response_count = 0; \
-\
-static void \
-type##_handler(const lcm_recv_buf_t* rbuf, const char* channel, \
- const type* msg, void* user) \
-{ \
- if(!check_##type(msg, g_##type##_response_count + 1)) { \
- return; \
- } \
- g_##type##_response_count++; \
-} \
-\
-static int \
-do_##type##_test(void) \
-{ \
- type msg; \
- type##_subscription_t* subs = type##_subscribe(g_lcm, \
- "test_" #type "_reply", type##_handler, NULL); \
- g_##type##_response_count = 0; \
- int result = 1; \
- int iter; \
- for(iter=0; iter<num_iters && result; iter++) { \
- fill_##type(iter, &msg); \
- type##_publish(g_lcm, "test_" #type, &msg); \
- if(!_lcm_handle_timeout(g_lcm, 500)) { \
- info(#type " test: Timeout waiting for reply\n"); \
- result = 0; \
- } else if(g_##type##_response_count != iter+1) { \
- info(#type " test: failed on iteration %d\n", iter); \
- result = 0; \
- } \
- clear_##type(&msg); \
- } \
- type##_unsubscribe(g_lcm, subs); \
- if(result) { \
- info("%-32s : PASSED\n", #type); \
- } else { \
- info("%-32s : FAILED\n", #type); \
- } \
- return result; \
-}
-
-MAKE_CLIENT_TEST(lcmtest2_cross_package_t, 100);
-MAKE_CLIENT_TEST(lcmtest_multidim_array_t, 5);
-MAKE_CLIENT_TEST(lcmtest_node_t, 7);
-MAKE_CLIENT_TEST(lcmtest_primitives_list_t, 100);
-MAKE_CLIENT_TEST(lcmtest_primitives_t, 1000);
-
-// ================================= echo test
-int g_echo_response_count = 0;
-int g_echo_msg_len = 0;
-uint8_t* g_echo_data = NULL;
-
-static void
-echo_handler(const lcm_recv_buf_t *rbuf, const char * channel, void * user)
-{
- if(rbuf->data_size != g_echo_msg_len)
- return;
- if(memcmp(rbuf->data, g_echo_data, rbuf->data_size))
- return;
- g_echo_response_count++;
-}
-
-static int
-do_echo_test(void)
-{
- int maxlen = 10000;
- int minlen = 10;
- g_echo_data = malloc(maxlen);
- lcm_subscription_t* subs = lcm_subscribe(g_lcm, "TEST_ECHO_REPLY",
echo_handler, NULL);
- g_echo_response_count = 0;
-
- int iter;
- for(iter=0; iter<100; iter++)
- {
- g_echo_msg_len = rand() % (maxlen - minlen) + minlen;
- int i;
- for(i=0; i<g_echo_msg_len; i++)
- g_echo_data[i] = rand() % 256;
-
- lcm_publish(g_lcm, "TEST_ECHO", g_echo_data, g_echo_msg_len);
-
- if(!_lcm_handle_timeout(g_lcm, 500) || (g_echo_response_count !=
iter+1))
- {
- info("echo test failed to receive response on iteration %d\n",
iter);
- free(g_echo_data);
- return 0;
- }
- }
-
- info("%-32s : PASSED\n", "echo test");
- lcm_unsubscribe(g_lcm, subs);
- free(g_echo_data);
- return 1;
-}
-
-// ========================== main
-int
-main(int argc, char ** argv)
-{
- srand(time(NULL));
-
- g_lcm = lcm_create(NULL);
- if(!g_lcm)
- {
- info("Unable to initialize LCM\n");
- return 1;
- }
-
- if(!do_echo_test())
- goto failed;
-
- if(!do_lcmtest_primitives_t_test())
- goto failed;
-
- if(!do_lcmtest_primitives_list_t_test())
- goto failed;
-
- if(!do_lcmtest_node_t_test())
- goto failed;
-
- if(!do_lcmtest_multidim_array_t_test())
- goto failed;
-
- if(!do_lcmtest2_cross_package_t_test())
- goto failed;
-
- info("All tests passed.\n");
- lcm_destroy(g_lcm);
- return 0;
-failed:
- info("failed\n");
- lcm_destroy(g_lcm);
- return 1;
-}
=======================================
--- /test/c/Makefile Thu Nov 6 02:34:46 2014 UTC
+++ /test/c/Makefile Mon Nov 10 02:01:46 2014 UTC
@@ -3,7 +3,8 @@
LCM_GEN=../../lcmgen/lcm-gen

# Use pkg-config to lookup the proper compiler and linker flags for LCM
-CFLAGS=`pkg-config --cflags lcm` -std=c99 -g
+CFLAGS=`pkg-config --cflags lcm` -I../gtest/include -std=c99 -g
+CXXFLAGS=`pkg-config --cflags lcm` -I../gtest/include -g
LDFLAGS=`pkg-config --libs lcm`
GTEST_LIBS=../gtest/libgtest.a ../gtest/libgtest_main.a

@@ -22,13 +23,13 @@
$(CC) -o $@ $^ $(LDFLAGS)

client: client.o common.o $(types_obj)
- $(CC) -o $@ $^ $(LDFLAGS)
+ $(CXX) -o $@ $^ $(LDFLAGS) $(GTEST_LIBS)

common.o: common.c $(types_src)
$(CC) $(CFLAGS) -c $<

-client.o: client.c $(types_src)
- $(CC) $(CFLAGS) -c $<
+client.o: client.cpp $(types_src)
+ $(CXX) $(CXXFLAGS) -c $<

server.o: server.c $(types_src)
$(CC) $(CFLAGS) -c $<
@@ -37,13 +38,13 @@
$(CXX) -o $@ $^ $(LDFLAGS) $(GTEST_LIBS)

eventlog_test.o: eventlog_test.cpp
- $(CXX) `pkg-config --cflags lcm` -g -I../gtest/include -c $<
+ $(CXX) $(CXXFLAGS) -c $<

memq_test: memq_test.o
$(CXX) -o $@ $^ $(LDFLAGS) $(GTEST_LIBS)

memq_test.o: memq_test.cpp $(types_src)
- $(CXX) `pkg-config --cflags lcm` -g -I../gtest/include -c $<
+ $(CXX) $(CXXFLAGS) -c $<

lcmtest_%.o: lcmtest_%.c lcmtest_%.h
$(CC) $(CFLAGS) -c $<
=======================================
--- /test/c/common.c Fri Jan 17 03:04:05 2014 UTC
+++ /test/c/common.c Mon Nov 10 02:01:46 2014 UTC
@@ -17,30 +17,6 @@
info("Expected " #field " to be: " fmt ", got " fmt " instead\n",
(expected), (field)); \
return 0; \
}
-
-int
-_lcm_handle_timeout(lcm_t* lcm, int ms)
-{
- // setup the LCM file descriptor for waiting.
- SOCKET lcm_fd = lcm_get_fileno(lcm);
- fd_set fds;
- FD_ZERO(&fds);
- FD_SET(lcm_fd, &fds);
-
- // wait a limited amount of time for an incoming message
- struct timeval timeout = {
- ms / 1000, // seconds
- (ms % 1000) * 1000 // microseconds
- };
- int status = select(lcm_fd + 1, &fds, 0, 0, &timeout);
- if(status > 0 && FD_ISSET(lcm_fd, &fds)) {
- lcm_handle(lcm);
- return 1;
- }
-
- // no messages
- return 0;
-}

char*
_strdup(const char* src)
=======================================
--- /test/c/common.h Wed Jan 15 01:53:28 2014 UTC
+++ /test/c/common.h Mon Nov 10 02:01:46 2014 UTC
@@ -1,6 +1,10 @@
#ifndef __common_h__
#define __common_h__

+#ifdef __cplusplus
+extern "C" {
+#endif
+
#include "lcmtest_primitives_t.h"
#include "lcmtest_primitives_list_t.h"
#include "lcmtest_node_t.h"
@@ -8,7 +12,6 @@
#include "lcmtest2_cross_package_t.h"

char* _strdup(const char* src);
-int _lcm_handle_timeout(lcm_t* lcm, int ms);

int check_lcmtest_multidim_array_t(const lcmtest_multidim_array_t* msg,
int expected);
void fill_lcmtest_multidim_array_t(int num_children,
lcmtest_multidim_array_t* result);
@@ -34,4 +37,8 @@
void fill_lcmtest2_another_type_t(int n, lcmtest2_another_type_t* msg);
void clear_lcmtest2_another_type_t(lcmtest2_another_type_t* msg);

+#ifdef __cplusplus
+}
+#endif
+
#endif
=======================================
--- /test/c/server.c Fri Jan 17 03:04:05 2014 UTC
+++ /test/c/server.c Mon Nov 10 02:01:46 2014 UTC
@@ -11,14 +11,15 @@

#include "common.h"

+#define info(...) do { fprintf(stderr, "c_server: "); \
+ fprintf(stderr, __VA_ARGS__); fprintf(stderr, "\n"); } while(0)
+
static lcm_t* g_lcm = NULL;

-// overall test status
+// Overall test status
static int g_test_complete = 0;
static int g_test_passed = 0;

-#define info(...) do { fprintf(stderr, "c_server: "); fprintf(stderr,
__VA_ARGS__); } while(0)
-
static void
all_tests_passed(void)
{
@@ -26,7 +27,7 @@
g_test_complete = 1;
}

-// ========================== Generic macro for declaring a test
+// Generic macro for declaring a test
#define MAKE_TEST(type, num_iters, success_func) \
\
static int g_##type##_count = 0; \
@@ -48,7 +49,6 @@
g_##type##_count++; \
if(g_##type##_count == num_iters) { \
type##_unsubscribe(g_lcm, g_##type##_subscription); \
- info("%-32s : PASSED\n", #type); \
success_func(); \
} \
} \
@@ -73,7 +73,6 @@
static void
end_echo_test()
{
- info("%-32s : PASSED\n", "echo test");
lcm_unsubscribe(g_lcm, g_echo_subscription);
begin_lcmtest_primitives_t_test();
}
@@ -93,7 +92,8 @@
static void
begin_echo_test()
{
- g_echo_subscription = lcm_subscribe(g_lcm, "TEST_ECHO", &echo_handler,
NULL);
+ g_echo_subscription = lcm_subscribe(g_lcm, "TEST_ECHO",
+ &echo_handler, NULL);
}

// ============================
@@ -106,23 +106,11 @@

begin_echo_test();

- if(_lcm_handle_timeout(g_lcm, 10000)) {
- while(!g_test_complete)
- {
- if(!_lcm_handle_timeout(g_lcm, 500)) {
- info("Timed out waiting for client message\n");
- g_test_complete = 1;
- break;
- }
- }
- } else {
- info("Timed out waiting for first client message\n");
+ while (!g_test_complete && (lcm_handle(g_lcm) == 0)) {
}

lcm_destroy(g_lcm);
- if(g_test_passed)
- info("All tests passed.\n");
- else
- info("Test failed.\n");
+ if(!g_test_passed)
+ info("Test failed.");
return !g_test_passed;
}
=======================================
--- /test/cpp/Makefile Thu Nov 6 02:34:46 2014 UTC
+++ /test/cpp/Makefile Mon Nov 10 02:01:46 2014 UTC
@@ -3,7 +3,7 @@
LCM_GEN=../../lcmgen/lcm-gen

# Use pkg-config to lookup the proper compiler and linker flags for LCM
-CFLAGS=`pkg-config --cflags lcm` -g -I .
+CFLAGS=`pkg-config --cflags lcm` -g -I . -I../gtest/include
LDFLAGS=`pkg-config --libs lcm`
GTEST_LIBS=../gtest/libgtest.a ../gtest/libgtest_main.a

@@ -15,19 +15,19 @@
memq_test

common.o: common.cpp $(types_src)
- $(CC) $(CFLAGS) $(LDFLAGS) -c $<
+ $(CC) $(CFLAGS) -c $<

client.o: client.cpp $(types_src)
- $(CC) $(CFLAGS) $(LDFLAGS) -c $<
+ $(CC) $(CFLAGS) -c $<

client: client.o common.o $(types_src)
- $(CXX) -o $@ client.o common.o $(LDFLAGS)
+ $(CXX) -o $@ client.o common.o $(LDFLAGS) $(GTEST_LIBS)

memq_test: memq_test.o
$(CXX) -o $@ memq_test.o $(LDFLAGS) $(GTEST_LIBS)

memq_test.o: memq_test.cpp $(types_src)
- $(CXX) `pkg-config --cflags lcm` -g -I../gtest/include -c $<
+ $(CXX) $(CFLAGS) -c $<

lcmtest/%.hpp: ../types/lcmtest/%.lcm
$(LCM_GEN) --cpp $<
=======================================
--- /test/cpp/client.cpp Fri Jan 17 03:04:05 2014 UTC
+++ /test/cpp/client.cpp Mon Nov 10 02:01:46 2014 UTC
@@ -2,66 +2,109 @@
#include <string.h>
#include <stdlib.h>
#include <time.h>
+#include <gtest/gtest.h>

#include <lcm/lcm.h>

#include "common.hpp"

-#define info(...) do { printf("cpp_client: "); printf(__VA_ARGS__); }
while(0)
+#define info(...) do { printf("cpp_client: "); printf(__VA_ARGS__); \
+ printf("\n"); } while(0)

-class LcmTest {
+class EchoTest {
public:
- LcmTest(lcm::LCM* lcm, const std::string test_name, int num_trails)
- : lcm_(lcm),
- test_channel_(test_name),
+ EchoTest()
+ : lcm_(),
+ num_trials_(100),
+ test_channel_("TEST_ECHO"),
response_count_(0),
- num_trials_(num_trails),
+ echo_data_(NULL),
+ echo_msg_len_(0),
subscription_() {
}
- virtual ~LcmTest() {
+
+ bool Run(void) {
+ int maxlen = 10000;
+ int minlen = 10;
+ echo_data_ = (uint8_t*) malloc(maxlen);
+ subscription_ = lcm_.subscribe(test_channel_ + "_REPLY",
+ &EchoTest::Handler, this);
+ response_count_ = 0;
+
+ for (int iter = 0; iter < num_trials_; iter++) {
+ echo_msg_len_ = rand() % (maxlen - minlen) + minlen;
+ for (int i = 0; i < echo_msg_len_; i++)
+ echo_data_[i] = rand() % 256;
+
+ lcm_.publish(test_channel_, echo_data_, echo_msg_len_);
+
+ if (lcm_.handleTimeout(500) <= 0 || (response_count_ != iter + 1)) {
+ info("echo test failed to receive response on iteration %d", iter);
+ free(echo_data_);
+ return false;
+ }
+ }
+
+ lcm_.unsubscribe(subscription_);
+ free(echo_data_);
+ return true;
}
- virtual bool Run()=0;

- protected:
- lcm::LCM* lcm_;
+ private:
+ void Handler(const lcm::ReceiveBuffer *rbuf, const std::string& channel)
{
+ if (rbuf->data_size != echo_msg_len_)
+ return;
+ if (memcmp(rbuf->data, echo_data_, rbuf->data_size))
+ return;
+ response_count_++;
+ }
+
+ lcm::LCM lcm_;
+ int num_trials_;
+ int echo_msg_len_;
+ uint8_t* echo_data_;
int response_count_;
- int num_trials_;
lcm::Subscription* subscription_;
std::string test_channel_;
};

+TEST(LCM_CPP, Echo) {
+ srand(time(NULL));
+
+ EXPECT_TRUE(EchoTest().Run());
+}
+
template<class LcmType>
-class LcmTypeTest : public LcmTest {
+class TypedTest {
public:
- LcmTypeTest(lcm::LCM* lcm, const std::string test_name, int num_trails)
- : LcmTest(lcm, test_name, num_trails) {
+ TypedTest(const std::string test_name, int num_trials)
+ : lcm_(),
+ test_channel_(test_name),
+ response_count_(0),
+ num_trials_(num_trials),
+ subscription_() {
}

bool Run(void) {
LcmType msg;
- lcm::Subscription* subscription = lcm_->subscribe(
- test_channel_ + "_reply", &LcmTypeTest<LcmType>::Handler, this);
+ lcm::Subscription* subscription = lcm_.subscribe(
+ test_channel_ + "_reply", &TypedTest<LcmType>::Handler, this);
bool result = true;
for (int trial = 0; trial < num_trials_ && result; trial++) {
FillLcmType(trial, &msg);
- lcm_->publish(test_channel_, &msg);
- if (!LcmHandleTimeout(lcm_, 500)) {
- info("%s test: Timeout waiting for reply\n",
test_channel_.c_str());
+ lcm_.publish(test_channel_, &msg);
+ if (lcm_.handleTimeout(500) <= 0) {
+ info("%s test: Timeout waiting for reply", test_channel_.c_str());
result = false;
break;
} else if (response_count_ != trial + 1) {
- info("%s test: failed on iteration %d\n", test_channel_.c_str(),
trial);
+ info("%s test: failed on iteration %d", test_channel_.c_str(),
trial);
result = false;
break;
}
ClearLcmType(&msg);
}
- lcm_->unsubscribe(subscription);
- if (result) {
- info("%-30s : PASSED\n", test_channel_.c_str());
- } else {
- info("%-30s : FAILED\n", test_channel_.c_str());
- }
+ lcm_.unsubscribe(subscription);
return result;
}

@@ -73,91 +116,35 @@
return;
}
}
-};

-class EchoTest : public LcmTest {
- public:
- EchoTest(lcm::LCM* lcm, int num_trails)
- : LcmTest(lcm, "TEST_ECHO", num_trails),
- echo_data_(NULL),
- echo_msg_len_(0) {
- }
- bool Run(void) {
- int maxlen = 10000;
- int minlen = 10;
- echo_data_ = (uint8_t*) malloc(maxlen);
- subscription_ = lcm_->subscribe(test_channel_ + "_REPLY",
- &EchoTest::Handler, this);
- response_count_ = 0;
-
- for (int iter = 0; iter < num_trials_; iter++) {
- echo_msg_len_ = rand() % (maxlen - minlen) + minlen;
- for (int i = 0; i < echo_msg_len_; i++)
- echo_data_[i] = rand() % 256;
-
- lcm_->publish(test_channel_, echo_data_, echo_msg_len_);
-
- if (!LcmHandleTimeout(lcm_, 500) || (response_count_ != iter + 1)) {
- info("echo test failed to receive response on iteration %d\n",
iter);
- free(echo_data_);
- return 0;
- }
- }
-
- info("%-30s : PASSED\n", "echo test");
- lcm_->unsubscribe(subscription_);
- free(echo_data_);
- return 1;
- }
-
- private:
- void Handler(const lcm::ReceiveBuffer *rbuf, const std::string& channel)
{
- if (rbuf->data_size != echo_msg_len_)
- return;
- if (memcmp(rbuf->data, echo_data_, rbuf->data_size))
- return;
- response_count_++;
- }
-
- int echo_msg_len_;
- uint8_t* echo_data_;
+ lcm::LCM lcm_;
+ int response_count_;
+ int num_trials_;
+ lcm::Subscription* subscription_;
+ std::string test_channel_;
};

-// ========================== main
-int main(int argc, char ** argv) {
- srand(time(NULL));
-
- lcm::LCM lcm;
- if (!lcm.good()) {
- info("Unable to initialize LCM\n");
- return 1;
- }
+TEST(LCM_CPP, primitives_t) {
+
EXPECT_TRUE(TypedTest<lcmtest::primitives_t>("test_lcmtest_primitives_t",
+ 1000).Run());
+}

- if (!EchoTest(&lcm, 100).Run())
- goto failed;
+TEST(LCM_CPP, primitives_list_t) {
+ EXPECT_TRUE(TypedTest<lcmtest::primitives_list_t>(
+ "test_lcmtest_primitives_list_t", 100).Run());
+}

- if
(!LcmTypeTest<lcmtest::primitives_t>(&lcm, "test_lcmtest_primitives_t",
- 1000).Run())
- goto failed;
- if (!LcmTypeTest<lcmtest::primitives_list_t>(&lcm,
- "test_lcmtest_primitives_list_t",
- 100).Run())
- goto failed;
- if (!LcmTypeTest<lcmtest::node_t>(&lcm, "test_lcmtest_node_t", 7).Run())
- goto failed;
- if (!LcmTypeTest<lcmtest::multidim_array_t>(&lcm,
- "test_lcmtest_multidim_array_t",
- 5).Run())
- goto failed;
- if (!LcmTypeTest<lcmtest2::cross_package_t>(&lcm,
- "test_lcmtest2_cross_package_t",
- 100).Run())
- goto failed;
+TEST(LCM_CPP, node_t) {
+ EXPECT_TRUE(TypedTest<lcmtest::node_t>("test_lcmtest_node_t",
+ 7).Run());
+}

- info("All tests passed.\n");
- return 0;
+TEST(LCM_CPP, multidim_array_t) {
+ EXPECT_TRUE(TypedTest<lcmtest::multidim_array_t>(
+ "test_lcmtest_multidim_array_t", 5).Run());
+}

- failed:
- info("failed\n");
- return 1;
+TEST(LCM_CPP, cross_package_t) {
+ EXPECT_TRUE(TypedTest<lcmtest2::cross_package_t>(
+ "test_lcmtest2_cross_package_t", 100).Run());
}
=======================================
--- /test/cpp/common.cpp Wed Jan 15 01:53:28 2014 UTC
+++ /test/cpp/common.cpp Mon Nov 10 02:01:46 2014 UTC
@@ -1,43 +1,16 @@
#include <stdio.h>
#include <inttypes.h>

-#ifndef WIN32
-#include <sys/select.h>
-typedef int SOCKET;
-#else
-#include <winsock2.h>
-#endif
-
#include "common.hpp"

-#define info(...) do { fprintf(stderr, "cpp_client: "); fprintf(stderr,
__VA_ARGS__); } while(0)
+#define info(...) do { fprintf(stderr, "cpp_client: "); \
+ fprintf(stderr, __VA_ARGS__); fprintf(stderr, "\n"); } while(0)

#define CHECK_FIELD(field, expected, fmt) \
if((field) != (expected)) { \
- info("Expected " #field " to be: " fmt ", got " fmt " instead\n",
(expected), (field)); \
+ info("Expected " #field " to be: " fmt ", got " fmt " instead",
(expected), (field)); \
return 0; \
}
-
-int LcmHandleTimeout(lcm::LCM* lcm, int ms) {
- // setup the LCM file descriptor for waiting.
- SOCKET lcm_fd = lcm->getFileno();
- fd_set fds;
- FD_ZERO(&fds);
- FD_SET(lcm_fd, &fds);
-
- // wait a limited amount of time for an incoming message
- struct timeval timeout = { ms / 1000, // seconds
- (ms % 1000) * 1000 // microseconds
- };
- int status = select(lcm_fd + 1, &fds, 0, 0, &timeout);
- if (status > 0 && FD_ISSET(lcm_fd, &fds)) {
- lcm->handle();
- return 1;
- }
-
- // no messages
- return 0;
-}

int CheckLcmType(const lcmtest::multidim_array_t* msg, int expected) {
CHECK_FIELD(msg->size_a, expected, "%d");
@@ -63,7 +36,7 @@
for (k = 0; k < msg->size_c; k++) {
snprintf(expected_buf, 79, "%d", n);
if (strcmp(expected_buf, msg->strarray[i][k].c_str())) {
- info("Expected msg->strarray[%d][%d] to be %s, got %s instead\n",
i, k,
+ info("Expected msg->strarray[%d][%d] to be %s, got %s instead", i,
k,
expected_buf, msg->strarray[i][k].c_str());
return 0;
}
@@ -184,7 +157,7 @@
char expected_name[100];
sprintf(expected_name, "%d", -n);
if(strcmp(expected_name, ex->name.c_str())) {
- info("Expected msg->items[%d].name to be %s, got %s
instead\n", n, expected_name, ex->name.c_str());
+ info("Expected msg->items[%d].name to be %s, got %s instead",
n, expected_name, ex->name.c_str());
return 0;
}
CHECK_FIELD(ex->enabled, (int)((n+1)%2), "%d");
@@ -246,7 +219,7 @@
char expected_name[100];
sprintf(expected_name, "%d", n);
if (strcmp(expected_name, msg->name.c_str())) {
- info("Expected msg->expected_name to be %s, got %s instead\n",
+ info("Expected msg->expected_name to be %s, got %s instead",
expected_name, msg->name.c_str());
return 0;
}
=======================================
--- /test/cpp/common.hpp Wed Jan 15 01:53:28 2014 UTC
+++ /test/cpp/common.hpp Mon Nov 10 02:01:46 2014 UTC
@@ -8,8 +8,6 @@
#include "lcmtest/multidim_array_t.hpp"
#include "lcmtest2/cross_package_t.hpp"

-int LcmHandleTimeout(lcm::LCM* lcm, int ms);
-
int CheckLcmType(const lcmtest::multidim_array_t* msg, int expected);
void FillLcmType(int num_children, lcmtest::multidim_array_t* result);
void ClearLcmType(lcmtest::multidim_array_t* msg);
=======================================
--- /test/python/client.py Fri Jan 17 03:04:05 2014 UTC
+++ /test/python/client.py Mon Nov 10 02:01:46 2014 UTC
@@ -3,6 +3,7 @@
import array
import random
import select
+import unittest

import lcm

@@ -276,7 +277,7 @@
return False

self.lc.unsubscribe(subs)
- info("%-31s : PASSED" % (pkg_name + "_" + self.msg_name))
+# info("%-31s : PASSED" % (pkg_name + "_" + self.msg_name))
return True


@@ -303,22 +304,31 @@
if not _lcm_handle_timeout(self.lc, 500) or
self.response_count != i + 1:
print("echo test failed to receive a response on
iteration %d" % i)
raise RuntimeError()
- info("%-31s : PASSED" % "echo test")
+# info("%-31s : PASSED" % "echo test")
self.lc.unsubscribe(self.subs)

-class Tester(object):
- def __init__(self):
+class Tester(unittest.TestCase):
+ def setUp(self):
+ random.seed()
self.lc = lcm.LCM()

- def run(self):
+ def test_1_echo(self):
EchoTester(self.lc).run()
+
+ def test_2_primitives_t(self):
StandardTester(self.lc, PrimitivesTest()).run()
+
+ def test_3_primitives_list_t(self):
StandardTester(self.lc, PrimitivesListTest()).run()
+
+ def test_4_node_t(self):
StandardTester(self.lc, NodeTest()).run()
+
+ def test_5_multidim_array_t(self):
StandardTester(self.lc, MultidimArrayTest()).run()
+
+ def test_6_cross_package(self):
StandardTester(self.lc, CrossPackageTest()).run()
- info("All tests passed")

-if __name__ == "__main__":
- random.seed()
- Tester().run()
+if __name__ == '__main__':
+ unittest.main()
=======================================
--- /test/run_tests.py Thu Jul 24 02:56:59 2014 UTC
+++ /test/run_tests.py Mon Nov 10 02:01:46 2014 UTC
@@ -6,21 +6,17 @@
import time

client = "c"
-server = "c"

tests = { \
- "c" : ("c/server", "c/client"),
- "python" : (None, "python python/client.py"),
- "cpp" : ("cpp/server", "cpp/client"),
+ "c" : "c/client",
+ "python" : "python python/client.py",
+ "cpp" : "cpp/client",
}

-def dotest(client_name, server_name):
+def dotest(client_name):
global tests
- server_args = tests[server_name][0]
- client_args = tests[client_name][1]
- if server_args is None:
- print("server test not defined for %s" % server_name)
- sys.exit(2)
+ server_args = "c/server"
+ client_args = tests[client_name]
if client_args is None:
print("client test not defined for %s" % client_name)
sys.exit(2)
@@ -28,18 +24,16 @@
time.sleep(0.1)
client_proc = subprocess.Popen(client_args, shell=True)

+ client_status = client_proc.wait()
+ server_proc.terminate()
server_status = server_proc.wait()
- client_status = client_proc.wait()
- print("server %s returned: %d" % (server_name, server_status))
+ print("server returned: %d" % (server_status))
print("client %s returned: %d" % (client_name, client_status))
print
-
+
def usage():
- print("Usage: %s [options] [client] [server]" % sys.argv[0])
+ print("Usage: %s [options] [client]" % sys.argv[0])
print("")
-# print(" client and server can be one of:")
-# print(" c")
-# print("")
print("Options:")
print(" -h, --help Show this help text")
print("")
@@ -54,16 +48,9 @@
if o in ["-h", "--help"]:
usage()

-#server = "c"
-#client = "c"
-#
-#if len(args) > 0):
-#
-#print("remaining args: %s" % args)
-
-dotest("c", "c")
-dotest("python", "c")
-dotest("cpp", "c")
+dotest("c")
+dotest("python")
+dotest("cpp")

print("Running C++ tests")
subprocess.check_call("cpp/memq_test", shell=True)

==============================================================================
Revision: 0c3c0705011f
Author: Albert Huang <ash...@gmail.com>
Date: Fri Nov 14 07:03:42 2014 UTC
Log: Convert unit tests to xml output
- add xmlrunner.py
- convert Python tests to use unittest module
- simplify C test server, convert to always running
- C/C++/Python unit tests output XML, which gets parsed by test runner

https://code.google.com/p/lcm/source/detail?r=0c3c0705011f

Added:
/test/run_client_server_tests.py
/test/xmlrunner.py
Deleted:
/test/run_tests.py
Modified:
/test/Makefile
/test/c/server.c
/test/python/client.py
/test/python/lcm_file_test.py

=======================================
--- /dev/null
+++ /test/run_client_server_tests.py Fri Nov 14 07:03:42 2014 UTC
@@ -0,0 +1,57 @@
+#!/usr/bin/env python
+import os
+import sys
+import subprocess
+
+def usage():
+ print("Usage: %s [options] [client]" % sys.argv[0])
+ print("")
+ print("Options:")
+ print(" -h, --help Show this help text")
+ print("")
+
+def main():
+ to_test = {
+ "C" : "c/client",
+ "Python" : "python python/client.py",
+ "C++" : "cpp/client",
+ "Lua" : "cd lua; lua client.lua"
+ }
+
+ test_passed = {}
+
+ # Start the test server
+ if not os.path.exists("c/server"):
+ print("Can't find test server c/server")
+ print("Try running 'make' first")
+ return 1
+ print("Starting test server")
+ server_proc = subprocess.Popen("c/server")
+
+ # Run the client tests while the test server is running
+ for name, prog in to_test.items():
+ client_status = subprocess.Popen(prog, shell=True).wait()
+ test_passed[name] = client_status == 0
+
+ # Stop the test server
+ print("Stopping test server")
+ server_proc.terminate()
+ server_status = server_proc.wait()
+ print("Test server stopped")
+
+ # Report
+ print("")
+ print("Test results:")
+ for name in sorted(test_passed.keys()):
+ if test_passed[name]:
+ print(" OK %s" % name)
+ else:
+ print(" FAIL %s" % name)
+
+ if all(test_passed.values()):
+ return 0
+ else:
+ return 1
+
+if __name__ == "__main__":
+ sys.exit(main())
=======================================
--- /dev/null
+++ /test/xmlrunner.py Fri Nov 14 07:03:42 2014 UTC
@@ -0,0 +1,405 @@
+# -*- coding: utf-8 -*-
+
+"""
+XML Test Runner for PyUnit
+"""
+
+# Written by Sebastian Rittau <sri...@jroger.in-berlin.de> and placed in
+# the Public Domain. With contributions by Paolo Borelli and others.
+
+from __future__ import unicode_literals
+
+__version__ = "0.2"
+
+import os.path
+import re
+import sys
+import time
+import traceback
+import unittest
+import unittest.util
+from xml.sax.saxutils import escape
+
+from io import StringIO, BytesIO
+
+
+class _TestInfo(object):
+
+ """Information about a particular test.
+
+ Used by _XMLTestResult.
+
+ """
+
+ def __init__(self, test, time):
+ (self._class, self._method) = test.id().rsplit(".", 1)
+ self._time = time
+ self._error = None
+ self._failure = None
+
+ @staticmethod
+ def create_success(test, time):
+ """Create a _TestInfo instance for a successful test."""
+ return _TestInfo(test, time)
+
+ @staticmethod
+ def create_failure(test, time, failure):
+ """Create a _TestInfo instance for a failed test."""
+ info = _TestInfo(test, time)
+ info._failure = failure
+ return info
+
+ @staticmethod
+ def create_error(test, time, error):
+ """Create a _TestInfo instance for an erroneous test."""
+ info = _TestInfo(test, time)
+ info._error = error
+ return info
+
+ def print_report(self, stream):
+ """Print information about this test case in XML format to the
+ supplied stream.
+
+ """
+ tag_template = (' <testcase classname="{class_}" name="{method}" '
+ 'time="{time:.4f}">')
+ stream.write(tag_template.format(class_=self._class,
+ method=self._method,
+ time=self._time))
+ if self._failure is not None:
+ self._print_error(stream, 'failure', self._failure)
+ if self._error is not None:
+ self._print_error(stream, 'error', self._error)
+ stream.write('</testcase>\n')
+
+ @staticmethod
+ def _print_error(stream, tag_name, error):
+ """Print information from a failure or error to the supplied
stream."""
+ str_ = str if sys.version_info[0] >= 3 else unicode
+ io_class = StringIO if sys.version_info[0] >= 3 else BytesIO
+ text = escape(str_(error[1]))
+ class_name = unittest.util.strclass(error[0])
+ stream.write('\n')
+ stream.write(' <{tag} type="{class_}">{text}\n'.format(
+ tag=tag_name, class_= class_name, text=text))
+ tb_stream = io_class()
+ traceback.print_tb(error[2], None, tb_stream)
+ tb_string = tb_stream.getvalue()
+ if sys.version_info[0] < 3:
+ tb_string = tb_string.decode("utf-8")
+ stream.write(escape(tb_string))
+ stream.write(' </{tag}>\n'.format(tag=tag_name))
+ stream.write(' ')
+
+
+def _clsname(cls):
+ return cls.__module__ + "." + cls.__name__
+
+
+class _XMLTestResult(unittest.TestResult):
+
+ """A test result class that stores result as XML.
+
+ Used by XMLTestRunner.
+
+ """
+
+ def __init__(self, class_name):
+ unittest.TestResult.__init__(self)
+ self._test_name = class_name
+ self._start_time = None
+ self._tests = []
+ self._error = None
+ self._failure = None
+
+ def startTest(self, test):
+ unittest.TestResult.startTest(self, test)
+ self._error = None
+ self._failure = None
+ self._start_time = time.time()
+
+ def stopTest(self, test):
+ time_taken = time.time() - self._start_time
+ unittest.TestResult.stopTest(self, test)
+ if self._error:
+ info = _TestInfo.create_error(test, time_taken, self._error)
+ elif self._failure:
+ info = _TestInfo.create_failure(test, time_taken,
self._failure)
+ else:
+ info = _TestInfo.create_success(test, time_taken)
+ self._tests.append(info)
+
+ def addError(self, test, err):
+ unittest.TestResult.addError(self, test, err)
+ self._error = err
+
+ def addFailure(self, test, err):
+ unittest.TestResult.addFailure(self, test, err)
+ self._failure = err
+
+ def print_report(self, stream, time_taken, out, err):
+ """Prints the XML report to the supplied stream.
+
+ The time the tests took to perform as well as the captured standard
+ output and standard error streams must be passed in.a
+
+ """
+ tag_template = ('<testsuite errors="{errors}"
failures="{failures}" '
+ 'name="{name}" tests="{total}"
time="{time:.3f}">\n')
+ stream.write(tag_template.format(name=self._test_name,
+ total=self.testsRun,
+ errors=len(self.errors),
+ failures=len(self.failures),
+ time=time_taken))
+ for info in self._tests:
+ info.print_report(stream)
+ stream.write(' <system-out><![CDATA[{0}]]></system-out>\n'.format(
+ out))
+ stream.write(' <system-err><![CDATA[{0}]]></system-err>\n'.format(
+ err))
+ stream.write('</testsuite>\n')
+
+
+class XMLTestRunner(object):
+
+ """A test runner that stores results in XML format compatible with
JUnit.
+
+ XMLTestRunner(stream=None) -> XML test runner
+
+ The XML file is written to the supplied stream. If stream is None, the
+ results are stored in a file called TEST-<module>.<class>.xml in the
+ current working directory (if not overridden with the path property),
+ where <module> and <class> are the module and class name of the test
class.
+
+ """
+
+ def __init__(self, stream=None):
+ self._stream = stream
+ self._path = "."
+
+ def run(self, test, name = None):
+ """Run the given test case or test suite."""
+ class_ = test.__class__
+ if name is None:
+ name = class_.__module__ + "." + class_.__name__
+ if self._stream is None:
+ filename = "TEST-{0}.xml".format(name)
+ stream = open(os.path.join(self._path, filename), "w")
+ stream.write('<?xml version="1.0" encoding="utf-8"?>\n')
+ else:
+ stream = self._stream
+
+ result = _XMLTestResult(name)
+ start_time = time.time()
+
+ with _FakeStdStreams():
+ test(result)
+ try:
+ out_s = sys.stdout.getvalue()
+ except AttributeError:
+ out_s = ""
+ try:
+ err_s = sys.stderr.getvalue()
+ except AttributeError:
+ err_s = ""
+
+ time_taken = time.time() - start_time
+ result.print_report(stream, time_taken, out_s, err_s)
+ if self._stream is None:
+ stream.close()
+
+ return result
+
+ def _set_path(self, path):
+ self._path = path
+
+ path = property(
+ lambda self: self._path, _set_path, None,
+ """The path where the XML files are stored.
+
+ This property is ignored when the XML file is written to a file
+ stream.""")
+
+
+class _FakeStdStreams(object):
+
+ def __enter__(self):
+ self._orig_stdout = sys.stdout
+ self._orig_stderr = sys.stderr
+ sys.stdout = StringIO()
+ sys.stderr = StringIO()
+
+ def __exit__(self, exc_type, exc_val, exc_tb):
+ sys.stdout = self._orig_stdout
+ sys.stderr = self._orig_stderr
+
+
+class XMLTestRunnerTest(unittest.TestCase):
+
+ def setUp(self):
+ self._stream = StringIO()
+
+ def _try_test_run(self, test_class, expected):
+
+ """Run the test suite against the supplied test class and compare
the
+ XML result against the expected XML string. Fail if the expected
+ string doesn't match the actual string. All time attributes in the
+ expected string should have the value "0.000". All error and
failure
+ messages are reduced to "Foobar".
+
+ """
+
+ self._run_test_class(test_class)
+
+ got = self._stream.getvalue()
+ # Replace all time="X.YYY" attributes by time="0.000" to enable a
+ # simple string comparison.
+ got = re.sub(r'time="\d+\.\d+"', 'time="0.000"', got)
+ # Likewise, replace all failure and error messages by a
simple "Foobar"
+ # string.
+ got = re.sub(r'(?s)<failure (.*?)>.*?</failure>',
+ r'<failure \1>Foobar</failure>', got)
+ got = re.sub(r'(?s)<error (.*?)>.*?</error>',
+ r'<error \1>Foobar</error>', got)
+ # And finally Python 3 compatibility.
+ got = got.replace('type="builtins.', 'type="exceptions.')
+
+ self.assertEqual(expected, got)
+
+ def _run_test_class(self, test_class):
+ runner = XMLTestRunner(self._stream)
+ runner.run(unittest.makeSuite(test_class))
+
+ def test_no_tests(self):
+ """Regression test: Check whether a test run without any tests
+ matches a previous run.
+
+ """
+ class TestTest(unittest.TestCase):
+ pass
+ self._try_test_run(TestTest, """<testsuite errors="0" failures="0"
name="unittest.suite.TestSuite" tests="0" time="0.000">
+ <system-out><![CDATA[]]></system-out>
+ <system-err><![CDATA[]]></system-err>
+</testsuite>
+""")
+
+ def test_success(self):
+ """Regression test: Check whether a test run with a successful test
+ matches a previous run.
+
+ """
+ class TestTest(unittest.TestCase):
+ def test_foo(self):
+ pass
+ self._try_test_run(TestTest, """<testsuite errors="0" failures="0"
name="unittest.suite.TestSuite" tests="1" time="0.000">
+ <testcase classname="__main__.TestTest" name="test_foo"
time="0.000"></testcase>
+ <system-out><![CDATA[]]></system-out>
+ <system-err><![CDATA[]]></system-err>
+</testsuite>
+""")
+
+ def test_failure(self):
+ """Regression test: Check whether a test run with a failing test
+ matches a previous run.
+
+ """
+ class TestTest(unittest.TestCase):
+ def test_foo(self):
+ self.assertTrue(False)
+ self._try_test_run(TestTest, """<testsuite errors="0" failures="1"
name="unittest.suite.TestSuite" tests="1" time="0.000">
+ <testcase classname="__main__.TestTest" name="test_foo" time="0.000">
+ <failure type="exceptions.AssertionError">Foobar</failure>
+ </testcase>
+ <system-out><![CDATA[]]></system-out>
+ <system-err><![CDATA[]]></system-err>
+</testsuite>
+""")
+
+ def test_error(self):
+ """Regression test: Check whether a test run with a erroneous test
+ matches a previous run.
+
+ """
+ class TestTest(unittest.TestCase):
+ def test_foo(self):
+ raise IndexError()
+ self._try_test_run(TestTest, """<testsuite errors="1" failures="0"
name="unittest.suite.TestSuite" tests="1" time="0.000">
+ <testcase classname="__main__.TestTest" name="test_foo" time="0.000">
+ <error type="exceptions.IndexError">Foobar</error>
+ </testcase>
+ <system-out><![CDATA[]]></system-out>
+ <system-err><![CDATA[]]></system-err>
+</testsuite>
+""")
+
+ def test_non_ascii_characters_in_traceback(self):
+ """Test umlauts in traceback exception messages."""
+ class TestTest(unittest.TestCase):
+ def test_foo(self):
+ raise Exception("Test äöü")
+ self._run_test_class(TestTest)
+
+ def test_stdout_capture(self):
+ """Regression test: Check whether a test run with output to stdout
+ matches a previous run.
+
+ """
+ class TestTest(unittest.TestCase):
+ def test_foo(self):
+ sys.stdout.write("Test\n")
+ self._try_test_run(TestTest, """<testsuite errors="0" failures="0"
name="unittest.suite.TestSuite" tests="1" time="0.000">
+ <testcase classname="__main__.TestTest" name="test_foo"
time="0.000"></testcase>
+ <system-out><![CDATA[Test
+]]></system-out>
+ <system-err><![CDATA[]]></system-err>
+</testsuite>
+""")
+
+ def test_stderr_capture(self):
+ """Regression test: Check whether a test run with output to stderr
+ matches a previous run.
+
+ """
+ class TestTest(unittest.TestCase):
+ def test_foo(self):
+ sys.stderr.write("Test\n")
+ self._try_test_run(TestTest, """<testsuite errors="0" failures="0"
name="unittest.suite.TestSuite" tests="1" time="0.000">
+ <testcase classname="__main__.TestTest" name="test_foo"
time="0.000"></testcase>
+ <system-out><![CDATA[]]></system-out>
+ <system-err><![CDATA[Test
+]]></system-err>
+</testsuite>
+""")
+
+ class NullStream(object):
+ """A file-like object that discards everything written to it."""
+ def write(self, buffer):
+ pass
+
+ def test_unittests_changing_stdout(self):
+ """Check whether the XMLTestRunner recovers gracefully from unit
tests
+ that change stdout, but don't change it back properly.
+
+ """
+ class TestTest(unittest.TestCase):
+ def test_foo(self):
+ sys.stdout = XMLTestRunnerTest.NullStream()
+
+ runner = XMLTestRunner(self._stream)
+ runner.run(unittest.makeSuite(TestTest))
+
+ def test_unittests_changing_stderr(self):
+ """Check whether the XMLTestRunner recovers gracefully from unit
tests
+ that change stderr, but don't change it back properly.
+
+ """
+ class TestTest(unittest.TestCase):
+ def test_foo(self):
+ sys.stderr = XMLTestRunnerTest.NullStream()
+
+ runner = XMLTestRunner(self._stream)
+ runner.run(unittest.makeSuite(TestTest))
+
+
+if __name__ == "__main__":
+ unittest.main()
=======================================
--- /test/run_tests.py Mon Nov 10 02:01:46 2014 UTC
+++ /dev/null
@@ -1,64 +0,0 @@
-#!/usr/bin/env python
-
-import sys
-import subprocess
-import getopt
-import time
-
-client = "c"
-
-tests = { \
- "c" : "c/client",
- "python" : "python python/client.py",
- "cpp" : "cpp/client",
- }
-
-def dotest(client_name):
- global tests
- server_args = "c/server"
- client_args = tests[client_name]
- if client_args is None:
- print("client test not defined for %s" % client_name)
- sys.exit(2)
- server_proc = subprocess.Popen(server_args, shell=True)
- time.sleep(0.1)
- client_proc = subprocess.Popen(client_args, shell=True)
-
- client_status = client_proc.wait()
- server_proc.terminate()
- server_status = server_proc.wait()
- print("server returned: %d" % (server_status))
- print("client %s returned: %d" % (client_name, client_status))
- print
-
-def usage():
- print("Usage: %s [options] [client]" % sys.argv[0])
- print("")
- print("Options:")
- print(" -h, --help Show this help text")
- print("")
-
-try:
- opts, args = getopt.getopt(sys.argv[1:], 'h', ['help'])
-except getopt.GetoptError:
- usage()
- sys.exit(2)
-
-for o, a in opts:
- if o in ["-h", "--help"]:
- usage()
-
-dotest("c")
-dotest("python")
-dotest("cpp")
-
-print("Running C++ tests")
-subprocess.check_call("cpp/memq_test", shell=True)
-
-# Call the lcm_file_test independantly
-print("Running Python tests.")
-subprocess.check_call("python/bool_test.py", shell=True)
-subprocess.check_call("python/byte_array_test.py", shell=True)
-subprocess.check_call("python/lcm_file_test.py", shell=True)
-subprocess.check_call("python/lcm_memq_test.py", shell=True)
-subprocess.check_call("python/lcm_thread_test.py", shell=True)
=======================================
--- /test/Makefile Mon Jul 7 07:30:30 2014 UTC
+++ /test/Makefile Fri Nov 14 07:03:42 2014 UTC
@@ -1,15 +1,13 @@
-all: test
-
-.buildstamp:
+all:
$(MAKE) -C gtest
$(MAKE) -C c
$(MAKE) -C python
$(MAKE) -C cpp
$(MAKE) -C java
- touch .buildstamp

-test: .buildstamp
- ./run_tests.py
+test: all
+ ./run_client_server_tests.py
+ ./run_unit_tests.py

clean:
$(MAKE) -C gtest clean
@@ -17,4 +15,3 @@
$(MAKE) -C python clean
$(MAKE) -C cpp clean
$(MAKE) -C java clean
- rm -f .buildstamp
=======================================
--- /test/c/server.c Mon Nov 10 02:01:46 2014 UTC
+++ /test/c/server.c Fri Nov 14 07:03:42 2014 UTC
@@ -2,98 +2,108 @@
#include <stdlib.h>
#include <lcm/lcm.h>

-#ifndef WIN32
-#include <sys/select.h>
-typedef int SOCKET;
-#else
-#include <winsock2.h>
-#endif
-
#include "common.h"

-#define info(...) do { fprintf(stderr, "c_server: "); \
- fprintf(stderr, __VA_ARGS__); fprintf(stderr, "\n"); } while(0)
-
static lcm_t* g_lcm = NULL;
+static int g_quit = 0;
+static int g_lcmtest_primitives_t_count = 0;
+static int g_lcmtest_primitives_list_t_count = 0;
+static int g_lcmtest_node_t_count = 0;
+static int g_lcmtest_multidim_array_t_count = 0;
+static int g_lcmtest2_cross_package_t_count = 0;

-// Overall test status
-static int g_test_complete = 0;
-static int g_test_passed = 0;
+static void
+reset_counts() {
+ g_lcmtest_primitives_t_count = 0;
+ g_lcmtest_primitives_list_t_count = 0;
+ g_lcmtest_node_t_count = 0;
+ g_lcmtest_multidim_array_t_count = 0;
+ g_lcmtest2_cross_package_t_count = 0;
+}

static void
-all_tests_passed(void)
+lcmtest_primitives_t_handler(const lcm_recv_buf_t* rbuf,
+ const char* channel,
+ const lcmtest_primitives_t* msg, void* user)
{
- g_test_passed = 1;
- g_test_complete = 1;
-}
+ // Reset all counts (maybe)
+ if (msg->i64 == 0) {
+ reset_counts();
+ }

-// Generic macro for declaring a test
-#define MAKE_TEST(type, num_iters, success_func) \
-\
-static int g_##type##_count = 0; \
-static type##_subscription_t* g_##type##_subscription = NULL; \
-\
-static void \
-type##_handler(const lcm_recv_buf_t* rbuf, const char* channel, \
- const type* msg, void* user) \
-{ \
- if(!check_##type(msg, g_##type##_count)) { \
- g_test_passed = 0; \
- g_test_complete = 1; \
- return; \
- } \
- type reply; \
- fill_##type(g_##type##_count + 1, &reply); \
- type##_publish(g_lcm, "test_" #type "_reply", &reply); \
- clear_##type(&reply); \
- g_##type##_count++; \
- if(g_##type##_count == num_iters) { \
- type##_unsubscribe(g_lcm, g_##type##_subscription); \
- success_func(); \
- } \
-} \
-\
-static void \
-begin_##type##_test() \
-{ \
- g_##type##_subscription = type##_subscribe(g_lcm, "test_" #type, &
type##_handler, NULL); \
+ lcmtest_primitives_t reply;
+ fill_lcmtest_primitives_t(g_lcmtest_primitives_t_count + 1,
+ &reply);
+ lcmtest_primitives_t_publish(g_lcm,
+ "test_lcmtest_primitives_t_reply", &reply);
+ clear_lcmtest_primitives_t(&reply);
+ g_lcmtest_primitives_t_count++;
}

-MAKE_TEST(lcmtest2_cross_package_t, 100, all_tests_passed);
-MAKE_TEST(lcmtest_multidim_array_t, 5,
begin_lcmtest2_cross_package_t_test);
-MAKE_TEST(lcmtest_node_t, 7, begin_lcmtest_multidim_array_t_test);
-MAKE_TEST(lcmtest_primitives_list_t, 100, begin_lcmtest_node_t_test);
-MAKE_TEST(lcmtest_primitives_t, 1000,
begin_lcmtest_primitives_list_t_test);
+static void
+lcmtest_primitives_list_t_handler(const lcm_recv_buf_t* rbuf,
+ const char* channel,
+ const lcmtest_primitives_list_t* msg, void* user)
+{
+ lcmtest_primitives_list_t reply;
+ fill_lcmtest_primitives_list_t(g_lcmtest_primitives_list_t_count + 1,
+ &reply);
+ lcmtest_primitives_list_t_publish(g_lcm,
+ "test_lcmtest_primitives_list_t_reply", &reply);
+ clear_lcmtest_primitives_list_t(&reply);
+ g_lcmtest_primitives_list_t_count++;
+}

-// ========================== echo test
-static int g_echo_count = 0;
-static lcm_subscription_t* g_echo_subscription = NULL;
+static void
+lcmtest_node_t_handler(const lcm_recv_buf_t* rbuf,
+ const char* channel,
+ const lcmtest_node_t* msg, void* user)
+{
+ lcmtest_node_t reply;
+ fill_lcmtest_node_t(g_lcmtest_node_t_count + 1,
+ &reply);
+ lcmtest_node_t_publish(g_lcm, "test_lcmtest_node_t_reply",
+ &reply);
+ clear_lcmtest_node_t(&reply);
+ g_lcmtest_node_t_count++;
+}

+static void
+lcmtest_multidim_array_t_handler(const lcm_recv_buf_t* rbuf,
+ const char* channel,
+ const lcmtest_multidim_array_t* msg, void* user)
+{
+ lcmtest_multidim_array_t reply;
+ fill_lcmtest_multidim_array_t(g_lcmtest_multidim_array_t_count + 1,
+ &reply);
+ lcmtest_multidim_array_t_publish(g_lcm,
+ "test_lcmtest_multidim_array_t_reply", &reply);
+ clear_lcmtest_multidim_array_t(&reply);
+ g_lcmtest_multidim_array_t_count++;
+}

static void
-end_echo_test()
+lcmtest2_cross_package_t_handler(const lcm_recv_buf_t* rbuf,
+ const char* channel, const lcmtest2_cross_package_t* msg, void* user)
{
- lcm_unsubscribe(g_lcm, g_echo_subscription);
- begin_lcmtest_primitives_t_test();
+ lcmtest2_cross_package_t reply;
+ fill_lcmtest2_cross_package_t(g_lcmtest2_cross_package_t_count + 1,
+ &reply);
+ lcmtest2_cross_package_t_publish(g_lcm,
+ "test_lcmtest2_cross_package_t_reply", &reply);
+ clear_lcmtest2_cross_package_t(&reply);
+ g_lcmtest2_cross_package_t_count++;
}

static void
echo_handler(const lcm_recv_buf_t *rbuf, const char* channel, void* user)
{
lcm_publish(g_lcm, "TEST_ECHO_REPLY", rbuf->data, rbuf->data_size);
- g_echo_count++;
-
- if(g_echo_count >= 100)
- {
- end_echo_test();
- }
}

static void
-begin_echo_test()
-{
- g_echo_subscription = lcm_subscribe(g_lcm, "TEST_ECHO",
- &echo_handler, NULL);
+quit_handler() {
+ g_quit = 1;
}

// ============================
@@ -104,13 +114,27 @@
if(!g_lcm)
return 1;

- begin_echo_test();
+ lcm_subscribe(g_lcm, "TEST_QUIT", &quit_handler, NULL);
+
+ lcm_subscribe(g_lcm, "TEST_ECHO", &echo_handler, NULL);
+
+ lcmtest_primitives_t_subscribe(g_lcm, "test_lcmtest_primitives_t",
+ &lcmtest_primitives_t_handler, NULL);
+
+
lcmtest_primitives_list_t_subscribe(g_lcm, "test_lcmtest_primitives_list_t",
+ &lcmtest_primitives_list_t_handler, NULL);
+
+ lcmtest_node_t_subscribe(g_lcm, "test_lcmtest_node_t",
+ &lcmtest_node_t_handler, NULL);
+
+
lcmtest_multidim_array_t_subscribe(g_lcm, "test_lcmtest_multidim_array_t",
+ &lcmtest_multidim_array_t_handler, NULL);
+
+
lcmtest2_cross_package_t_subscribe(g_lcm, "test_lcmtest2_cross_package_t",
+ &lcmtest2_cross_package_t_handler, NULL);

- while (!g_test_complete && (lcm_handle(g_lcm) == 0)) {
- }
+ while (lcm_handle(g_lcm) == 0 && !g_quit) {}

lcm_destroy(g_lcm);
- if(!g_test_passed)
- info("Test failed.");
- return !g_test_passed;
+ return 0;
}
=======================================
--- /test/python/client.py Mon Nov 10 02:01:46 2014 UTC
+++ /test/python/client.py Fri Nov 14 07:03:42 2014 UTC
@@ -307,7 +307,7 @@
# info("%-31s : PASSED" % "echo test")
self.lc.unsubscribe(self.subs)

-class Tester(unittest.TestCase):
+class ClientTest(unittest.TestCase):
def setUp(self):
random.seed()
self.lc = lcm.LCM()
=======================================
--- /test/python/lcm_file_test.py Thu Jul 24 07:09:43 2014 UTC
+++ /test/python/lcm_file_test.py Fri Nov 14 07:03:42 2014 UTC
@@ -34,7 +34,7 @@
msg = self.tester.make_message(iteration)
lcm_obj.publish(self.test_channel, msg.encode())

- print("opening read mode")
+# print("opening read mode")
lcm_obj = lcm.LCM("file://%s?mode=r" % self.log_filename)
subs = lcm_obj.subscribe(self.test_channel, handler)
for iteration in range(self.num_iterations):

==============================================================================
Revision: dd4397fa2000
Author: Albert Huang <ash...@gmail.com>
Date: Sun Nov 16 21:14:57 2014 UTC
Log: Start on java LcmTestClient

https://code.google.com/p/lcm/source/detail?r=dd4397fa2000

Added:
/test/java/build.xml
/test/java/lcmtest/LcmTestClient.java
/test/run_unit_tests.py
Modified:
/.gitignore
/lcm-java/make-javadocs.sh
/test/python/client.py

=======================================
--- /dev/null
+++ /test/java/build.xml Sun Nov 16 21:14:57 2014 UTC
@@ -0,0 +1,47 @@
+<project name="lcmtest" default="build" basedir=".">
+
+ <target name="build" depends="build-lcmtest"/>
+
+ <!--
+ <target name="build-hamcrest-core">
+ <mkdir dir="build"/>
+ <javac srcdir="hamcrest-core-1.3"
+ classpath="hamcrest-core-1.3"
+ includes="**/*.java"
+ destdir="build"/>
+ </target>
+
+ <target name="build-junit" depends="build-hamcrest-core">
+ <javac srcdir="junit-4.11"
+ classpath="build:junit-4.11"
+ includes="**/*.java"
+ destdir="build"/>
+ </target>
+ <target name="build-lcmtest" depends="build-junit">
+-->
+
+ <target name="build-lcmtest">
+ <mkdir dir="build"/>
+ <exec executable="../../lcmgen/lcm-gen">
+ <arg value="--lazy"/>
+ <arg value="--java"/>
+ <arg value="--jpath"/>
+ <arg value="lcmtest"/>
+ <arg value="../types/lcmtest/comments_t.lcm"/>
+ <arg value="../types/lcmtest/primitives_list_t.lcm"/>
+ <arg value="../types/lcmtest/bools_t.lcm"/>
+ <arg value="../types/lcmtest/node_t.lcm"/>
+ <arg value="../types/lcmtest/multidim_array_t.lcm"/>
+ <arg value="../types/lcmtest/primitives_t.lcm"/>
+ <arg value="../types/lcmtest/exampleconst_t.lcm"/>
+ <arg value="../types/lcmtest/byte_array_t.lcm"/>
+ <arg value="../types/lcmtest2/cross_package_t.lcm"/>
+ <arg value="../types/lcmtest2/another_type_t.lcm"/>
+ </exec>
+ <javac srcdir="lcmtest"
+ classpath="../../lcm-java/lcm.jar"
+ includeAntRuntime="no"
+ includes="**/*.java"
+ destdir="build"/>
+ </target>
+</project>
=======================================
--- /dev/null
+++ /test/java/lcmtest/LcmTestClient.java Sun Nov 16 21:14:57 2014 UTC
@@ -0,0 +1,338 @@
+import java.io.IOException;
+import java.io.DataInput;
+import java.lang.IllegalArgumentException;
+import java.lang.Thread;
+import java.util.Arrays;
+import java.util.Random;
+
+import lcm.lcm.LCM;
+import lcm.lcm.LCMSubscriber;
+import lcm.lcm.LCMDataInputStream;
+
+import lcmtest.primitives_t;
+import lcmtest.primitives_list_t;
+import lcmtest.node_t;
+import lcmtest.multidim_array_t;
+import lcmtest2.cross_package_t;
+
+public class LcmTestClient implements LCMSubscriber {
+ private boolean test_success_ = false;
+ private boolean test_failed_ = false;
+ private boolean any_test_failed_ = false;
+
+ private LCM lcm_;
+ private byte echo_data_[];
+ private int echo_response_count_ = 0;
+ private Random random_ = new Random();
+
+ private long abort_time_ = 0;
+
+ LcmTestClient() {}
+
+ static private <T> void checkField(T actual, T expected, String field)
{
+ if (!actual.equals(expected)) {
+ throw new IllegalArgumentException(
+ String.format("%s : Expected %s, got %s",
+ field, String.valueOf(expected),
String.valueOf(actual)));
+ }
+ }
+
+ private void setupSubscribers() throws IOException {
+ lcm_ = new LCM();
+
+ lcm_.subscribe("TEST_ECHO_REPLY", this);
+ }
+
+ public void messageReceived(LCM lcm, String channel,
+ LCMDataInputStream ins) {
+ if (channel.equals("TEST_ECHO_REPLY")) {
+ handleEchoReply(ins);
+ }
+ }
+
+ private void handleEchoReply(LCMDataInputStream ins) {
+ try {
+ int len = ins.available();
+ byte data[] = new byte[len];
+ ins.readFully(data);
+
+ if (!Arrays.equals(data, echo_data_)) {
+ test_failed_ = true;
+ return;
+ }
+
+ echo_response_count_++;
+ if (echo_response_count_ >= 100) {
+ test_success_ = true;
+ } else {
+ sendNextEchoMessage();
+ }
+ } catch (IOException ex) {
+ System.err.println("Failed to handle echo reply");
+ }
+ }
+
+ private void sendNextEchoMessage() throws IOException {
+ echo_data_ = new byte[random_.nextInt(9990) + 10];
+ random_.nextBytes(echo_data_);
+ lcm_.publish("TEST_ECHO", echo_data_, 0, echo_data_.length);
+ }
+
+ private boolean waitForSuccessOrAbort() {
+ while(true) {
+ synchronized(this) {
+ if (test_success_) {
+ return true;
+ }
+ }
+ try {
+ Thread.sleep(100);
+ } catch (java.lang.InterruptedException ex) {
+ return false;
+ }
+
+ if (System.currentTimeMillis() >= abort_time_) {
+ System.err.printf("Timed out");
+ test_failed_ = true;
+ return false;
+ }
+ }
+ }
+
+ private boolean doEchoTest() throws IOException {
+ echo_data_ = new byte[10000];
+ echo_response_count_ = 0;
+ sendNextEchoMessage();
+ abort_time_ = System.currentTimeMillis() + 500;
+ return waitForSuccessOrAbort();
+ }
+
+ private interface MessageMakerChecker<MsgType> {
+ public MsgType makeMessage(int iteration);
+ public boolean checkReply(MsgType msg, int iteration);
+ }
+
+ private class MessageTester<MsgType extends lcm.lcm.LCMEncodable>
implements LCMSubscriber {
+ private MessageMakerChecker<MsgType> makerChecker_;
+ private String name_;
+ private int iteration_ = 0;
+ private int numIterations_;
+ private LCM lcm_;
+ private long abortTime_;
+ private boolean success_ = false;
+ private boolean done_ = false;
+ private Class type_;
+
+ MessageTester(LCM lcm, String name, MessageMakerChecker<MsgType>
makerChecker,
+ int numIterations) {
+ lcm_ = lcm;
+ makerChecker_ = makerChecker;
+ name_ = name;
+ numIterations_ = numIterations;
+ }
+
+ public void messageReceived(LCM lcm, String channel,
LCMDataInputStream ins) {
+ MsgType msg;
+ try {
+ msg =
(MsgType)type_.getConstructor(DataInput.class).newInstance(ins);
+ } catch (java.lang.Exception ex) {
+ done_ = true;
+ return;
+ }
+ if (!makerChecker_.checkReply(msg, iteration_ + 1)) {
+ success_ = false;
+ done_ = true;
+ return;
+ }
+ abortTime_ = System.currentTimeMillis() + 500;
+ iteration_++;
+ if (iteration_ >= numIterations_) {
+ success_ = true;
+ done_ = true;
+ return;
+ }
+ sendMessage();
+ }
+
+ private void sendMessage() {
+ MsgType msg = makerChecker_.makeMessage(iteration_);
+ lcm_.publish("test_" + name_, msg);
+ }
+
+ public boolean run() {
+ lcm_.subscribe("test_" + name_ + "_reply", this);
+ abortTime_ = System.currentTimeMillis() + 500;
+ MsgType msg = makerChecker_.makeMessage(iteration_);
+ lcm_.publish("test_" + name_, msg);
+ type_ = msg.getClass();
+ while(true) {
+ synchronized(this) {
+ if (done_) {
+ break;
+ }
+ }
+ try {
+ Thread.sleep(10);
+ } catch (java.lang.InterruptedException ex) {
+ break;
+ }
+
+ if (System.currentTimeMillis() >= abortTime_) {
+ System.err.printf("Timed out on iteration %d\n",
iteration_);
+ break;
+ }
+ }
+ lcm_.unsubscribe("test_" + name_ + "_reply", this);
+ if (success_) {
+ System.out.println(" OK - " + name_);
+ } else {
+ System.out.printf(" FAIL - %s - iteration %d\n", name_,
iteration_);
+ }
+ return success_;
+ }
+ }
+
+ private class PrimitivesMakerChecker implements
MessageMakerChecker<primitives_t> {
+ public primitives_t makeMessage(int iteration) {
+ primitives_t msg = new primitives_t();
+ int n = iteration;
+ msg.i8 = (byte)(n % 100);
+ msg.i16 = (short)(n * 10);
+ msg.i64 = n * 10000;
+ msg.position[0] = n;
+ msg.position[1] = n;
+ msg.position[2] = n;
+ msg.orientation[0] = n;
+ msg.orientation[1] = n;
+ msg.orientation[2] = n;
+ msg.orientation[3] = n;
+ msg.num_ranges= n;
+ msg.ranges = new short[n];
+ msg.name = String.valueOf(n);
+ msg.enabled = n % 2 == 1;
+ return msg;
+ }
+
+ public boolean checkReply(primitives_t reply, int iteration) {
+ try {
+ int n = iteration;
+ checkField(reply.i8, (byte)(n % 100), "i8");
+ checkField(reply.i16, (short)(n * 10), "i16");
+ checkField((long)reply.i64, (long)(n * 10000), "i64");
+ checkField(reply.position[0], (float)n, "position[0]");
+ checkField(reply.position[1], (float)n, "position[1]");
+ checkField(reply.position[2], (float)n, "position[2]");
+ checkField(reply.orientation[0],
(double)n, "orientation[0]");
+ checkField(reply.orientation[1],
(double)n, "orientation[1]");
+ checkField(reply.orientation[2],
(double)n, "orientation[2]");
+ checkField(reply.orientation[3],
(double)n, "orientation[3]");
+ checkField(reply.num_ranges, n, "num_ranges");
+ for (int i = 0; i < reply.num_ranges; i++) {
+ checkField(reply.ranges[i], (short)i,
String.format("ranges[%d]", i));
+ }
+ checkField(reply.name, String.valueOf(n), "name");
+ checkField(reply.enabled, n % 2 == 1, "enabled");
+ } catch (IllegalArgumentException ex) {
+ ex.printStackTrace(System.err);
+ return false;
+ }
+ return true;
+ }
+ }
+
+ private class PrimitivesListMakerChecker implements
MessageMakerChecker<primitives_list_t> {
+ public primitives_list_t makeMessage(int iteration) {
+ primitives_list_t msg = new primitives_list_t();
+ msg.num_items = iteration;
+ msg.items = new primitives_t[msg.num_items];
+ for (int n = 0; n < msg.num_items; n++) {
+ primitives_t submsg = new primitives_t();
+ msg.items[n] = submsg;
+ submsg.i8 = (byte)(-(n % 100));
+ submsg.i16 = (short)(-n * 100);
+ submsg.i64 = (long)(-n * 10000);
+ submsg.position[0] = -n;
+ submsg.position[1] = -n;
+ submsg.position[2] = -n;
+ submsg.orientation[0] = -n;
+ submsg.orientation[1] = -n;
+ submsg.orientation[2] = -n;
+ submsg.orientation[3] = -n;
+ submsg.num_ranges = n;
+ submsg.ranges = new short[n];
+ for (int j = 0; j < n; j++) {
+ submsg.ranges[j] = (short)-j;
+ }
+ submsg.name = String.format("%d", -n);
+ submsg.enabled = ((n + 1) % 2) == 1;
+ }
+ return msg;
+ }
+
+ public boolean checkReply(primitives_list_t reply, int iteration) {
+ try {
+ checkField(reply.num_items, iteration, "num_items");
+ for (int n = 0; n < iteration; n++) {
+ primitives_t submsg = reply.items[n];
+ String errPrefix = String.format(".items[%d].", n);
+ checkField(submsg.i8, (byte)(-(n % 100)), errPrefix
+ "i8");
+ checkField(submsg.i16, (short)(-n * 10), errPrefix
+ "i8");
+ checkField(submsg.i64, (long)(-n * 10000), errPrefix
+ "i8");
+ checkField(submsg.position[0], (float)-n, errPrefix
+ "position[0]");
+ checkField(submsg.position[1], (float)-n, errPrefix
+ "position[1]");
+ checkField(submsg.position[2], (float)-n, errPrefix
+ "position[2]");
+ checkField(submsg.orientation[0], (double)-n,
errPrefix + "orientation[0]");
+ checkField(submsg.orientation[1], (double)-n,
errPrefix + "orientation[1]");
+ checkField(submsg.orientation[2], (double)-n,
errPrefix + "orientation[2]");
+ checkField(submsg.orientation[3], (double)-n,
errPrefix + "orientation[3]");
+ checkField(submsg.num_ranges, n, errPrefix
+ "num_ranges");
+ for (int i = 0; i < submsg.num_ranges; i++) {
+ checkField(submsg.ranges[i], (short)-i, errPrefix
+ String.format("ranges[%d]", i));
+ }
+ checkField(submsg.name, String.valueOf(-n), errPrefix
+ "name");
+ checkField(submsg.enabled, ((n + 1) % 2) == 1,
errPrefix + "enabled");
+ }
+ } catch (IllegalArgumentException ex) {
+ ex.printStackTrace(System.err);
+ return false;
+ }
+ return true;
+ }
+ }
+
+ public int runTests() {
+ try {
+ setupSubscribers();
+
+ boolean echo_test_success = doEchoTest();
+ if (echo_test_success) {
+ System.out.println(" OK - echo test");
+ } else {
+ System.out.println(" FAIL - echo test");
+ return 1;
+ }
+
+ MessageTester<primitives_t> primitives_tester = new
MessageTester<primitives_t>(
+ lcm_, "lcmtest_primitives_t", new
PrimitivesMakerChecker(), 1000);
+ if (!primitives_tester.run()) {
+ return 1;
+ }
+
+ MessageTester<primitives_list_t> primitives_list_tester = new
MessageTester<primitives_list_t>(
+ lcm_, "lcmtest_primitives_list_t", new
PrimitivesListMakerChecker(), 100);
+ if (!primitives_list_tester.run()) {
+ return 1;
+ }
+ } catch(IOException ex) {
+ System.err.println("IOException");
+ return 1;
+ }
+
+ return 0;
+ }
+
+ public static void main(String[] args) {
+ LcmTestClient client = new LcmTestClient();
+ System.exit(client.runTests());
+ }
+}
=======================================
--- /dev/null
+++ /test/run_unit_tests.py Sun Nov 16 21:14:57 2014 UTC
@@ -0,0 +1,83 @@
+#!/usr/bin/python
+import os
+import shutil
+import subprocess
+import sys
+import unittest
+import xml.etree.ElementTree
+
+import xmlrunner
+
+def run_gtest(name):
+ xml_fname = name.replace("/", "_")
+ subprocess.check_call("%s --gtest_output=xml:lcm_unittest/%s.xml" % \
+ (name, xml_fname), shell=True)
+
+def run_tests():
+ # Python unit tests
+ print("Running Python unit tests")
+ py_results_file = open("lcm_unittest/lcm_python.xml", "w")
+ sys.path.append("python")
+ tests = unittest.TestLoader().discover("python", "*_test.py")
+ runner = xmlrunner.XMLTestRunner(py_results_file)
+ runner.run(tests, "LCM_PYTHON")
+ py_results_file.close()
+
+ # C unit tests
+ print("Running C unit tests")
+ run_gtest("c/memq_test")
+ run_gtest("c/eventlog_test")
+
+ # C++ unit tests
+ print("Running C++ unit tests")
+ run_gtest("cpp/memq_test")
+
+def summarize_results():
+ # Parse and summarize unit test results
+ num_failures = 0
+ num_tests = 0
+ num_errors = 0
+ for bname in os.listdir("lcm_unittest"):
+ fname = "lcm_unittest/%s" % bname
+ tree = xml.etree.ElementTree.parse(fname)
+ root = tree.getroot()
+ for testsuite in root.iter("testsuite"):
+ print("Test suite: %s" % testsuite.attrib["name"])
+ suite_attrib = testsuite.attrib
+ num_failures += int(suite_attrib["failures"])
+ num_tests += int(suite_attrib["tests"])
+ num_errors += int(suite_attrib["tests"])
+ for testcase in testsuite.iter("testcase"):
+ failures = list(testcase.iter("failure"))
+
+ if not failures:
+ print(" OK %s.%s" % (testsuite.attrib["name"],
+ testcase.attrib["name"]))
+ else:
+ print(" FAIL %s.%s" % (testsuite.attrib["name"],
+ testcase.attrib["name"]))
+ for failure in failures:
+ print(failure.text)
+ print("")
+
+ print("Tests passed: %d / %d" % (num_tests - num_failures, num_tests))
+
+ if num_failures:
+ print("Not all tests passed")
+ return 1
+ else:
+ print("All tests passed")
+ return 0
+
+def main():
+ # Setup output directory
+ if os.path.exists("lcm_unittest"):
+ shutil.rmtree("lcm_unittest")
+
+ os.mkdir("lcm_unittest")
+
+ run_tests()
+ return summarize_results()
+
+if __name__ == "__main__":
+ sys.exit(main())
=======================================
--- /.gitignore Sat Nov 8 08:13:01 2014 UTC
+++ /.gitignore Sun Nov 16 21:14:57 2014 UTC
@@ -119,9 +119,10 @@
test/cpp/memq_test
test/gtest/libgtest.a
test/gtest/libgtest_main.a
-test/java/lcmtest/
-test/java/lcmtest2/
+test/java/lcmtest/lcmtest
+test/java/lcmtest/lcmtest2
test/java/lcmtests.jar
+test/java/build
test/python/client.pyc
test/python/lcmtest/
test/python/lcmtest2/
=======================================
--- /lcm-java/make-javadocs.sh Sat Feb 14 22:29:54 2009 UTC
+++ /lcm-java/make-javadocs.sh Sun Nov 16 21:14:57 2014 UTC
@@ -4,7 +4,7 @@
rm -rf javadocs
fi

-CLASSES="lcm/lcm/LCM.java lcm/logging/Log.java lcm/lcm/LCMSubscriber.java
lcm/lcm/LCMEncodable.java lcm/lcm/MessageAggregator.java"
+CLASSES="lcm/lcm/LCM.java lcm/logging/Log.java lcm/lcm/LCMSubscriber.java
lcm/lcm/LCMEncodable.java lcm/lcm/MessageAggregator.java
lcm/lcm/LCMDataInputStream.java lcm/lcm/LCMDataOutputStream.java"

mkdir javadocs
javadoc -d javadocs -link http://java.sun.com/j2se/1.5.0/docs/api $CLASSES
=======================================
--- /test/python/client.py Fri Nov 14 07:03:42 2014 UTC
+++ /test/python/client.py Sun Nov 16 21:14:57 2014 UTC
@@ -237,7 +237,7 @@
check_field(reply.orientation[1], float(n), "orientation[1]");
check_field(reply.orientation[2], float(n), "orientation[2]");
check_field(reply.orientation[3], float(n), "orientation[3]");
- check_field(reply.num_ranges, n, "%d");
+ check_field(reply.num_ranges, n, "num_ranges");
for i in range(n):
check_field(reply.ranges[i], i, "ranges[%d]" % i)
check_field(reply.name, "%d" % n, "name")

==============================================================================
Revision: b8e44c66189d
Author: Albert Huang <ash...@gmail.com>
Date: Sun Nov 16 21:58:55 2014 UTC
Log: add junit, hamcrest sources
add Java LcmTestClient for regression testng
apply fix from mkappeller to terminate UDPMulticastProvider reader
Fixes #95
thread on calling close().

https://code.google.com/p/lcm/source/detail?r=b8e44c66189d

Added:
/test/java/hamcrest-core-1.3/META-INF/MANIFEST.MF
/test/java/hamcrest-core-1.3/org/hamcrest/BaseDescription.java
/test/java/hamcrest-core-1.3/org/hamcrest/BaseMatcher.java
/test/java/hamcrest-core-1.3/org/hamcrest/Condition.java
/test/java/hamcrest-core-1.3/org/hamcrest/CoreMatchers.java
/test/java/hamcrest-core-1.3/org/hamcrest/CustomMatcher.java
/test/java/hamcrest-core-1.3/org/hamcrest/CustomTypeSafeMatcher.java
/test/java/hamcrest-core-1.3/org/hamcrest/Description.java
/test/java/hamcrest-core-1.3/org/hamcrest/DiagnosingMatcher.java
/test/java/hamcrest-core-1.3/org/hamcrest/Factory.java
/test/java/hamcrest-core-1.3/org/hamcrest/FeatureMatcher.java
/test/java/hamcrest-core-1.3/org/hamcrest/Matcher.java
/test/java/hamcrest-core-1.3/org/hamcrest/MatcherAssert.java
/test/java/hamcrest-core-1.3/org/hamcrest/SelfDescribing.java
/test/java/hamcrest-core-1.3/org/hamcrest/StringDescription.java
/test/java/hamcrest-core-1.3/org/hamcrest/TypeSafeDiagnosingMatcher.java
/test/java/hamcrest-core-1.3/org/hamcrest/TypeSafeMatcher.java
/test/java/hamcrest-core-1.3/org/hamcrest/core/AllOf.java
/test/java/hamcrest-core-1.3/org/hamcrest/core/AnyOf.java
/test/java/hamcrest-core-1.3/org/hamcrest/core/CombinableMatcher.java
/test/java/hamcrest-core-1.3/org/hamcrest/core/DescribedAs.java
/test/java/hamcrest-core-1.3/org/hamcrest/core/Every.java
/test/java/hamcrest-core-1.3/org/hamcrest/core/Is.java
/test/java/hamcrest-core-1.3/org/hamcrest/core/IsAnything.java
/test/java/hamcrest-core-1.3/org/hamcrest/core/IsCollectionContaining.java
/test/java/hamcrest-core-1.3/org/hamcrest/core/IsEqual.java
/test/java/hamcrest-core-1.3/org/hamcrest/core/IsInstanceOf.java
/test/java/hamcrest-core-1.3/org/hamcrest/core/IsNot.java
/test/java/hamcrest-core-1.3/org/hamcrest/core/IsNull.java
/test/java/hamcrest-core-1.3/org/hamcrest/core/IsSame.java
/test/java/hamcrest-core-1.3/org/hamcrest/core/ShortcutCombination.java
/test/java/hamcrest-core-1.3/org/hamcrest/core/StringContains.java
/test/java/hamcrest-core-1.3/org/hamcrest/core/StringEndsWith.java
/test/java/hamcrest-core-1.3/org/hamcrest/core/StringStartsWith.java
/test/java/hamcrest-core-1.3/org/hamcrest/core/SubstringMatcher.java
/test/java/hamcrest-core-1.3/org/hamcrest/core/package.html
/test/java/hamcrest-core-1.3/org/hamcrest/internal/ArrayIterator.java

/test/java/hamcrest-core-1.3/org/hamcrest/internal/ReflectiveTypeFinder.java
/test/java/hamcrest-core-1.3/org/hamcrest/internal/SelfDescribingValue.java

/test/java/hamcrest-core-1.3/org/hamcrest/internal/SelfDescribingValueIterator.java
/test/java/hamcrest-core-1.3/org/hamcrest/package.html
/test/java/junit-4.11/META-INF/MANIFEST.MF
/test/java/junit-4.11/junit/extensions/ActiveTestSuite.java
/test/java/junit-4.11/junit/extensions/RepeatedTest.java
/test/java/junit-4.11/junit/extensions/TestDecorator.java
/test/java/junit-4.11/junit/extensions/TestSetup.java
/test/java/junit-4.11/junit/extensions/package-info.java
/test/java/junit-4.11/junit/framework/Assert.java
/test/java/junit-4.11/junit/framework/AssertionFailedError.java
/test/java/junit-4.11/junit/framework/ComparisonCompactor.java
/test/java/junit-4.11/junit/framework/ComparisonFailure.java
/test/java/junit-4.11/junit/framework/JUnit4TestAdapter.java
/test/java/junit-4.11/junit/framework/JUnit4TestAdapterCache.java
/test/java/junit-4.11/junit/framework/JUnit4TestCaseFacade.java
/test/java/junit-4.11/junit/framework/Protectable.java
/test/java/junit-4.11/junit/framework/Test.java
/test/java/junit-4.11/junit/framework/TestCase.java
/test/java/junit-4.11/junit/framework/TestFailure.java
/test/java/junit-4.11/junit/framework/TestListener.java
/test/java/junit-4.11/junit/framework/TestResult.java
/test/java/junit-4.11/junit/framework/TestSuite.java
/test/java/junit-4.11/junit/framework/package-info.java
/test/java/junit-4.11/junit/runner/BaseTestRunner.java
/test/java/junit-4.11/junit/runner/TestRunListener.java
/test/java/junit-4.11/junit/runner/Version.java
/test/java/junit-4.11/junit/runner/Version.java.template
/test/java/junit-4.11/junit/runner/logo.gif
/test/java/junit-4.11/junit/runner/package-info.java
/test/java/junit-4.11/junit/runner/smalllogo.gif
/test/java/junit-4.11/junit/textui/ResultPrinter.java
/test/java/junit-4.11/junit/textui/TestRunner.java
/test/java/junit-4.11/junit/textui/package-info.java
/test/java/junit-4.11/org/junit/After.java
/test/java/junit-4.11/org/junit/AfterClass.java
/test/java/junit-4.11/org/junit/Assert.java
/test/java/junit-4.11/org/junit/Assume.java
/test/java/junit-4.11/org/junit/Before.java
/test/java/junit-4.11/org/junit/BeforeClass.java
/test/java/junit-4.11/org/junit/ClassRule.java
/test/java/junit-4.11/org/junit/ComparisonFailure.java
/test/java/junit-4.11/org/junit/FixMethodOrder.java
/test/java/junit-4.11/org/junit/Ignore.java
/test/java/junit-4.11/org/junit/Rule.java
/test/java/junit-4.11/org/junit/Test.java
/test/java/junit-4.11/org/junit/experimental/ParallelComputer.java
/test/java/junit-4.11/org/junit/experimental/categories/Categories.java
/test/java/junit-4.11/org/junit/experimental/categories/Category.java

/test/java/junit-4.11/org/junit/experimental/max/CouldNotReadCoreException.java
/test/java/junit-4.11/org/junit/experimental/max/MaxCore.java
/test/java/junit-4.11/org/junit/experimental/max/MaxHistory.java
/test/java/junit-4.11/org/junit/experimental/results/FailureList.java
/test/java/junit-4.11/org/junit/experimental/results/PrintableResult.java
/test/java/junit-4.11/org/junit/experimental/results/ResultMatchers.java
/test/java/junit-4.11/org/junit/experimental/runners/Enclosed.java
/test/java/junit-4.11/org/junit/experimental/theories/DataPoint.java
/test/java/junit-4.11/org/junit/experimental/theories/DataPoints.java

/test/java/junit-4.11/org/junit/experimental/theories/ParameterSignature.java

/test/java/junit-4.11/org/junit/experimental/theories/ParameterSupplier.java

/test/java/junit-4.11/org/junit/experimental/theories/ParametersSuppliedBy.java

/test/java/junit-4.11/org/junit/experimental/theories/PotentialAssignment.java
/test/java/junit-4.11/org/junit/experimental/theories/Theories.java
/test/java/junit-4.11/org/junit/experimental/theories/Theory.java

/test/java/junit-4.11/org/junit/experimental/theories/internal/AllMembersSupplier.java

/test/java/junit-4.11/org/junit/experimental/theories/internal/Assignments.java

/test/java/junit-4.11/org/junit/experimental/theories/internal/ParameterizedAssertionError.java

/test/java/junit-4.11/org/junit/experimental/theories/suppliers/TestedOn.java

/test/java/junit-4.11/org/junit/experimental/theories/suppliers/TestedOnSupplier.java
/test/java/junit-4.11/org/junit/internal/ArrayComparisonFailure.java
/test/java/junit-4.11/org/junit/internal/AssumptionViolatedException.java
/test/java/junit-4.11/org/junit/internal/ComparisonCriteria.java
/test/java/junit-4.11/org/junit/internal/ExactComparisonCriteria.java
/test/java/junit-4.11/org/junit/internal/InexactComparisonCriteria.java
/test/java/junit-4.11/org/junit/internal/JUnitSystem.java
/test/java/junit-4.11/org/junit/internal/MethodSorter.java
/test/java/junit-4.11/org/junit/internal/RealSystem.java
/test/java/junit-4.11/org/junit/internal/TextListener.java

/test/java/junit-4.11/org/junit/internal/builders/AllDefaultPossibilitiesBuilder.java
/test/java/junit-4.11/org/junit/internal/builders/AnnotatedBuilder.java
/test/java/junit-4.11/org/junit/internal/builders/IgnoredBuilder.java
/test/java/junit-4.11/org/junit/internal/builders/IgnoredClassRunner.java
/test/java/junit-4.11/org/junit/internal/builders/JUnit3Builder.java
/test/java/junit-4.11/org/junit/internal/builders/JUnit4Builder.java
/test/java/junit-4.11/org/junit/internal/builders/NullBuilder.java
/test/java/junit-4.11/org/junit/internal/builders/SuiteMethodBuilder.java

/test/java/junit-4.11/org/junit/internal/matchers/StacktracePrintingMatcher.java

/test/java/junit-4.11/org/junit/internal/matchers/ThrowableCauseMatcher.java

/test/java/junit-4.11/org/junit/internal/matchers/ThrowableMessageMatcher.java
/test/java/junit-4.11/org/junit/internal/matchers/TypeSafeMatcher.java
/test/java/junit-4.11/org/junit/internal/requests/ClassRequest.java
/test/java/junit-4.11/org/junit/internal/requests/FilterRequest.java
/test/java/junit-4.11/org/junit/internal/requests/SortingRequest.java
/test/java/junit-4.11/org/junit/internal/requests/package-info.java
/test/java/junit-4.11/org/junit/internal/runners/ClassRoadie.java
/test/java/junit-4.11/org/junit/internal/runners/ErrorReportingRunner.java
/test/java/junit-4.11/org/junit/internal/runners/FailedBefore.java
/test/java/junit-4.11/org/junit/internal/runners/InitializationError.java
/test/java/junit-4.11/org/junit/internal/runners/JUnit38ClassRunner.java
/test/java/junit-4.11/org/junit/internal/runners/JUnit4ClassRunner.java
/test/java/junit-4.11/org/junit/internal/runners/MethodRoadie.java
/test/java/junit-4.11/org/junit/internal/runners/MethodValidator.java
/test/java/junit-4.11/org/junit/internal/runners/SuiteMethod.java
/test/java/junit-4.11/org/junit/internal/runners/TestClass.java
/test/java/junit-4.11/org/junit/internal/runners/TestMethod.java

/test/java/junit-4.11/org/junit/internal/runners/model/EachTestNotifier.java

/test/java/junit-4.11/org/junit/internal/runners/model/MultipleFailureException.java

/test/java/junit-4.11/org/junit/internal/runners/model/ReflectiveCallable.java
/test/java/junit-4.11/org/junit/internal/runners/package-info.java

/test/java/junit-4.11/org/junit/internal/runners/rules/RuleFieldValidator.java

/test/java/junit-4.11/org/junit/internal/runners/statements/ExpectException.java
/test/java/junit-4.11/org/junit/internal/runners/statements/Fail.java

/test/java/junit-4.11/org/junit/internal/runners/statements/FailOnTimeout.java

/test/java/junit-4.11/org/junit/internal/runners/statements/InvokeMethod.java
/test/java/junit-4.11/org/junit/internal/runners/statements/RunAfters.java
/test/java/junit-4.11/org/junit/internal/runners/statements/RunBefores.java
/test/java/junit-4.11/org/junit/matchers/JUnitMatchers.java
/test/java/junit-4.11/org/junit/matchers/package-info.java
/test/java/junit-4.11/org/junit/package-info.java
/test/java/junit-4.11/org/junit/rules/ErrorCollector.java
/test/java/junit-4.11/org/junit/rules/ExpectedException.java
/test/java/junit-4.11/org/junit/rules/ExpectedExceptionMatcherBuilder.java
/test/java/junit-4.11/org/junit/rules/ExternalResource.java
/test/java/junit-4.11/org/junit/rules/MethodRule.java
/test/java/junit-4.11/org/junit/rules/RuleChain.java
/test/java/junit-4.11/org/junit/rules/RunRules.java
/test/java/junit-4.11/org/junit/rules/TemporaryFolder.java
/test/java/junit-4.11/org/junit/rules/TestName.java
/test/java/junit-4.11/org/junit/rules/TestRule.java
/test/java/junit-4.11/org/junit/rules/TestWatcher.java
/test/java/junit-4.11/org/junit/rules/TestWatchman.java
/test/java/junit-4.11/org/junit/rules/Timeout.java
/test/java/junit-4.11/org/junit/rules/Verifier.java
/test/java/junit-4.11/org/junit/runner/Computer.java
/test/java/junit-4.11/org/junit/runner/Describable.java
/test/java/junit-4.11/org/junit/runner/Description.java
/test/java/junit-4.11/org/junit/runner/JUnitCore.java
/test/java/junit-4.11/org/junit/runner/Request.java
/test/java/junit-4.11/org/junit/runner/Result.java
/test/java/junit-4.11/org/junit/runner/RunWith.java
/test/java/junit-4.11/org/junit/runner/Runner.java
/test/java/junit-4.11/org/junit/runner/manipulation/Filter.java
/test/java/junit-4.11/org/junit/runner/manipulation/Filterable.java

/test/java/junit-4.11/org/junit/runner/manipulation/NoTestsRemainException.java
/test/java/junit-4.11/org/junit/runner/manipulation/Sortable.java
/test/java/junit-4.11/org/junit/runner/manipulation/Sorter.java
/test/java/junit-4.11/org/junit/runner/manipulation/package-info.java
/test/java/junit-4.11/org/junit/runner/notification/Failure.java
/test/java/junit-4.11/org/junit/runner/notification/RunListener.java
/test/java/junit-4.11/org/junit/runner/notification/RunNotifier.java

/test/java/junit-4.11/org/junit/runner/notification/StoppedByUserException.java
/test/java/junit-4.11/org/junit/runner/notification/package-info.java
/test/java/junit-4.11/org/junit/runner/package-info.java
/test/java/junit-4.11/org/junit/runners/AllTests.java
/test/java/junit-4.11/org/junit/runners/BlockJUnit4ClassRunner.java
/test/java/junit-4.11/org/junit/runners/JUnit4.java
/test/java/junit-4.11/org/junit/runners/MethodSorters.java
/test/java/junit-4.11/org/junit/runners/Parameterized.java
/test/java/junit-4.11/org/junit/runners/ParentRunner.java
/test/java/junit-4.11/org/junit/runners/Suite.java
/test/java/junit-4.11/org/junit/runners/model/FrameworkField.java
/test/java/junit-4.11/org/junit/runners/model/FrameworkMember.java
/test/java/junit-4.11/org/junit/runners/model/FrameworkMethod.java
/test/java/junit-4.11/org/junit/runners/model/InitializationError.java
/test/java/junit-4.11/org/junit/runners/model/MultipleFailureException.java

/test/java/junit-4.11/org/junit/runners/model/NoGenericTypeParametersValidator.java
/test/java/junit-4.11/org/junit/runners/model/RunnerBuilder.java
/test/java/junit-4.11/org/junit/runners/model/RunnerScheduler.java
/test/java/junit-4.11/org/junit/runners/model/Statement.java
/test/java/junit-4.11/org/junit/runners/model/TestClass.java
/test/java/junit-4.11/org/junit/runners/package-info.java
/test/java/lcmtest/TestUDPMulticastProvider.java
Modified:
/.gitignore
/lcm-java/lcm/lcm/UDPMulticastProvider.java
/test/Makefile
/test/README
/test/java/Makefile
/test/java/build.xml
/test/java/lcmtest/LcmTestClient.java
/test/run_client_server_tests.py
/test/run_unit_tests.py

=======================================
--- /dev/null
+++ /test/java/hamcrest-core-1.3/META-INF/MANIFEST.MF Sun Nov 16 21:58:55
2014 UTC
@@ -0,0 +1,9 @@
+Manifest-Version: 1.0
+Ant-Version: Apache Ant 1.8.1
+Created-By: 1.6.0_33-b03 (Sun Microsystems Inc.)
+Implementation-Title: hamcrest-core
+Implementation-Vendor: hamcrest.org
+Implementation-Version: 1.3
+Built-By: tom
+Built-Date: 2012-07-09 19:49:34
+
=======================================
--- /dev/null
+++ /test/java/hamcrest-core-1.3/org/hamcrest/BaseDescription.java Sun Nov
16 21:58:55 2014 UTC
@@ -0,0 +1,144 @@
+package org.hamcrest;
+
+import static java.lang.String.valueOf;
+
+import java.util.Arrays;
+import java.util.Iterator;
+
+import org.hamcrest.internal.ArrayIterator;
+import org.hamcrest.internal.SelfDescribingValueIterator;
+
+/**
+ * A {@link Description} that is stored as a string.
+ */
+public abstract class BaseDescription implements Description {
+
+ @Override
+ public Description appendText(String text) {
+ append(text);
+ return this;
+ }
+
+ @Override
+ public Description appendDescriptionOf(SelfDescribing value) {
+ value.describeTo(this);
+ return this;
+ }
+
+ @Override
+ public Description appendValue(Object value) {
+ if (value == null) {
+ append("null");
+ } else if (value instanceof String) {
+ toJavaSyntax((String) value);
+ } else if (value instanceof Character) {
+ append('"');
+ toJavaSyntax((Character) value);
+ append('"');
+ } else if (value instanceof Short) {
+ append('<');
+ append(descriptionOf(value));
+ append("s>");
+ } else if (value instanceof Long) {
+ append('<');
+ append(descriptionOf(value));
+ append("L>");
+ } else if (value instanceof Float) {
+ append('<');
+ append(descriptionOf(value));
+ append("F>");
+ } else if (value.getClass().isArray()) {
+ appendValueList("[",", ","]", new ArrayIterator(value));
+ } else {
+ append('<');
+ append(descriptionOf(value));
+ append('>');
+ }
+ return this;
+ }
+
+ private String descriptionOf(Object value) {
+ try {
+ return valueOf(value);
+ }
+ catch (Exception e) {
+ return value.getClass().getName() + "@" +
Integer.toHexString(value.hashCode());
+ }
+ }
+
+ @Override
+ public <T> Description appendValueList(String start, String separator,
String end, T... values) {
+ return appendValueList(start, separator, end,
Arrays.asList(values));
+ }
+
+ @Override
+ public <T> Description appendValueList(String start, String separator,
String end, Iterable<T> values) {
+ return appendValueList(start, separator, end, values.iterator());
+ }
+
+ private <T> Description appendValueList(String start, String
separator, String end, Iterator<T> values) {
+ return appendList(start, separator, end, new
SelfDescribingValueIterator<T>(values));
+ }
+
+ @Override
+ public Description appendList(String start, String separator, String
end, Iterable<? extends SelfDescribing> values) {
+ return appendList(start, separator, end, values.iterator());
+ }
+
+ private Description appendList(String start, String separator, String
end, Iterator<? extends SelfDescribing> i) {
+ boolean separate = false;
+
+ append(start);
+ while (i.hasNext()) {
+ if (separate) append(separator);
+ appendDescriptionOf(i.next());
+ separate = true;
+ }
+ append(end);
+
+ return this;
+ }
+
+ /**
+ * Append the String <var>str</var> to the description.
+ * The default implementation passes every character to {@link
#append(char)}.
+ * Override in subclasses to provide an efficient implementation.
+ */
+ protected void append(String str) {
+ for (int i = 0; i < str.length(); i++) {
+ append(str.charAt(i));
+ }
+ }
+
+ /**
+ * Append the char <var>c</var> to the description.
+ */
+ protected abstract void append(char c);
+
+ private void toJavaSyntax(String unformatted) {
+ append('"');
+ for (int i = 0; i < unformatted.length(); i++) {
+ toJavaSyntax(unformatted.charAt(i));
+ }
+ append('"');
+ }
+
+ private void toJavaSyntax(char ch) {
+ switch (ch) {
+ case '"':
+ append("\\\"");
+ break;
+ case '\n':
+ append("\\n");
+ break;
+ case '\r':
+ append("\\r");
+ break;
+ case '\t':
+ append("\\t");
+ break;
+ default:
+ append(ch);
+ }
+ }
+}
=======================================
--- /dev/null
+++ /test/java/hamcrest-core-1.3/org/hamcrest/BaseMatcher.java Sun Nov 16
21:58:55 2014 UTC
@@ -0,0 +1,30 @@
+/* Copyright (c) 2000-2006 hamcrest.org
+ */
+package org.hamcrest;
+
+/**
+ * BaseClass for all Matcher implementations.
+ *
+ * @see Matcher
+ */
+public abstract class BaseMatcher<T> implements Matcher<T> {
+
+ /**
+ * @see Matcher#_dont_implement_Matcher___instead_extend_BaseMatcher_()
+ */
+ @Override
+ @Deprecated
+ public final void
_dont_implement_Matcher___instead_extend_BaseMatcher_() {
+ // See Matcher interface for an explanation of this method.
+ }
+
+ @Override
+ public void describeMismatch(Object item, Description description) {
+ description.appendText("was ").appendValue(item);
+ }
+
+ @Override
+ public String toString() {
+ return StringDescription.toString(this);
+ }
+}
=======================================
--- /dev/null
+++ /test/java/hamcrest-core-1.3/org/hamcrest/Condition.java Sun Nov 16
21:58:55 2014 UTC
@@ -0,0 +1,69 @@
+package org.hamcrest;
+
+/**
+ * A Condition implements part of a multi-step match. We sometimes need to
write matchers
+ * that have a sequence of steps, where each step depends on the result of
the previous
+ * step and we can stop processing as soon as a step fails. These classes
provide
+ * infrastructure for writing such a sequence.
+ *
+ * Based on https://github.com/npryce/maybe-java
+ * @author Steve Freeman 2012 http://www.hamcrest.com
+ */
+
+public abstract class Condition<T> {
+ public static final NotMatched<Object> NOT_MATCHED = new
NotMatched<Object>();
+
+ public interface Step<I, O> {
+ Condition<O> apply(I value, Description mismatch);
+ }
+
+ private Condition() { }
+
+ public abstract boolean matching(Matcher<T> match, String message);
+ public abstract <U> Condition<U> and(Step<? super T, U> mapping);
+
+ public final boolean matching(Matcher<T> match) { return
matching(match, ""); }
+ public final <U> Condition<U> then(Step<? super T, U> mapping) {
return and(mapping); }
+
+ @SuppressWarnings("unchecked")
+ public static <T> Condition<T> notMatched() {
+ return (Condition<T>) NOT_MATCHED;
+ }
+
+ public static <T> Condition<T> matched(final T theValue, final
Description mismatch) {
+ return new Matched<T>(theValue, mismatch);
+ }
+
+ private static final class Matched<T> extends Condition<T> {
+ private final T theValue;
+ private final Description mismatch;
+
+ private Matched(T theValue, Description mismatch) {
+ this.theValue = theValue;
+ this.mismatch = mismatch;
+ }
+
+ @Override
+ public boolean matching(Matcher<T> matcher, String message) {
+ if (matcher.matches(theValue)) {
+ return true;
+ }
+ mismatch.appendText(message);
+ matcher.describeMismatch(theValue, mismatch);
+ return false;
+ }
+
+ @Override
+ public <U> Condition<U> and(Step<? super T, U> next) {
+ return next.apply(theValue, mismatch);
+ }
+ }
+
+ private static final class NotMatched<T> extends Condition<T> {
+ @Override public boolean matching(Matcher<T> match, String
message) { return false; }
+
+ @Override public <U> Condition<U> and(Step<? super T, U> mapping) {
+ return notMatched();
+ }
+ }
+}
=======================================
--- /dev/null
+++ /test/java/hamcrest-core-1.3/org/hamcrest/CoreMatchers.java Sun Nov 16
21:58:55 2014 UTC
@@ -0,0 +1,533 @@
+// Generated source.
+package org.hamcrest;
+
+public class CoreMatchers {
+
+ /**
+ * Creates a matcher that matches if the examined object matches
<b>ALL</b> of the specified matchers.
+ * <p/>
+ * For example:
+ * <pre>assertThat("myValue", allOf(startsWith("my"),
containsString("Val")))</pre>
+ */
+ public static <T> org.hamcrest.Matcher<T>
allOf(java.lang.Iterable<org.hamcrest.Matcher<? super T>> matchers) {
+ return org.hamcrest.core.AllOf.<T>allOf(matchers);
+ }
+
+ /**
+ * Creates a matcher that matches if the examined object matches
<b>ALL</b> of the specified matchers.
+ * <p/>
+ * For example:
+ * <pre>assertThat("myValue", allOf(startsWith("my"),
containsString("Val")))</pre>
+ */
+ public static <T> org.hamcrest.Matcher<T> allOf(org.hamcrest.Matcher<?
super T>... matchers) {
+ return org.hamcrest.core.AllOf.<T>allOf(matchers);
+ }
+
+ /**
+ * Creates a matcher that matches if the examined object matches
<b>ALL</b> of the specified matchers.
+ * <p/>
+ * For example:
+ * <pre>assertThat("myValue", allOf(startsWith("my"),
containsString("Val")))</pre>
+ */
+ public static <T> org.hamcrest.Matcher<T> allOf(org.hamcrest.Matcher<?
super T> first, org.hamcrest.Matcher<? super T> second) {
+ return org.hamcrest.core.AllOf.<T>allOf(first, second);
+ }
+
+ /**
+ * Creates a matcher that matches if the examined object matches
<b>ALL</b> of the specified matchers.
+ * <p/>
+ * For example:
+ * <pre>assertThat("myValue", allOf(startsWith("my"),
containsString("Val")))</pre>
+ */
+ public static <T> org.hamcrest.Matcher<T> allOf(org.hamcrest.Matcher<?
super T> first, org.hamcrest.Matcher<? super T> second,
org.hamcrest.Matcher<? super T> third) {
+ return org.hamcrest.core.AllOf.<T>allOf(first, second, third);
+ }
+
+ /**
+ * Creates a matcher that matches if the examined object matches
<b>ALL</b> of the specified matchers.
+ * <p/>
+ * For example:
+ * <pre>assertThat("myValue", allOf(startsWith("my"),
containsString("Val")))</pre>
+ */
+ public static <T> org.hamcrest.Matcher<T> allOf(org.hamcrest.Matcher<?
super T> first, org.hamcrest.Matcher<? super T> second,
org.hamcrest.Matcher<? super T> third, org.hamcrest.Matcher<? super T>
fourth) {
+ return org.hamcrest.core.AllOf.<T>allOf(first, second, third, fourth);
+ }
+
+ /**
+ * Creates a matcher that matches if the examined object matches
<b>ALL</b> of the specified matchers.
+ * <p/>
+ * For example:
+ * <pre>assertThat("myValue", allOf(startsWith("my"),
containsString("Val")))</pre>
+ */
+ public static <T> org.hamcrest.Matcher<T> allOf(org.hamcrest.Matcher<?
super T> first, org.hamcrest.Matcher<? super T> second,
org.hamcrest.Matcher<? super T> third, org.hamcrest.Matcher<? super T>
fourth, org.hamcrest.Matcher<? super T> fifth) {
+ return org.hamcrest.core.AllOf.<T>allOf(first, second, third, fourth,
fifth);
+ }
+
+ /**
+ * Creates a matcher that matches if the examined object matches
<b>ALL</b> of the specified matchers.
+ * <p/>
+ * For example:
+ * <pre>assertThat("myValue", allOf(startsWith("my"),
containsString("Val")))</pre>
+ */
+ public static <T> org.hamcrest.Matcher<T> allOf(org.hamcrest.Matcher<?
super T> first, org.hamcrest.Matcher<? super T> second,
org.hamcrest.Matcher<? super T> third, org.hamcrest.Matcher<? super T>
fourth, org.hamcrest.Matcher<? super T> fifth, org.hamcrest.Matcher<? super
T> sixth) {
+ return org.hamcrest.core.AllOf.<T>allOf(first, second, third, fourth,
fifth, sixth);
+ }
+
+ /**
+ * Creates a matcher that matches if the examined object matches
<b>ANY</b> of the specified matchers.
+ * <p/>
+ * For example:
+ * <pre>assertThat("myValue", anyOf(startsWith("foo"),
containsString("Val")))</pre>
+ */
+ public static <T> org.hamcrest.core.AnyOf<T>
anyOf(java.lang.Iterable<org.hamcrest.Matcher<? super T>> matchers) {
+ return org.hamcrest.core.AnyOf.<T>anyOf(matchers);
+ }
+
+ /**
+ * Creates a matcher that matches if the examined object matches
<b>ANY</b> of the specified matchers.
+ * <p/>
+ * For example:
+ * <pre>assertThat("myValue", anyOf(startsWith("foo"),
containsString("Val")))</pre>
+ */
+ public static <T> org.hamcrest.core.AnyOf<T>
anyOf(org.hamcrest.Matcher<T> first, org.hamcrest.Matcher<? super T>
second, org.hamcrest.Matcher<? super T> third) {
+ return org.hamcrest.core.AnyOf.<T>anyOf(first, second, third);
+ }
+
+ /**
+ * Creates a matcher that matches if the examined object matches
<b>ANY</b> of the specified matchers.
+ * <p/>
+ * For example:
+ * <pre>assertThat("myValue", anyOf(startsWith("foo"),
containsString("Val")))</pre>
+ */
+ public static <T> org.hamcrest.core.AnyOf<T>
anyOf(org.hamcrest.Matcher<T> first, org.hamcrest.Matcher<? super T>
second, org.hamcrest.Matcher<? super T> third, org.hamcrest.Matcher<? super
T> fourth) {
+ return org.hamcrest.core.AnyOf.<T>anyOf(first, second, third, fourth);
+ }
+
+ /**
+ * Creates a matcher that matches if the examined object matches
<b>ANY</b> of the specified matchers.
+ * <p/>
+ * For example:
+ * <pre>assertThat("myValue", anyOf(startsWith("foo"),
containsString("Val")))</pre>
+ */
+ public static <T> org.hamcrest.core.AnyOf<T>
anyOf(org.hamcrest.Matcher<T> first, org.hamcrest.Matcher<? super T>
second, org.hamcrest.Matcher<? super T> third, org.hamcrest.Matcher<? super
T> fourth, org.hamcrest.Matcher<? super T> fifth) {
+ return org.hamcrest.core.AnyOf.<T>anyOf(first, second, third, fourth,
fifth);
+ }
+
+ /**
+ * Creates a matcher that matches if the examined object matches
<b>ANY</b> of the specified matchers.
+ * <p/>
+ * For example:
+ * <pre>assertThat("myValue", anyOf(startsWith("foo"),
containsString("Val")))</pre>
+ */
+ public static <T> org.hamcrest.core.AnyOf<T>
anyOf(org.hamcrest.Matcher<T> first, org.hamcrest.Matcher<? super T>
second, org.hamcrest.Matcher<? super T> third, org.hamcrest.Matcher<? super
T> fourth, org.hamcrest.Matcher<? super T> fifth, org.hamcrest.Matcher<?
super T> sixth) {
+ return org.hamcrest.core.AnyOf.<T>anyOf(first, second, third, fourth,
fifth, sixth);
+ }
+
+ /**
+ * Creates a matcher that matches if the examined object matches
<b>ANY</b> of the specified matchers.
+ * <p/>
+ * For example:
+ * <pre>assertThat("myValue", anyOf(startsWith("foo"),
containsString("Val")))</pre>
+ */
+ public static <T> org.hamcrest.core.AnyOf<T>
anyOf(org.hamcrest.Matcher<T> first, org.hamcrest.Matcher<? super T>
second) {
+ return org.hamcrest.core.AnyOf.<T>anyOf(first, second);
+ }
+
+ /**
+ * Creates a matcher that matches if the examined object matches
<b>ANY</b> of the specified matchers.
+ * <p/>
+ * For example:
+ * <pre>assertThat("myValue", anyOf(startsWith("foo"),
containsString("Val")))</pre>
+ */
+ public static <T> org.hamcrest.core.AnyOf<T>
anyOf(org.hamcrest.Matcher<? super T>... matchers) {
+ return org.hamcrest.core.AnyOf.<T>anyOf(matchers);
+ }
+
+ /**
+ * Creates a matcher that matches when both of the specified matchers
match the examined object.
+ * <p/>
+ * For example:
+ * <pre>assertThat("fab",
both(containsString("a")).and(containsString("b")))</pre>
+ */
+ public static <LHS>
org.hamcrest.core.CombinableMatcher.CombinableBothMatcher<LHS>
both(org.hamcrest.Matcher<? super LHS> matcher) {
+ return org.hamcrest.core.CombinableMatcher.<LHS>both(matcher);
+ }
+
+ /**
+ * Creates a matcher that matches when either of the specified matchers
match the examined object.
+ * <p/>
+ * For example:
+ * <pre>assertThat("fan",
either(containsString("a")).and(containsString("b")))</pre>
+ */
+ public static <LHS>
org.hamcrest.core.CombinableMatcher.CombinableEitherMatcher<LHS>
either(org.hamcrest.Matcher<? super LHS> matcher) {
+ return org.hamcrest.core.CombinableMatcher.<LHS>either(matcher);
+ }
+
+ /**
+ * Wraps an existing matcher, overriding its description with that
specified. All other functions are
+ * delegated to the decorated matcher, including its mismatch
description.
+ * <p/>
+ * For example:
+ * <pre>describedAs("a big decimal equal to %0", equalTo(myBigDecimal),
myBigDecimal.toPlainString())</pre>
+ *
+ * @param description
+ * the new description for the wrapped matcher
+ * @param matcher
+ * the matcher to wrap
+ * @param values
+ * optional values to insert into the tokenised description
+ */
+ public static <T> org.hamcrest.Matcher<T> describedAs(java.lang.String
description, org.hamcrest.Matcher<T> matcher, java.lang.Object... values) {
+ return org.hamcrest.core.DescribedAs.<T>describedAs(description,
matcher, values);
+ }
+
+ /**
+ * Creates a matcher for {@link Iterable}s that only matches when a
single pass over the
+ * examined {@link Iterable} yields items that are all matched by the
specified
+ * <code>itemMatcher</code>.
+ * <p/>
+ * For example:
+ * <pre>assertThat(Arrays.asList("bar", "baz"),
everyItem(startsWith("ba")))</pre>
+ *
+ * @param itemMatcher
+ * the matcher to apply to every item provided by the examined
{@link Iterable}
+ */
+ public static <U> org.hamcrest.Matcher<java.lang.Iterable<U>>
everyItem(org.hamcrest.Matcher<U> itemMatcher) {
+ return org.hamcrest.core.Every.<U>everyItem(itemMatcher);
+ }
+
+ /**
+ * A shortcut to the frequently used <code>is(equalTo(x))</code>.
+ * <p/>
+ * For example:
+ * <pre>assertThat(cheese, is(smelly))</pre>
+ * instead of:
+ * <pre>assertThat(cheese, is(equalTo(smelly)))</pre>
+ */
+ public static <T> org.hamcrest.Matcher<T> is(T value) {
+ return org.hamcrest.core.Is.<T>is(value);
+ }
+
+ /**
+ * Decorates another Matcher, retaining its behaviour, but allowing tests
+ * to be slightly more expressive.
+ * <p/>
+ * For example:
+ * <pre>assertThat(cheese, is(equalTo(smelly)))</pre>
+ * instead of:
+ * <pre>assertThat(cheese, equalTo(smelly))</pre>
+ */
+ public static <T> org.hamcrest.Matcher<T> is(org.hamcrest.Matcher<T>
matcher) {
+ return org.hamcrest.core.Is.<T>is(matcher);
+ }
+
+ /**
+ * A shortcut to the frequently used
<code>is(instanceOf(SomeClass.class))</code>.
+ * <p/>
+ * For example:
+ * <pre>assertThat(cheese, is(Cheddar.class))</pre>
+ * instead of:
+ * <pre>assertThat(cheese, is(instanceOf(Cheddar.class)))</pre>
+ *
+ * @deprecated use isA(Class<T> type) instead.
+ */
+ public static <T> org.hamcrest.Matcher<T> is(java.lang.Class<T> type) {
+ return org.hamcrest.core.Is.<T>is(type);
+ }
+
+ /**
+ * A shortcut to the frequently used
<code>is(instanceOf(SomeClass.class))</code>.
+ * <p/>
+ * For example:
+ * <pre>assertThat(cheese, isA(Cheddar.class))</pre>
+ * instead of:
+ * <pre>assertThat(cheese, is(instanceOf(Cheddar.class)))</pre>
+ */
+ public static <T> org.hamcrest.Matcher<T> isA(java.lang.Class<T> type) {
+ return org.hamcrest.core.Is.<T>isA(type);
+ }
+
+ /**
+ * Creates a matcher that always matches, regardless of the examined
object.
+ */
+ public static org.hamcrest.Matcher<java.lang.Object> anything() {
+ return org.hamcrest.core.IsAnything.anything();
+ }
+
+ /**
+ * Creates a matcher that always matches, regardless of the examined
object, but describes
+ * itself with the specified {@link String}.
+ *
+ * @param description
+ * a meaningful {@link String} used when describing itself
+ */
+ public static org.hamcrest.Matcher<java.lang.Object>
anything(java.lang.String description) {
+ return org.hamcrest.core.IsAnything.anything(description);
+ }
+
+ /**
+ * Creates a matcher for {@link Iterable}s that only matches when a
single pass over the
+ * examined {@link Iterable} yields at least one item that is equal to
the specified
+ * <code>item</code>. Whilst matching, the traversal of the examined
{@link Iterable}
+ * will stop as soon as a matching item is found.
+ * <p/>
+ * For example:
+ * <pre>assertThat(Arrays.asList("foo", "bar"), hasItem("bar"))</pre>
+ *
+ * @param item
+ * the item to compare against the items provided by the examined
{@link Iterable}
+ */
+ public static <T> org.hamcrest.Matcher<java.lang.Iterable<? super T>>
hasItem(T item) {
+ return org.hamcrest.core.IsCollectionContaining.<T>hasItem(item);
+ }
+
+ /**
+ * Creates a matcher for {@link Iterable}s that only matches when a
single pass over the
+ * examined {@link Iterable} yields at least one item that is matched by
the specified
+ * <code>itemMatcher</code>. Whilst matching, the traversal of the
examined {@link Iterable}
+ * will stop as soon as a matching item is found.
+ * <p/>
+ * For example:
+ * <pre>assertThat(Arrays.asList("foo", "bar"),
hasItem(startsWith("ba")))</pre>
+ *
+ * @param itemMatcher
+ * the matcher to apply to items provided by the examined {@link
Iterable}
+ */
+ public static <T> org.hamcrest.Matcher<java.lang.Iterable<? super T>>
hasItem(org.hamcrest.Matcher<? super T> itemMatcher) {
+ return
org.hamcrest.core.IsCollectionContaining.<T>hasItem(itemMatcher);
+ }
+
+ /**
+ * Creates a matcher for {@link Iterable}s that matches when consecutive
passes over the
+ * examined {@link Iterable} yield at least one item that is equal to
the corresponding
+ * item from the specified <code>items</code>. Whilst matching, each
traversal of the
+ * examined {@link Iterable} will stop as soon as a matching item is
found.
+ * <p/>
+ * For example:
+ * <pre>assertThat(Arrays.asList("foo", "bar", "baz"),
hasItems("baz", "foo"))</pre>
+ *
+ * @param items
+ * the items to compare against the items provided by the examined
{@link Iterable}
+ */
+ public static <T> org.hamcrest.Matcher<java.lang.Iterable<T>>
hasItems(T... items) {
+ return org.hamcrest.core.IsCollectionContaining.<T>hasItems(items);
+ }
+
+ /**
+ * Creates a matcher for {@link Iterable}s that matches when consecutive
passes over the
+ * examined {@link Iterable} yield at least one item that is matched by
the corresponding
+ * matcher from the specified <code>itemMatchers</code>. Whilst
matching, each traversal of
+ * the examined {@link Iterable} will stop as soon as a matching item is
found.
+ * <p/>
+ * For example:
+ * <pre>assertThat(Arrays.asList("foo", "bar", "baz"),
hasItems(endsWith("z"), endsWith("o")))</pre>
+ *
+ * @param itemMatchers
+ * the matchers to apply to items provided by the examined {@link
Iterable}
+ */
+ public static <T> org.hamcrest.Matcher<java.lang.Iterable<T>>
hasItems(org.hamcrest.Matcher<? super T>... itemMatchers) {
+ return
org.hamcrest.core.IsCollectionContaining.<T>hasItems(itemMatchers);
+ }
+
+ /**
+ * Creates a matcher that matches when the examined object is logically
equal to the specified
+ * <code>operand</code>, as determined by calling the {@link
java.lang.Object#equals} method on
+ * the <b>examined</b> object.
+ *
+ * <p>If the specified operand is <code>null</code> then the created
matcher will only match if
+ * the examined object's <code>equals</code> method returns
<code>true</code> when passed a
+ * <code>null</code> (which would be a violation of the
<code>equals</code> contract), unless the
+ * examined object itself is <code>null</code>, in which case the
matcher will return a positive
+ * match.</p>
+ *
+ * <p>The created matcher provides a special behaviour when examining
<code>Array</code>s, whereby
+ * it will match if both the operand and the examined object are arrays
of the same length and
+ * contain items that are equal to each other (according to the above
rules) <b>in the same
+ * indexes</b>.</p>
+ * <p/>
+ * For example:
+ * <pre>
+ * assertThat("foo", equalTo("foo"));
+ * assertThat(new String[] {"foo", "bar"}, equalTo(new String[]
{"foo", "bar"}));
+ * </pre>
+ */
+ public static <T> org.hamcrest.Matcher<T> equalTo(T operand) {
+ return org.hamcrest.core.IsEqual.<T>equalTo(operand);
+ }
+
+ /**
+ * Creates a matcher that matches when the examined object is an
instance of the specified <code>type</code>,
+ * as determined by calling the {@link
java.lang.Class#isInstance(Object)} method on that type, passing the
+ * the examined object.
+ *
+ * <p>The created matcher forces a relationship between specified type
and the examined object, and should be
+ * used when it is necessary to make generics conform, for example in
the JMock clause
+ * <code>with(any(Thing.class))</code></p>
+ * <p/>
+ * For example:
+ * <pre>assertThat(new Canoe(), instanceOf(Canoe.class));</pre>
+ */
+ public static <T> org.hamcrest.Matcher<T> any(java.lang.Class<T> type) {
+ return org.hamcrest.core.IsInstanceOf.<T>any(type);
+ }
+
+ /**
+ * Creates a matcher that matches when the examined object is an
instance of the specified <code>type</code>,
+ * as determined by calling the {@link
java.lang.Class#isInstance(Object)} method on that type, passing the
+ * the examined object.
+ *
+ * <p>The created matcher assumes no relationship between specified type
and the examined object.</p>
+ * <p/>
+ * For example:
+ * <pre>assertThat(new Canoe(), instanceOf(Paddlable.class));</pre>
+ */
+ public static <T> org.hamcrest.Matcher<T> instanceOf(java.lang.Class<?>
type) {
+ return org.hamcrest.core.IsInstanceOf.<T>instanceOf(type);
+ }
+
+ /**
+ * Creates a matcher that wraps an existing matcher, but inverts the
logic by which
+ * it will match.
+ * <p/>
+ * For example:
+ * <pre>assertThat(cheese, is(not(equalTo(smelly))))</pre>
+ *
+ * @param matcher
+ * the matcher whose sense should be inverted
+ */
+ public static <T> org.hamcrest.Matcher<T> not(org.hamcrest.Matcher<T>
matcher) {
+ return org.hamcrest.core.IsNot.<T>not(matcher);
+ }
+
+ /**
+ * A shortcut to the frequently used <code>not(equalTo(x))</code>.
+ * <p/>
+ * For example:
+ * <pre>assertThat(cheese, is(not(smelly)))</pre>
+ * instead of:
+ * <pre>assertThat(cheese, is(not(equalTo(smelly))))</pre>
+ *
+ * @param value
+ * the value that any examined object should <b>not</b> equal
+ */
+ public static <T> org.hamcrest.Matcher<T> not(T value) {
+ return org.hamcrest.core.IsNot.<T>not(value);
+ }
+
+ /**
+ * Creates a matcher that matches if examined object is
<code>null</code>.
+ * <p/>
+ * For example:
+ * <pre>assertThat(cheese, is(nullValue())</pre>
+ */
+ public static org.hamcrest.Matcher<java.lang.Object> nullValue() {
+ return org.hamcrest.core.IsNull.nullValue();
+ }
+
+ /**
+ * Creates a matcher that matches if examined object is
<code>null</code>. Accepts a
+ * single dummy argument to facilitate type inference.
+ * <p/>
+ * For example:
+ * <pre>assertThat(cheese, is(nullValue(Cheese.class))</pre>
+ *
+ * @param type
+ * dummy parameter used to infer the generic type of the returned
matcher
+ */
+ public static <T> org.hamcrest.Matcher<T> nullValue(java.lang.Class<T>
type) {
+ return org.hamcrest.core.IsNull.<T>nullValue(type);
+ }
+
+ /**
+ * A shortcut to the frequently used <code>not(nullValue())</code>.
+ * <p/>
+ * For example:
+ * <pre>assertThat(cheese, is(notNullValue()))</pre>
+ * instead of:
+ * <pre>assertThat(cheese, is(not(nullValue())))</pre>
+ */
+ public static org.hamcrest.Matcher<java.lang.Object> notNullValue() {
+ return org.hamcrest.core.IsNull.notNullValue();
+ }
+
+ /**
+ * A shortcut to the frequently used <code>not(nullValue(X.class)).
Accepts a
+ * single dummy argument to facilitate type inference.</code>.
+ * <p/>
+ * For example:
+ * <pre>assertThat(cheese, is(notNullValue(X.class)))</pre>
+ * instead of:
+ * <pre>assertThat(cheese, is(not(nullValue(X.class))))</pre>
+ *
+ * @param type
+ * dummy parameter used to infer the generic type of the returned
matcher
+ */
+ public static <T> org.hamcrest.Matcher<T>
notNullValue(java.lang.Class<T> type) {
+ return org.hamcrest.core.IsNull.<T>notNullValue(type);
+ }
+
+ /**
+ * Creates a matcher that matches only when the examined object is the
same instance as
+ * the specified target object.
+ *
+ * @param target
+ * the target instance against which others should be assessed
+ */
+ public static <T> org.hamcrest.Matcher<T> sameInstance(T target) {
+ return org.hamcrest.core.IsSame.<T>sameInstance(target);
+ }
+
+ /**
+ * Creates a matcher that matches only when the examined object is the
same instance as
+ * the specified target object.
+ *
+ * @param target
+ * the target instance against which others should be assessed
+ */
+ public static <T> org.hamcrest.Matcher<T> theInstance(T target) {
+ return org.hamcrest.core.IsSame.<T>theInstance(target);
+ }
+
+ /**
+ * Creates a matcher that matches if the examined {@link String}
contains the specified
+ * {@link String} anywhere.
+ * <p/>
+ * For example:
+ * <pre>assertThat("myStringOfNote", containsString("ring"))</pre>
+ *
+ * @param substring
+ * the substring that the returned matcher will expect to find
within any examined string
+ */
+ public static org.hamcrest.Matcher<java.lang.String>
containsString(java.lang.String substring) {
+ return org.hamcrest.core.StringContains.containsString(substring);
+ }
+
+ /**
+ * Creates a matcher that matches if the examined {@link String} starts
with the specified
+ * {@link String}.
+ * <p/>
+ * For example:
+ * <pre>assertThat("myStringOfNote", startsWith("my"))</pre>
+ *
+ * @param prefix
+ * the substring that the returned matcher will expect at the start
of any examined string
+ */
+ public static org.hamcrest.Matcher<java.lang.String>
startsWith(java.lang.String prefix) {
+ return org.hamcrest.core.StringStartsWith.startsWith(prefix);
+ }
+
+ /**
+ * Creates a matcher that matches if the examined {@link String} ends
with the specified
+ * {@link String}.
+ * <p/>
+ * For example:
+ * <pre>assertThat("myStringOfNote", endsWith("Note"))</pre>
+ *
+ * @param suffix
+ * the substring that the returned matcher will expect at the end
of any examined string
+ */
+ public static org.hamcrest.Matcher<java.lang.String>
endsWith(java.lang.String suffix) {
+ return org.hamcrest.core.StringEndsWith.endsWith(suffix);
+ }
+
+}
=======================================
--- /dev/null
+++ /test/java/hamcrest-core-1.3/org/hamcrest/CustomMatcher.java Sun Nov 16
21:58:55 2014 UTC
@@ -0,0 +1,37 @@
+package org.hamcrest;
+
+/**
+ * Utility class for writing one off matchers.
+ * For example:
+ * <pre>
+ * Matcher&lt;String&gt; aNonEmptyString = new
CustomMatcher&lt;String&gt;("a non empty string") {
+ * public boolean matches(Object object) {
+ * return ((object instanceof String) && !((String) object).isEmpty();
+ * }
+ * };
+ * </pre>
+ * <p>
+ * This class is designed for scenarios where an anonymous inner class
+ * matcher makes sense. It should not be used by API designers implementing
+ * matchers.
+ *
+ * @author Neil Dunn
+ * @see CustomTypeSafeMatcher for a type safe variant of this class that
you probably
+ * want to use.
+ * @param <T> The type of object being matched.
+ */
+public abstract class CustomMatcher<T> extends BaseMatcher<T> {
+ private final String fixedDescription;
+
+ public CustomMatcher(String description) {
+ if (description == null) {
+ throw new IllegalArgumentException("Description should be non
null!");
+ }
+ this.fixedDescription = description;
+ }
+
+ @Override
+ public final void describeTo(Description description) {
+ description.appendText(fixedDescription);
+ }
+}
=======================================
--- /dev/null
+++ /test/java/hamcrest-core-1.3/org/hamcrest/CustomTypeSafeMatcher.java
Sun Nov 16 21:58:55 2014 UTC
@@ -0,0 +1,39 @@
+package org.hamcrest;
+
+
+/**
+ * Utility class for writing one off matchers.
+ * For example:
+ * <pre>
+ * Matcher&lt;String&gt; aNonEmptyString = new
CustomTypeSafeMatcher&lt;String&gt;("a non empty string") {
+ * public boolean matchesSafely(String string) {
+ * return !string.isEmpty();
+ * }
+ * public void describeMismatchSafely(String string, Description
mismatchDescription) {
+ * mismatchDescription.appendText("was empty");
+ * }
+ * };
+ * </pre>
+ * This is a variant of {@link CustomMatcher} that first type checks
+ * the argument being matched. By the time {@link
TypeSafeMatcher#matchesSafely} is
+ * is called the argument is guaranteed to be non-null and of the correct
+ * type.
+ *
+ * @author Neil Dunn
+ * @param <T> The type of object being matched
+ */
+public abstract class CustomTypeSafeMatcher<T> extends TypeSafeMatcher<T> {
+ private final String fixedDescription;
+
+ public CustomTypeSafeMatcher(String description) {
+ if (description == null) {
+ throw new IllegalArgumentException("Description must be non
null!");
+ }
+ this.fixedDescription = description;
+ }
+
+ @Override
+ public final void describeTo(Description description) {
+ description.appendText(fixedDescription);
+ }
+}
=======================================
--- /dev/null
+++ /test/java/hamcrest-core-1.3/org/hamcrest/Description.java Sun Nov 16
21:58:55 2014 UTC
@@ -0,0 +1,89 @@
+package org.hamcrest;
+
+/**
+ * A description of a Matcher. A Matcher will describe itself to a
description
+ * which can later be used for reporting.
+ *
+ * @see Matcher#describeTo(Description)
+ */
+public interface Description {
+ /**
+ * A description that consumes input but does nothing.
+ */
+ static final Description NONE = new NullDescription();
+
+ /**
+ * Appends some plain text to the description.
+ */
+ Description appendText(String text);
+
+ /**
+ * Appends the description of a {@link SelfDescribing} value to this
description.
+ */
+ Description appendDescriptionOf(SelfDescribing value);
+
+ /**
+ * Appends an arbitary value to the description.
+ */
+ Description appendValue(Object value);
+
+ /**
+ * Appends a list of values to the description.
+ */
+ <T> Description appendValueList(String start, String separator, String
end,
+ T... values);
+
+ /**
+ * Appends a list of values to the description.
+ */
+ <T> Description appendValueList(String start, String separator, String
end,
+ Iterable<T> values);
+
+ /**
+ * Appends a list of {@link org.hamcrest.SelfDescribing} objects
+ * to the description.
+ */
+ Description appendList(String start, String separator, String end,
+ Iterable<? extends SelfDescribing> values);
+
+
+ public static final class NullDescription implements Description {
+ @Override
+ public Description appendDescriptionOf(SelfDescribing value) {
+ return this;
+ }
+
+ @Override
+ public Description appendList(String start, String separator,
+ String end, Iterable<? extends SelfDescribing> values) {
+ return this;
+ }
+
+ @Override
+ public Description appendText(String text) {
+ return this;
+ }
+
+ @Override
+ public Description appendValue(Object value) {
+ return this;
+ }
+
+ @Override
+ public <T> Description appendValueList(String start, String
separator,
+ String end, T... values) {
+ return this;
+ }
+
+ @Override
+ public <T> Description appendValueList(String start, String
separator,
+ String end, Iterable<T> values) {
+ return this;
+ }
+
+ @Override
+ public String toString() {
+ return "";
+ }
+ }
+}
=======================================
--- /dev/null
+++ /test/java/hamcrest-core-1.3/org/hamcrest/DiagnosingMatcher.java Sun
Nov 16 21:58:55 2014 UTC
@@ -0,0 +1,21 @@
+package org.hamcrest;
+
+/**
+ * TODO(ngd): Document.
+ *
+ * @param <T>
+ */
+public abstract class DiagnosingMatcher<T> extends BaseMatcher<T> {
+
+ @Override
+ public final boolean matches(Object item) {
+ return matches(item, Description.NONE);
+ }
+
+ @Override
+ public final void describeMismatch(Object item, Description
mismatchDescription) {
+ matches(item, mismatchDescription);
+ }
+
+ protected abstract boolean matches(Object item, Description
mismatchDescription);
+}
=======================================
--- /dev/null
+++ /test/java/hamcrest-core-1.3/org/hamcrest/Factory.java Sun Nov 16
21:58:55 2014 UTC
@@ -0,0 +1,17 @@
+package org.hamcrest;
+
+import static java.lang.annotation.ElementType.METHOD;
+import java.lang.annotation.Retention;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+import java.lang.annotation.Target;
+
+/**
+ * Marks a Hamcrest static factory method so tools recognise them.
+ * A factory method is an equivalent to a named constructor.
+ *
+ * @author Joe Walnes
+ */
+@Retention(RUNTIME)
+@Target({METHOD})
+public @interface Factory {
+}
=======================================
--- /dev/null
+++ /test/java/hamcrest-core-1.3/org/hamcrest/FeatureMatcher.java Sun Nov
16 21:58:55 2014 UTC
@@ -0,0 +1,54 @@
+package org.hamcrest;
+
+import org.hamcrest.internal.ReflectiveTypeFinder;
+
+/**
+ * Supporting class for matching a feature of an object. Implement
<code>featureValueOf()</code>
+ * in a subclass to pull out the feature to be matched against.
+ *
+ * @param <T> The type of the object to be matched
+ * @param <U> The type of the feature to be matched
+ */
+public abstract class FeatureMatcher<T, U> extends
TypeSafeDiagnosingMatcher<T> {
+ private static final ReflectiveTypeFinder TYPE_FINDER = new
ReflectiveTypeFinder("featureValueOf", 1, 0);
+ private final Matcher<? super U> subMatcher;
+ private final String featureDescription;
+ private final String featureName;
+
+ /**
+ * Constructor
+ * @param subMatcher The matcher to apply to the feature
+ * @param featureDescription Descriptive text to use in describeTo
+ * @param featureName Identifying text for mismatch message
+ */
+ public FeatureMatcher(Matcher<? super U> subMatcher, String
featureDescription, String featureName) {
+ super(TYPE_FINDER);
+ this.subMatcher = subMatcher;
+ this.featureDescription = featureDescription;
+ this.featureName = featureName;
+ }
+
+ /**
+ * Implement this to extract the interesting feature.
+ * @param actual the target object
+ * @return the feature to be matched
+ */
+ protected abstract U featureValueOf(T actual);
+
+ @Override
+ protected boolean matchesSafely(T actual, Description mismatch) {
+ final U featureValue = featureValueOf(actual);
+ if (!subMatcher.matches(featureValue)) {
+ mismatch.appendText(featureName).appendText(" ");
+ subMatcher.describeMismatch(featureValue, mismatch);
+ return false;
+ }
+ return true;
+ };
+
+ @Override
+ public final void describeTo(Description description) {
+ description.appendText(featureDescription).appendText(" ")
+ .appendDescriptionOf(subMatcher);
+ }
+}
=======================================
--- /dev/null
+++ /test/java/hamcrest-core-1.3/org/hamcrest/Matcher.java Sun Nov 16
21:58:55 2014 UTC
@@ -0,0 +1,63 @@
+/* Copyright (c) 2000-2006 hamcrest.org
+ */
+package org.hamcrest;
+
+/**
+ * A matcher over acceptable values.
+ * A matcher is able to describe itself to give feedback when it fails.
+ * <p/>
+ * Matcher implementations should <b>NOT directly implement this
interface</b>.
+ * Instead, <b>extend</b> the {@link BaseMatcher} abstract class,
+ * which will ensure that the Matcher API can grow to support
+ * new features and remain compatible with all Matcher implementations.
+ * <p/>
+ * For easy access to common Matcher implementations, use the static
factory
+ * methods in {@link CoreMatchers}.
+ * <p/>
+ * N.B. Well designed matchers should be immutable.
+ *
+ * @see CoreMatchers
+ * @see BaseMatcher
+ */
+public interface Matcher<T> extends SelfDescribing {
+
+ /**
+ * Evaluates the matcher for argument <var>item</var>.
+ * <p/>
+ * This method matches against Object, instead of the generic type T.
This is
+ * because the caller of the Matcher does not know at runtime what the
type is
+ * (because of type erasure with Java generics). It is down to the
implementations
+ * to check the correct type.
+ *
+ * @param item the object against which the matcher is evaluated.
+ * @return <code>true</code> if <var>item</var> matches, otherwise
<code>false</code>.
+ *
+ * @see BaseMatcher
+ */
+ boolean matches(Object item);
+
+ /**
+ * Generate a description of why the matcher has not accepted the item.
+ * The description will be part of a larger description of why a
matching
+ * failed, so it should be concise.
+ * This method assumes that <code>matches(item)</code> is false, but
+ * will not check this.
+ *
+ * @param item The item that the Matcher has rejected.
+ * @param mismatchDescription
+ * The description to be built or appended to.
+ */
+ void describeMismatch(Object item, Description mismatchDescription);
+
+ /**
+ * This method simply acts a friendly reminder not to implement
Matcher directly and
+ * instead extend BaseMatcher. It's easy to ignore JavaDoc, but a bit
harder to ignore
+ * compile errors .
+ *
+ * @see Matcher for reasons why.
+ * @see BaseMatcher
+ * @deprecated to make
+ */
+ @Deprecated
+ void _dont_implement_Matcher___instead_extend_BaseMatcher_();
+}
=======================================
--- /dev/null
+++ /test/java/hamcrest-core-1.3/org/hamcrest/MatcherAssert.java Sun Nov 16
21:58:55 2014 UTC
@@ -0,0 +1,29 @@
+/* Copyright (c) 2000-2006 hamcrest.org
+ */
+package org.hamcrest;
+
+
+public class MatcherAssert {
+ public static <T> void assertThat(T actual, Matcher<? super T>
matcher) {
+ assertThat("", actual, matcher);
+ }
+
+ public static <T> void assertThat(String reason, T actual, Matcher<?
super T> matcher) {
+ if (!matcher.matches(actual)) {
+ Description description = new StringDescription();
+ description.appendText(reason)
+ .appendText("\nExpected: ")
+ .appendDescriptionOf(matcher)
+ .appendText("\n but: ");
+ matcher.describeMismatch(actual, description);
+
+ throw new AssertionError(description.toString());
+ }
+ }
+
+ public static void assertThat(String reason, boolean assertion) {
+ if (!assertion) {
+ throw new AssertionError(reason);
+ }
+ }
+}
=======================================
--- /dev/null
+++ /test/java/hamcrest-core-1.3/org/hamcrest/SelfDescribing.java Sun Nov
16 21:58:55 2014 UTC
@@ -0,0 +1,16 @@
+package org.hamcrest;
+
+/**
+ * The ability of an object to describe itself.
+ */
+public interface SelfDescribing {
+ /**
+ * Generates a description of the object. The description may be part
of a
+ * a description of a larger object of which this is just a component,
so it
+ * should be worded appropriately.
+ *
+ * @param description
+ * The description to be built or appended to.
+ */
+ void describeTo(Description description);
+}
=======================================
--- /dev/null
+++ /test/java/hamcrest-core-1.3/org/hamcrest/StringDescription.java Sun
Nov 16 21:58:55 2014 UTC
@@ -0,0 +1,63 @@
+package org.hamcrest;
+
+import java.io.IOException;
+
+/**
+ * A {@link Description} that is stored as a string.
+ */
+public class StringDescription extends BaseDescription {
+ private final Appendable out;
+
+ public StringDescription() {
+ this(new StringBuilder());
+ }
+
+ public StringDescription(Appendable out) {
+ this.out = out;
+ }
+
+ /**
+ * Return the description of a {@link SelfDescribing} object as a
String.
+ *
+ * @param selfDescribing
+ * The object to be described.
+ * @return
+ * The description of the object.
+ */
+ public static String toString(SelfDescribing selfDescribing) {
+ return new
StringDescription().appendDescriptionOf(selfDescribing).toString();
+ }
+
+ /**
+ * Alias for {@link #toString(SelfDescribing)}.
+ */
+ public static String asString(SelfDescribing selfDescribing) {
+ return toString(selfDescribing);
+ }
+
+ @Override
+ protected void append(String str) {
+ try {
+ out.append(str);
+ } catch (IOException e) {
+ throw new RuntimeException("Could not write description", e);
+ }
+ }
+
+ @Override
+ protected void append(char c) {
+ try {
+ out.append(c);
+ } catch (IOException e) {
+ throw new RuntimeException("Could not write description", e);
+ }
+ }
+
+ /**
+ * Returns the description as a string.
+ */
+ @Override
+ public String toString() {
+ return out.toString();
+ }
+}
=======================================
--- /dev/null
+++
/test/java/hamcrest-core-1.3/org/hamcrest/TypeSafeDiagnosingMatcher.java
Sun Nov 16 21:58:55 2014 UTC
@@ -0,0 +1,69 @@
+package org.hamcrest;
+
+import org.hamcrest.internal.ReflectiveTypeFinder;
+
+
+/**
+ * Convenient base class for Matchers that require a non-null value of a
specific type
+ * and that will report why the received value has been rejected.
+ * This implements the null check, checks the type and then casts.
+ * To use, implement <pre>matchesSafely()</pre>.
+ *
+ * @param <T>
+ * @author Neil Dunn
+ * @author Nat Pryce
+ * @author Steve Freeman
+ */
+public abstract class TypeSafeDiagnosingMatcher<T> extends BaseMatcher<T> {
+ private static final ReflectiveTypeFinder TYPE_FINDER = new
ReflectiveTypeFinder("matchesSafely", 2, 0);
+ private final Class<?> expectedType;
+
+ /**
+ * Subclasses should implement this. The item will already have been
checked
+ * for the specific type and will never be null.
+ */
+ protected abstract boolean matchesSafely(T item, Description
mismatchDescription);
+
+ /**
+ * Use this constructor if the subclass that implements
<code>matchesSafely</code>
+ * is <em>not</em> the class that binds &lt;T&gt; to a type.
+ * @param expectedType The expectedType of the actual value.
+ */
+ protected TypeSafeDiagnosingMatcher(Class<?> expectedType) {
+ this.expectedType = expectedType;
+ }
+
+ /**
+ * Use this constructor if the subclass that implements
<code>matchesSafely</code>
+ * is <em>not</em> the class that binds &lt;T&gt; to a type.
+ * @param typeFinder A type finder to extract the type
+ */
+ protected TypeSafeDiagnosingMatcher(ReflectiveTypeFinder typeFinder) {
+ this.expectedType = typeFinder.findExpectedType(getClass());
+ }
+
+ /**
+ * The default constructor for simple sub types
+ */
+ protected TypeSafeDiagnosingMatcher() {
+ this(TYPE_FINDER);
+ }
+
+ @Override
+ @SuppressWarnings("unchecked")
+ public final boolean matches(Object item) {
+ return item != null
+ && expectedType.isInstance(item)
+ && matchesSafely((T) item, new Description.NullDescription());
+ }
+
+ @SuppressWarnings("unchecked")
+ @Override
+ public final void describeMismatch(Object item, Description
mismatchDescription) {
+ if (item == null || !expectedType.isInstance(item)) {
+ super.describeMismatch(item, mismatchDescription);
+ } else {
+ matchesSafely((T) item, mismatchDescription);
+ }
+ }
+}
=======================================
--- /dev/null
+++ /test/java/hamcrest-core-1.3/org/hamcrest/TypeSafeMatcher.java Sun Nov
16 21:58:55 2014 UTC
@@ -0,0 +1,85 @@
+package org.hamcrest;
+
+import org.hamcrest.internal.ReflectiveTypeFinder;
+
+/**
+ * Convenient base class for Matchers that require a non-null value of a
specific type.
+ * This simply implements the null check, checks the type and then casts.
+ *
+ * @author Joe Walnes
+ * @author Steve Freeman
+ * @author Nat Pryce
+ */
+public abstract class TypeSafeMatcher<T> extends BaseMatcher<T> {
+ private static final ReflectiveTypeFinder TYPE_FINDER = new
ReflectiveTypeFinder("matchesSafely", 1, 0);
+
+ final private Class<?> expectedType;
+
+ /**
+ * The default constructor for simple sub types
+ */
+ protected TypeSafeMatcher() {
+ this(TYPE_FINDER);
+ }
+
+ /**
+ * Use this constructor if the subclass that implements
<code>matchesSafely</code>
+ * is <em>not</em> the class that binds &lt;T&gt; to a type.
+ * @param expectedType The expectedType of the actual value.
+ */
+ protected TypeSafeMatcher(Class<?> expectedType) {
+ this.expectedType = expectedType;
+ }
+
+ /**
+ * Use this constructor if the subclass that implements
<code>matchesSafely</code>
+ * is <em>not</em> the class that binds &lt;T&gt; to a type.
+ * @param typeFinder A type finder to extract the type
+ */
+ protected TypeSafeMatcher(ReflectiveTypeFinder typeFinder) {
+ this.expectedType = typeFinder.findExpectedType(getClass());
+ }
+
+ /**
+ * Subclasses should implement this. The item will already have been
checked for
+ * the specific type and will never be null.
+ */
+ protected abstract boolean matchesSafely(T item);
+
+ /**
+ * Subclasses should override this. The item will already have been
checked for
+ * the specific type and will never be null.
+ */
+ protected void describeMismatchSafely(T item, Description
mismatchDescription) {
+ super.describeMismatch(item, mismatchDescription);
+ }
+
+ /**
+ * Methods made final to prevent accidental override.
+ * If you need to override this, there's no point on extending
TypeSafeMatcher.
+ * Instead, extend the {@link BaseMatcher}.
+ */
+ @Override
+ @SuppressWarnings({"unchecked"})
+ public final boolean matches(Object item) {
+ return item != null
+ && expectedType.isInstance(item)
+ && matchesSafely((T) item);
+ }
+
+ @SuppressWarnings("unchecked")
+ @Override
+ final public void describeMismatch(Object item, Description
description) {
+ if (item == null) {
+ super.describeMismatch(item, description);
+ } else if (! expectedType.isInstance(item)) {
+ description.appendText("was a ")
+ .appendText(item.getClass().getName())
+ .appendText(" (")
+ .appendValue(item)
+ .appendText(")");
+ } else {
+ describeMismatchSafely((T)item, description);
+ }
+ }
+}
=======================================
--- /dev/null
+++ /test/java/hamcrest-core-1.3/org/hamcrest/core/AllOf.java Sun Nov 16
21:58:55 2014 UTC
@@ -0,0 +1,142 @@
+package org.hamcrest.core;
+
+import org.hamcrest.Description;
+import org.hamcrest.DiagnosingMatcher;
+import org.hamcrest.Factory;
+import org.hamcrest.Matcher;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+/**
+ * Calculates the logical conjunction of multiple matchers. Evaluation is
shortcut, so
+ * subsequent matchers are not called if an earlier matcher returns
<code>false</code>.
+ */
+public class AllOf<T> extends DiagnosingMatcher<T> {
+
+ private final Iterable<Matcher<? super T>> matchers;
+
+ public AllOf(Iterable<Matcher<? super T>> matchers) {
+ this.matchers = matchers;
+ }
+
+ @Override
+ public boolean matches(Object o, Description mismatch) {
+ for (Matcher<? super T> matcher : matchers) {
+ if (!matcher.matches(o)) {
+ mismatch.appendDescriptionOf(matcher).appendText(" ");
+ matcher.describeMismatch(o, mismatch);
+ return false;
+ }
+ }
+ return true;
+ }
+
+ @Override
+ public void describeTo(Description description) {
+ description.appendList("(", " " + "and" + " ", ")", matchers);
+ }
+
+ /**
+ * Creates a matcher that matches if the examined object matches
<b>ALL</b> of the specified matchers.
+ * <p/>
+ * For example:
+ * <pre>assertThat("myValue", allOf(startsWith("my"),
containsString("Val")))</pre>
+ */
+ @Factory
+ public static <T> Matcher<T> allOf(Iterable<Matcher<? super T>>
matchers) {
+ return new AllOf<T>(matchers);
+ }
+
+ /**
+ * Creates a matcher that matches if the examined object matches
<b>ALL</b> of the specified matchers.
+ * <p/>
+ * For example:
+ * <pre>assertThat("myValue", allOf(startsWith("my"),
containsString("Val")))</pre>
+ */
+ @Factory
+ public static <T> Matcher<T> allOf(Matcher<? super T>... matchers) {
+ return allOf(Arrays.asList(matchers));
+ }
+
+ /**
+ * Creates a matcher that matches if the examined object matches
<b>ALL</b> of the specified matchers.
+ * <p/>
+ * For example:
+ * <pre>assertThat("myValue", allOf(startsWith("my"),
containsString("Val")))</pre>
+ */
+ @Factory
+ public static <T> Matcher<T> allOf(Matcher<? super T> first, Matcher<?
super T> second) {
+ List<Matcher<? super T>> matchers = new ArrayList<Matcher<? super
T>>(2);
+ matchers.add(first);
+ matchers.add(second);
+ return allOf(matchers);
+ }
+
+ /**
+ * Creates a matcher that matches if the examined object matches
<b>ALL</b> of the specified matchers.
+ * <p/>
+ * For example:
+ * <pre>assertThat("myValue", allOf(startsWith("my"),
containsString("Val")))</pre>
+ */
+ @Factory
+ public static <T> Matcher<T> allOf(Matcher<? super T> first, Matcher<?
super T> second, Matcher<? super T> third) {
+ List<Matcher<? super T>> matchers = new ArrayList<Matcher<? super
T>>(3);
+ matchers.add(first);
+ matchers.add(second);
+ matchers.add(third);
+ return allOf(matchers);
+ }
+
+ /**
+ * Creates a matcher that matches if the examined object matches
<b>ALL</b> of the specified matchers.
+ * <p/>
+ * For example:
+ * <pre>assertThat("myValue", allOf(startsWith("my"),
containsString("Val")))</pre>
+ */
+ @Factory
+ public static <T> Matcher<T> allOf(Matcher<? super T> first, Matcher<?
super T> second, Matcher<? super T> third, Matcher<? super T> fourth) {
+ List<Matcher<? super T>> matchers = new ArrayList<Matcher<? super
T>>(4);
+ matchers.add(first);
+ matchers.add(second);
+ matchers.add(third);
+ matchers.add(fourth);
+ return allOf(matchers);
+ }
+
+ /**
+ * Creates a matcher that matches if the examined object matches
<b>ALL</b> of the specified matchers.
+ * <p/>
+ * For example:
+ * <pre>assertThat("myValue", allOf(startsWith("my"),
containsString("Val")))</pre>
+ */
+ @Factory
+ public static <T> Matcher<T> allOf(Matcher<? super T> first, Matcher<?
super T> second, Matcher<? super T> third, Matcher<? super T> fourth,
Matcher<? super T> fifth) {
+ List<Matcher<? super T>> matchers = new ArrayList<Matcher<? super
T>>(5);
+ matchers.add(first);
+ matchers.add(second);
+ matchers.add(third);
+ matchers.add(fourth);
+ matchers.add(fifth);
+ return allOf(matchers);
+ }
+
+ /**
+ * Creates a matcher that matches if the examined object matches
<b>ALL</b> of the specified matchers.
+ * <p/>
+ * For example:
+ * <pre>assertThat("myValue", allOf(startsWith("my"),
containsString("Val")))</pre>
+ */
+ @Factory
+ public static <T> Matcher<T> allOf(Matcher<? super T> first, Matcher<?
super T> second, Matcher<? super T> third, Matcher<? super T> fourth,
Matcher<? super T> fifth, Matcher<? super T> sixth) {
+ List<Matcher<? super T>> matchers = new ArrayList<Matcher<? super
T>>(6);
+ matchers.add(first);
+ matchers.add(second);
+ matchers.add(third);
+ matchers.add(fourth);
+ matchers.add(fifth);
+ matchers.add(sixth);
+ return allOf(matchers);
+ }
+}
=======================================
--- /dev/null
+++ /test/java/hamcrest-core-1.3/org/hamcrest/core/AnyOf.java Sun Nov 16
21:58:55 2014 UTC
@@ -0,0 +1,132 @@
+package org.hamcrest.core;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+import org.hamcrest.Description;
+import org.hamcrest.Factory;
+import org.hamcrest.Matcher;
+
+/**
+ * Calculates the logical disjunction of multiple matchers. Evaluation is
shortcut, so
+ * subsequent matchers are not called if an earlier matcher returns
<code>true</code>.
+ */
+public class AnyOf<T> extends ShortcutCombination<T> {
+
+ public AnyOf(Iterable<Matcher<? super T>> matchers) {
+ super(matchers);
+ }
+
+ @Override
+ public boolean matches(Object o) {
+ return matches(o, true);
+ }
+
+ @Override
+ public void describeTo(Description description) {
+ describeTo(description, "or");
+ }
+
+ /**
+ * Creates a matcher that matches if the examined object matches
<b>ANY</b> of the specified matchers.
+ * <p/>
+ * For example:
+ * <pre>assertThat("myValue", anyOf(startsWith("foo"),
containsString("Val")))</pre>
+ */
+ @Factory
+ public static <T> AnyOf<T> anyOf(Iterable<Matcher<? super T>>
matchers) {
+ return new AnyOf<T>(matchers);
+ }
+
+ /**
+ * Creates a matcher that matches if the examined object matches
<b>ANY</b> of the specified matchers.
+ * <p/>
+ * For example:
+ * <pre>assertThat("myValue", anyOf(startsWith("foo"),
containsString("Val")))</pre>
+ */
+ @Factory
+ public static <T> AnyOf<T> anyOf(Matcher<? super T>... matchers) {
+ return anyOf(Arrays.asList(matchers));
+ }
+
+ /**
+ * Creates a matcher that matches if the examined object matches
<b>ANY</b> of the specified matchers.
+ * <p/>
+ * For example:
+ * <pre>assertThat("myValue", anyOf(startsWith("foo"),
containsString("Val")))</pre>
+ */
+ @Factory
+ public static <T> AnyOf<T> anyOf(Matcher<T> first, Matcher<? super T>
second) {
+ List<Matcher<? super T>> matchers = new ArrayList<Matcher<? super
T>>();
+ matchers.add(first);
+ matchers.add(second);
+ return anyOf(matchers);
+ }
+
+ /**
+ * Creates a matcher that matches if the examined object matches
<b>ANY</b> of the specified matchers.
+ * <p/>
+ * For example:
+ * <pre>assertThat("myValue", anyOf(startsWith("foo"),
containsString("Val")))</pre>
+ */
+ @Factory
+ public static <T> AnyOf<T> anyOf(Matcher<T> first, Matcher<? super T>
second, Matcher<? super T> third) {
+ List<Matcher<? super T>> matchers = new ArrayList<Matcher<? super
T>>();
+ matchers.add(first);
+ matchers.add(second);
+ matchers.add(third);
+ return anyOf(matchers);
+ }
+
+ /**
+ * Creates a matcher that matches if the examined object matches
<b>ANY</b> of the specified matchers.
+ * <p/>
+ * For example:
+ * <pre>assertThat("myValue", anyOf(startsWith("foo"),
containsString("Val")))</pre>
+ */
+ @Factory
+ public static <T> AnyOf<T> anyOf(Matcher<T> first, Matcher<? super T>
second, Matcher<? super T> third, Matcher<? super T> fourth) {
+ List<Matcher<? super T>> matchers = new ArrayList<Matcher<? super
T>>();
+ matchers.add(first);
+ matchers.add(second);
+ matchers.add(third);
+ matchers.add(fourth);
+ return anyOf(matchers);
+ }
+
+ /**
+ * Creates a matcher that matches if the examined object matches
<b>ANY</b> of the specified matchers.
+ * <p/>
+ * For example:
+ * <pre>assertThat("myValue", anyOf(startsWith("foo"),
containsString("Val")))</pre>
+ */
+ @Factory
+ public static <T> AnyOf<T> anyOf(Matcher<T> first, Matcher<? super T>
second, Matcher<? super T> third, Matcher<? super T> fourth, Matcher<?
super T> fifth) {
+ List<Matcher<? super T>> matchers = new ArrayList<Matcher<? super
T>>();
+ matchers.add(first);
+ matchers.add(second);
+ matchers.add(third);
+ matchers.add(fourth);
+ matchers.add(fifth);
+ return anyOf(matchers);
+ }
+
+ /**
+ * Creates a matcher that matches if the examined object matches
<b>ANY</b> of the specified matchers.
+ * <p/>
+ * For example:
+ * <pre>assertThat("myValue", anyOf(startsWith("foo"),
containsString("Val")))</pre>
+ */
+ @Factory
+ public static <T> AnyOf<T> anyOf(Matcher<T> first, Matcher<? super T>
second, Matcher<? super T> third, Matcher<? super T> fourth, Matcher<?
super T> fifth, Matcher<? super T> sixth) {
+ List<Matcher<? super T>> matchers = new ArrayList<Matcher<? super
T>>();
+ matchers.add(first);
+ matchers.add(second);
+ matchers.add(third);
+ matchers.add(fourth);
+ matchers.add(fifth);
+ matchers.add(sixth);
+ return anyOf(matchers);
+ }
+}
=======================================
--- /dev/null
+++ /test/java/hamcrest-core-1.3/org/hamcrest/core/CombinableMatcher.java
Sun Nov 16 21:58:55 2014 UTC
@@ -0,0 +1,84 @@
+package org.hamcrest.core;
+
+import org.hamcrest.*;
+
+import java.util.ArrayList;
+
+public class CombinableMatcher<T> extends TypeSafeDiagnosingMatcher<T> {
+ private final Matcher<? super T> matcher;
+
+ public CombinableMatcher(Matcher<? super T> matcher) {
+ this.matcher = matcher;
+ }
+
+ @Override
+ protected boolean matchesSafely(T item, Description mismatch) {
+ if (!matcher.matches(item)) {
+ matcher.describeMismatch(item, mismatch);
+ return false;
+ }
+ return true;
+ }
+
+ @Override
+ public void describeTo(Description description) {
+ description.appendDescriptionOf(matcher);
+ }
+
+ public CombinableMatcher<T> and(Matcher<? super T> other) {
+ return new CombinableMatcher<T>(new
AllOf<T>(templatedListWith(other)));
+ }
+
+ public CombinableMatcher<T> or(Matcher<? super T> other) {
+ return new CombinableMatcher<T>(new
AnyOf<T>(templatedListWith(other)));
+ }
+
+ private ArrayList<Matcher<? super T>> templatedListWith(Matcher<? super
T> other) {
+ ArrayList<Matcher<? super T>> matchers = new ArrayList<Matcher<? super
T>>();
+ matchers.add(matcher);
+ matchers.add(other);
+ return matchers;
+ }
+
+ /**
+ * Creates a matcher that matches when both of the specified matchers
match the examined object.
+ * <p/>
+ * For example:
+ * <pre>assertThat("fab",
both(containsString("a")).and(containsString("b")))</pre>
+ */
+ @Factory
+ public static <LHS> CombinableBothMatcher<LHS> both(Matcher<? super LHS>
matcher) {
+ return new CombinableBothMatcher<LHS>(matcher);
+ }
+
+ public static final class CombinableBothMatcher<X> {
+ private final Matcher<? super X> first;
+ public CombinableBothMatcher(Matcher<? super X> matcher) {
+ this.first = matcher;
+ }
+ public CombinableMatcher<X> and(Matcher<? super X> other) {
+ return new CombinableMatcher<X>(first).and(other);
+ }
+ }
+
+ /**
+ * Creates a matcher that matches when either of the specified matchers
match the examined object.
+ * <p/>
+ * For example:
+ * <pre>assertThat("fan",
either(containsString("a")).and(containsString("b")))</pre>
+ */
+ @Factory
+ public static <LHS> CombinableEitherMatcher<LHS> either(Matcher<? super
LHS> matcher) {
+ return new CombinableEitherMatcher<LHS>(matcher);
+ }
+
+ public static final class CombinableEitherMatcher<X> {
+ private final Matcher<? super X> first;
+ public CombinableEitherMatcher(Matcher<? super X> matcher) {
+ this.first = matcher;
+ }
+ public CombinableMatcher<X> or(Matcher<? super X> other) {
+ return new CombinableMatcher<X>(first).or(other);
+ }
+ }
+}
=======================================
--- /dev/null
+++ /test/java/hamcrest-core-1.3/org/hamcrest/core/DescribedAs.java Sun Nov
16 21:58:55 2014 UTC
@@ -0,0 +1,74 @@
+/* Copyright (c) 2000-2006 hamcrest.org
+ */
+package org.hamcrest.core;
+
+import org.hamcrest.BaseMatcher;
+import org.hamcrest.Description;
+import org.hamcrest.Factory;
+import org.hamcrest.Matcher;
+
+import java.util.regex.Pattern;
+
+import static java.lang.Integer.parseInt;
+
+/**
+ * Provides a custom description to another matcher.
+ */
+public class DescribedAs<T> extends BaseMatcher<T> {
+ private final String descriptionTemplate;
+ private final Matcher<T> matcher;
+ private final Object[] values;
+
+ private final static Pattern ARG_PATTERN =
Pattern.compile("%([0-9]+)");
+
+ public DescribedAs(String descriptionTemplate, Matcher<T> matcher,
Object[] values) {
+ this.descriptionTemplate = descriptionTemplate;
+ this.matcher = matcher;
+ this.values = values.clone();
+ }
+
+ @Override
+ public boolean matches(Object o) {
+ return matcher.matches(o);
+ }
+
+ @Override
+ public void describeTo(Description description) {
+ java.util.regex.Matcher arg =
ARG_PATTERN.matcher(descriptionTemplate);
+
+ int textStart = 0;
+ while (arg.find()) {
+
description.appendText(descriptionTemplate.substring(textStart,
arg.start()));
+ description.appendValue(values[parseInt(arg.group(1))]);
+ textStart = arg.end();
+ }
+
+ if (textStart < descriptionTemplate.length()) {
+
description.appendText(descriptionTemplate.substring(textStart));
+ }
+ }
+
+ @Override
+ public void describeMismatch(Object item, Description description) {
+ matcher.describeMismatch(item, description);
+ }
+
+ /**
+ * Wraps an existing matcher, overriding its description with that
specified. All other functions are
+ * delegated to the decorated matcher, including its mismatch
description.
+ * <p/>
+ * For example:
+ * <pre>describedAs("a big decimal equal to %0",
equalTo(myBigDecimal), myBigDecimal.toPlainString())</pre>
+ *
+ * @param description
+ * the new description for the wrapped matcher
+ * @param matcher
+ * the matcher to wrap
+ * @param values
+ * optional values to insert into the tokenised description
+ */
+ @Factory
+ public static <T> Matcher<T> describedAs(String description,
Matcher<T> matcher, Object... values) {
+ return new DescribedAs<T>(description, matcher, values);
+ }
+}
=======================================
--- /dev/null
+++ /test/java/hamcrest-core-1.3/org/hamcrest/core/Every.java Sun Nov 16
21:58:55 2014 UTC
@@ -0,0 +1,47 @@
+package org.hamcrest.core;
+
+import org.hamcrest.Description;
+import org.hamcrest.Factory;
+import org.hamcrest.Matcher;
+import org.hamcrest.TypeSafeDiagnosingMatcher;
+
+public class Every<T> extends TypeSafeDiagnosingMatcher<Iterable<T>> {
+ private final Matcher<? super T> matcher;
+
+ public Every(Matcher<? super T> matcher) {
+ this.matcher= matcher;
+ }
+
+ @Override
+ public boolean matchesSafely(Iterable<T> collection, Description
mismatchDescription) {
+ for (T t : collection) {
+ if (!matcher.matches(t)) {
+ mismatchDescription.appendText("an item ");
+ matcher.describeMismatch(t, mismatchDescription);
+ return false;
+ }
+ }
+ return true;
+ }
+
+ @Override
+ public void describeTo(Description description) {
+ description.appendText("every item
is ").appendDescriptionOf(matcher);
+ }
+
+ /**
+ * Creates a matcher for {@link Iterable}s that only matches when a
single pass over the
+ * examined {@link Iterable} yields items that are all matched by the
specified
+ * <code>itemMatcher</code>.
+ * <p/>
+ * For example:
+ * <pre>assertThat(Arrays.asList("bar", "baz"),
everyItem(startsWith("ba")))</pre>
+ *
+ * @param itemMatcher
+ * the matcher to apply to every item provided by the examined
{@link Iterable}
+ */
+ @Factory
+ public static <U> Matcher<Iterable<U>> everyItem(final Matcher<U>
itemMatcher) {
+ return new Every<U>(itemMatcher);
+ }
+}
=======================================
--- /dev/null
+++ /test/java/hamcrest-core-1.3/org/hamcrest/core/Is.java Sun Nov 16
21:58:55 2014 UTC
@@ -0,0 +1,100 @@
+package org.hamcrest.core;
+
+import org.hamcrest.BaseMatcher;
+import org.hamcrest.Description;
+import org.hamcrest.Factory;
+import org.hamcrest.Matcher;
+
+import static org.hamcrest.core.IsEqual.equalTo;
+import static org.hamcrest.core.IsInstanceOf.instanceOf;
+
+/**
+ * Decorates another Matcher, retaining the behaviour but allowing tests
+ * to be slightly more expressive.
+ *
+ * For example: assertThat(cheese, equalTo(smelly))
+ * vs. assertThat(cheese, is(equalTo(smelly)))
+ */
+public class Is<T> extends BaseMatcher<T> {
+ private final Matcher<T> matcher;
+
+ public Is(Matcher<T> matcher) {
+ this.matcher = matcher;
+ }
+
+ @Override
+ public boolean matches(Object arg) {
+ return matcher.matches(arg);
+ }
+
+ @Override
+ public void describeTo(Description description) {
+ description.appendText("is ").appendDescriptionOf(matcher);
+ }
+
+ @Override
+ public void describeMismatch(Object item, Description
mismatchDescription) {
+ matcher.describeMismatch(item, mismatchDescription);
+ }
+
+ /**
+ * Decorates another Matcher, retaining its behaviour, but allowing
tests
+ * to be slightly more expressive.
+ * <p/>
+ * For example:
+ * <pre>assertThat(cheese, is(equalTo(smelly)))</pre>
+ * instead of:
+ * <pre>assertThat(cheese, equalTo(smelly))</pre>
+ *
+ */
+ @Factory
+ public static <T> Matcher<T> is(Matcher<T> matcher) {
+ return new Is<T>(matcher);
+ }
+
+ /**
+ * A shortcut to the frequently used <code>is(equalTo(x))</code>.
+ * <p/>
+ * For example:
+ * <pre>assertThat(cheese, is(smelly))</pre>
+ * instead of:
+ * <pre>assertThat(cheese, is(equalTo(smelly)))</pre>
+ *
+ */
+ @Factory
+ public static <T> Matcher<T> is(T value) {
+ return is(equalTo(value));
+ }
+
+ /**
+ * A shortcut to the frequently used
<code>is(instanceOf(SomeClass.class))</code>.
+ * <p/>
+ * For example:
+ * <pre>assertThat(cheese, is(Cheddar.class))</pre>
+ * instead of:
+ * <pre>assertThat(cheese, is(instanceOf(Cheddar.class)))</pre>
+ *
+ * @deprecated use isA(Class<T> type) instead.
+ */
+ @Factory
+ @Deprecated
+ public static <T> Matcher<T> is(Class<T> type) {
+ final Matcher<T> typeMatcher = instanceOf(type);
+ return is(typeMatcher);
+ }
+
+ /**
+ * A shortcut to the frequently used
<code>is(instanceOf(SomeClass.class))</code>.
+ * <p/>
+ * For example:
+ * <pre>assertThat(cheese, isA(Cheddar.class))</pre>
+ * instead of:
+ * <pre>assertThat(cheese, is(instanceOf(Cheddar.class)))</pre>
+ *
+ */
+ @Factory
+ public static <T> Matcher<T> isA(Class<T> type) {
+ final Matcher<T> typeMatcher = instanceOf(type);
+ return is(typeMatcher);
+ }
+}
=======================================
--- /dev/null
+++ /test/java/hamcrest-core-1.3/org/hamcrest/core/IsAnything.java Sun Nov
16 21:58:55 2014 UTC
@@ -0,0 +1,55 @@
+/* Copyright (c) 2000-2006 hamcrest.org
+ */
+package org.hamcrest.core;
+
+import org.hamcrest.Description;
+import org.hamcrest.Matcher;
+import org.hamcrest.Factory;
+import org.hamcrest.BaseMatcher;
+
+
+/**
+ * A matcher that always returns <code>true</code>.
+ */
+public class IsAnything<T> extends BaseMatcher<T> {
+
+ private final String message;
+
+ public IsAnything() {
+ this("ANYTHING");
+ }
+
+ public IsAnything(String message) {
+ this.message = message;
+ }
+
+ @Override
+ public boolean matches(Object o) {
+ return true;
+ }
+
+ @Override
+ public void describeTo(Description description) {
+ description.appendText(message);
+ }
+
+ /**
+ * Creates a matcher that always matches, regardless of the examined
object.
+ */
+ @Factory
+ public static Matcher<Object> anything() {
+ return new IsAnything<Object>();
+ }
+
+ /**
+ * Creates a matcher that always matches, regardless of the examined
object, but describes
+ * itself with the specified {@link String}.
+ *
+ * @param description
+ * a meaningful {@link String} used when describing itself
+ */
+ @Factory
+ public static Matcher<Object> anything(String description) {
+ return new IsAnything<Object>(description);
+ }
+}
=======================================
--- /dev/null
+++
/test/java/hamcrest-core-1.3/org/hamcrest/core/IsCollectionContaining.java
Sun Nov 16 21:58:55 2014 UTC
@@ -0,0 +1,126 @@
+package org.hamcrest.core;
+
+import static org.hamcrest.core.AllOf.allOf;
+import static org.hamcrest.core.IsEqual.equalTo;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.hamcrest.Description;
+import org.hamcrest.Factory;
+import org.hamcrest.Matcher;
+import org.hamcrest.TypeSafeDiagnosingMatcher;
+
+public class IsCollectionContaining<T> extends
TypeSafeDiagnosingMatcher<Iterable<? super T>> {
+ private final Matcher<? super T> elementMatcher;
+
+ public IsCollectionContaining(Matcher<? super T> elementMatcher) {
+ this.elementMatcher = elementMatcher;
+ }
+
+ @Override
+ protected boolean matchesSafely(Iterable<? super T> collection,
Description mismatchDescription) {
+ boolean isPastFirst = false;
+ for (Object item : collection) {
+ if (elementMatcher.matches(item)){
+ return true;
+ }
+ if (isPastFirst) {
+ mismatchDescription.appendText(", ");
+ }
+ elementMatcher.describeMismatch(item, mismatchDescription);
+ isPastFirst = true;
+ }
+ return false;
+ }
+
+ @Override
+ public void describeTo(Description description) {
+ description
+ .appendText("a collection containing ")
+ .appendDescriptionOf(elementMatcher);
+ }
+
+
+ /**
+ * Creates a matcher for {@link Iterable}s that only matches when a
single pass over the
+ * examined {@link Iterable} yields at least one item that is matched
by the specified
+ * <code>itemMatcher</code>. Whilst matching, the traversal of the
examined {@link Iterable}
+ * will stop as soon as a matching item is found.
+ * <p/>
+ * For example:
+ * <pre>assertThat(Arrays.asList("foo", "bar"),
hasItem(startsWith("ba")))</pre>
+ *
+ * @param itemMatcher
+ * the matcher to apply to items provided by the examined {@link
Iterable}
+ */
+ @Factory
+ public static <T> Matcher<Iterable<? super T>> hasItem(Matcher<? super
T> itemMatcher) {
+ return new IsCollectionContaining<T>(itemMatcher);
+ }
+
+ /**
+ * Creates a matcher for {@link Iterable}s that only matches when a
single pass over the
+ * examined {@link Iterable} yields at least one item that is equal to
the specified
+ * <code>item</code>. Whilst matching, the traversal of the examined
{@link Iterable}
+ * will stop as soon as a matching item is found.
+ * <p/>
+ * For example:
+ * <pre>assertThat(Arrays.asList("foo", "bar"), hasItem("bar"))</pre>
+ *
+ * @param item
+ * the item to compare against the items provided by the examined
{@link Iterable}
+ */
+ @Factory
+ public static <T> Matcher<Iterable<? super T>> hasItem(T item) {
+ // Doesn't forward to hasItem() method so compiler can sort out
generics.
+ return new IsCollectionContaining<T>(equalTo(item));
+ }
+
+ /**
+ * Creates a matcher for {@link Iterable}s that matches when
consecutive passes over the
+ * examined {@link Iterable} yield at least one item that is matched
by the corresponding
+ * matcher from the specified <code>itemMatchers</code>. Whilst
matching, each traversal of
+ * the examined {@link Iterable} will stop as soon as a matching item
is found.
+ * <p/>
+ * For example:
+ * <pre>assertThat(Arrays.asList("foo", "bar", "baz"),
hasItems(endsWith("z"), endsWith("o")))</pre>
+ *
+ * @param itemMatchers
+ * the matchers to apply to items provided by the examined {@link
Iterable}
+ */
+ @Factory
+ public static <T> Matcher<Iterable<T>> hasItems(Matcher<? super T>...
itemMatchers) {
+ List<Matcher<? super Iterable<T>>> all = new ArrayList<Matcher<?
super Iterable<T>>>(itemMatchers.length);
+
+ for (Matcher<? super T> elementMatcher : itemMatchers) {
+ // Doesn't forward to hasItem() method so compiler can sort out
generics.
+ all.add(new IsCollectionContaining<T>(elementMatcher));
+ }
+
+ return allOf(all);
+ }
+
+ /**
+ * Creates a matcher for {@link Iterable}s that matches when
consecutive passes over the
+ * examined {@link Iterable} yield at least one item that is equal to
the corresponding
+ * item from the specified <code>items</code>. Whilst matching, each
traversal of the
+ * examined {@link Iterable} will stop as soon as a matching item is
found.
+ * <p/>
+ * For example:
+ * <pre>assertThat(Arrays.asList("foo", "bar", "baz"),
hasItems("baz", "foo"))</pre>
+ *
+ * @param items
+ * the items to compare against the items provided by the examined
{@link Iterable}
+ */
+ @Factory
+ public static <T> Matcher<Iterable<T>> hasItems(T... items) {
+ List<Matcher<? super Iterable<T>>> all = new ArrayList<Matcher<?
super Iterable<T>>>(items.length);
+ for (T element : items) {
+ all.add(hasItem(element));
+ }
+
+ return allOf(all);
+ }
+
+}
=======================================
--- /dev/null
+++ /test/java/hamcrest-core-1.3/org/hamcrest/core/IsEqual.java Sun Nov 16
21:58:55 2014 UTC
@@ -0,0 +1,94 @@
+/* Copyright (c) 2000-2006 hamcrest.org
+ */
+package org.hamcrest.core;
+
+import org.hamcrest.BaseMatcher;
+import org.hamcrest.Description;
+import org.hamcrest.Factory;
+import org.hamcrest.Matcher;
+
+import java.lang.reflect.Array;
+
+
+/**
+ * Is the value equal to another value, as tested by the
+ * {@link java.lang.Object#equals} invokedMethod?
+ */
+public class IsEqual<T> extends BaseMatcher<T> {
+ private final Object expectedValue;
+
+ public IsEqual(T equalArg) {
+ expectedValue = equalArg;
+ }
+
+ @Override
+ public boolean matches(Object actualValue) {
+ return areEqual(actualValue, expectedValue);
+ }
+
+ @Override
+ public void describeTo(Description description) {
+ description.appendValue(expectedValue);
+ }
+
+ private static boolean areEqual(Object actual, Object expected) {
+ if (actual == null) {
+ return expected == null;
+ }
+
+ if (expected != null && isArray(actual)) {
+ return isArray(expected) && areArraysEqual(actual, expected);
+ }
+
+ return actual.equals(expected);
+ }
+
+ private static boolean areArraysEqual(Object actualArray, Object
expectedArray) {
+ return areArrayLengthsEqual(actualArray, expectedArray) &&
areArrayElementsEqual(actualArray, expectedArray);
+ }
+
+ private static boolean areArrayLengthsEqual(Object actualArray, Object
expectedArray) {
+ return Array.getLength(actualArray) ==
Array.getLength(expectedArray);
+ }
+
+ private static boolean areArrayElementsEqual(Object actualArray,
Object expectedArray) {
+ for (int i = 0; i < Array.getLength(actualArray); i++) {
+ if (!areEqual(Array.get(actualArray, i),
Array.get(expectedArray, i))) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ private static boolean isArray(Object o) {
+ return o.getClass().isArray();
+ }
+
+ /**
+ * Creates a matcher that matches when the examined object is
logically equal to the specified
+ * <code>operand</code>, as determined by calling the {@link
java.lang.Object#equals} method on
+ * the <b>examined</b> object.
+ *
+ * <p>If the specified operand is <code>null</code> then the created
matcher will only match if
+ * the examined object's <code>equals</code> method returns
<code>true</code> when passed a
+ * <code>null</code> (which would be a violation of the
<code>equals</code> contract), unless the
+ * examined object itself is <code>null</code>, in which case the
matcher will return a positive
+ * match.</p>
+ *
+ * <p>The created matcher provides a special behaviour when examining
<code>Array</code>s, whereby
+ * it will match if both the operand and the examined object are
arrays of the same length and
+ * contain items that are equal to each other (according to the above
rules) <b>in the same
+ * indexes</b>.</p>
+ * <p/>
+ * For example:
+ * <pre>
+ * assertThat("foo", equalTo("foo"));
+ * assertThat(new String[] {"foo", "bar"}, equalTo(new String[]
{"foo", "bar"}));
+ * </pre>
+ *
+ */
+ @Factory
+ public static <T> Matcher<T> equalTo(T operand) {
+ return new IsEqual<T>(operand);
+ }
+}
=======================================
--- /dev/null
+++ /test/java/hamcrest-core-1.3/org/hamcrest/core/IsInstanceOf.java Sun
Nov 16 21:58:55 2014 UTC
@@ -0,0 +1,98 @@
+/* Copyright (c) 2000-2006 hamcrest.org
+ */
+package org.hamcrest.core;
+
+import org.hamcrest.Description;
+import org.hamcrest.DiagnosingMatcher;
+import org.hamcrest.Factory;
+import org.hamcrest.Matcher;
+
+
+/**
+ * Tests whether the value is an instance of a class.
+ * Classes of basic types will be converted to the relevant "Object"
classes
+ */
+public class IsInstanceOf extends DiagnosingMatcher<Object> {
+ private final Class<?> expectedClass;
+ private final Class<?> matchableClass;
+
+ /**
+ * Creates a new instance of IsInstanceOf
+ *
+ * @param expectedClass The predicate evaluates to true for instances
of this class
+ * or one of its subclasses.
+ */
+ public IsInstanceOf(Class<?> expectedClass) {
+ this.expectedClass = expectedClass;
+ this.matchableClass = matchableClass(expectedClass);
+ }
+
+ private static Class<?> matchableClass(Class<?> expectedClass) {
+ if (boolean.class.equals(expectedClass)) return Boolean.class;
+ if (byte.class.equals(expectedClass)) return Byte.class;
+ if (char.class.equals(expectedClass)) return Character.class;
+ if (double.class.equals(expectedClass)) return Double.class;
+ if (float.class.equals(expectedClass)) return Float.class;
+ if (int.class.equals(expectedClass)) return Integer.class;
+ if (long.class.equals(expectedClass)) return Long.class;
+ if (short.class.equals(expectedClass)) return Short.class;
+ return expectedClass;
+ }
+
+ @Override
+ protected boolean matches(Object item, Description mismatch) {
+ if (null == item) {
+ mismatch.appendText("null");
+ return false;
+ }
+
+ if (!matchableClass.isInstance(item)) {
+ mismatch.appendValue(item).appendText(" is a " +
item.getClass().getName());
+ return false;
+ }
+
+ return true;
+ }
+
+ @Override
+ public void describeTo(Description description) {
+ description.appendText("an instance
of ").appendText(expectedClass.getName());
+ }
+
+ /**
+ * Creates a matcher that matches when the examined object is an
instance of the specified <code>type</code>,
+ * as determined by calling the {@link
java.lang.Class#isInstance(Object)} method on that type, passing the
+ * the examined object.
+ *
+ * <p>The created matcher assumes no relationship between specified
type and the examined object.</p>
+ * <p/>
+ * For example:
+ * <pre>assertThat(new Canoe(), instanceOf(Paddlable.class));</pre>
+ *
+ */
+ @SuppressWarnings("unchecked")
+ @Factory
+ public static <T> Matcher<T> instanceOf(Class<?> type) {
+ return (Matcher<T>) new IsInstanceOf(type);
+ }
+
+ /**
+ * Creates a matcher that matches when the examined object is an
instance of the specified <code>type</code>,
+ * as determined by calling the {@link
java.lang.Class#isInstance(Object)} method on that type, passing the
+ * the examined object.
+ *
+ * <p>The created matcher forces a relationship between specified type
and the examined object, and should be
+ * used when it is necessary to make generics conform, for example in
the JMock clause
+ * <code>with(any(Thing.class))</code></p>
+ * <p/>
+ * For example:
+ * <pre>assertThat(new Canoe(), instanceOf(Canoe.class));</pre>
+ *
+ */
+ @SuppressWarnings("unchecked")
+ @Factory
+ public static <T> Matcher<T> any(Class<T> type) {
+ return (Matcher<T>) new IsInstanceOf(type);
+ }
+
+}
=======================================
--- /dev/null
+++ /test/java/hamcrest-core-1.3/org/hamcrest/core/IsNot.java Sun Nov 16
21:58:55 2014 UTC
@@ -0,0 +1,64 @@
+/* Copyright (c) 2000-2009 hamcrest.org
+ */
+package org.hamcrest.core;
+
+import org.hamcrest.BaseMatcher;
+import org.hamcrest.Description;
+import org.hamcrest.Factory;
+import org.hamcrest.Matcher;
+
+import static org.hamcrest.core.IsEqual.equalTo;
+
+
+/**
+ * Calculates the logical negation of a matcher.
+ */
+public class IsNot<T> extends BaseMatcher<T> {
+ private final Matcher<T> matcher;
+
+ public IsNot(Matcher<T> matcher) {
+ this.matcher = matcher;
+ }
+
+ @Override
+ public boolean matches(Object arg) {
+ return !matcher.matches(arg);
+ }
+
+ @Override
+ public void describeTo(Description description) {
+ description.appendText("not ").appendDescriptionOf(matcher);
+ }
+
+
+ /**
+ * Creates a matcher that wraps an existing matcher, but inverts the
logic by which
+ * it will match.
+ * <p/>
+ * For example:
+ * <pre>assertThat(cheese, is(not(equalTo(smelly))))</pre>
+ *
+ * @param matcher
+ * the matcher whose sense should be inverted
+ */
+ @Factory
+ public static <T> Matcher<T> not(Matcher<T> matcher) {
+ return new IsNot<T>(matcher);
+ }
+
+ /**
+ * A shortcut to the frequently used <code>not(equalTo(x))</code>.
+ * <p/>
+ * For example:
+ * <pre>assertThat(cheese, is(not(smelly)))</pre>
+ * instead of:
+ * <pre>assertThat(cheese, is(not(equalTo(smelly))))</pre>
+ *
+ * @param value
+ * the value that any examined object should <b>not</b> equal
+ */
+ @Factory
+ public static <T> Matcher<T> not(T value) {
+ return not(equalTo(value));
+ }
+}
=======================================
--- /dev/null
+++ /test/java/hamcrest-core-1.3/org/hamcrest/core/IsNull.java Sun Nov 16
21:58:55 2014 UTC
@@ -0,0 +1,84 @@
+/* Copyright (c) 2000-2010 hamcrest.org
+ */
+package org.hamcrest.core;
+
+import static org.hamcrest.core.IsNot.not;
+import org.hamcrest.Description;
+import org.hamcrest.Matcher;
+import org.hamcrest.Factory;
+import org.hamcrest.BaseMatcher;
+
+/**
+ * Is the value null?
+ */
+public class IsNull<T> extends BaseMatcher<T> {
+ @Override
+ public boolean matches(Object o) {
+ return o == null;
+ }
+
+ @Override
+ public void describeTo(Description description) {
+ description.appendText("null");
+ }
+
+ /**
+ * Creates a matcher that matches if examined object is
<code>null</code>.
+ * <p/>
+ * For example:
+ * <pre>assertThat(cheese, is(nullValue())</pre>
+ *
+ */
+ @Factory
+ public static Matcher<Object> nullValue() {
+ return new IsNull<Object>();
+ }
+
+ /**
+ * A shortcut to the frequently used <code>not(nullValue())</code>.
+ * <p/>
+ * For example:
+ * <pre>assertThat(cheese, is(notNullValue()))</pre>
+ * instead of:
+ * <pre>assertThat(cheese, is(not(nullValue())))</pre>
+ *
+ */
+ @Factory
+ public static Matcher<Object> notNullValue() {
+ return not(nullValue());
+ }
+
+ /**
+ * Creates a matcher that matches if examined object is
<code>null</code>. Accepts a
+ * single dummy argument to facilitate type inference.
+ * <p/>
+ * For example:
+ * <pre>assertThat(cheese, is(nullValue(Cheese.class))</pre>
+ *
+ * @param type
+ * dummy parameter used to infer the generic type of the returned
matcher
+ */
+ @Factory
+ public static <T> Matcher<T> nullValue(Class<T> type) {
+ return new IsNull<T>();
+ }
+
+ /**
+ * A shortcut to the frequently used <code>not(nullValue(X.class)).
Accepts a
+ * single dummy argument to facilitate type inference.</code>.
+ * <p/>
+ * For example:
+ * <pre>assertThat(cheese, is(notNullValue(X.class)))</pre>
+ * instead of:
+ * <pre>assertThat(cheese, is(not(nullValue(X.class))))</pre>
+ *
+ * @param type
+ * dummy parameter used to infer the generic type of the returned
matcher
+ *
+ */
+ @Factory
+ public static <T> Matcher<T> notNullValue(Class<T> type) {
+ return not(nullValue(type));
+ }
+}
+
=======================================
--- /dev/null
+++ /test/java/hamcrest-core-1.3/org/hamcrest/core/IsSame.java Sun Nov 16
21:58:55 2014 UTC
@@ -0,0 +1,56 @@
+/* Copyright (c) 2000-2006 hamcrest.org
+ */
+package org.hamcrest.core;
+
+import org.hamcrest.BaseMatcher;
+import org.hamcrest.Description;
+import org.hamcrest.Factory;
+import org.hamcrest.Matcher;
+
+
+/**
+ * Is the value the same object as another value?
+ */
+public class IsSame<T> extends BaseMatcher<T> {
+ private final T object;
+
+ public IsSame(T object) {
+ this.object = object;
+ }
+
+ @Override
+ public boolean matches(Object arg) {
+ return arg == object;
+ }
+
+ @Override
+ public void describeTo(Description description) {
+ description.appendText("sameInstance(")
+ .appendValue(object)
+ .appendText(")");
+ }
+
+ /**
+ * Creates a matcher that matches only when the examined object is the
same instance as
+ * the specified target object.
+ *
+ * @param target
+ * the target instance against which others should be assessed
+ */
+ @Factory
+ public static <T> Matcher<T> sameInstance(T target) {
+ return new IsSame<T>(target);
+ }
+
+ /**
+ * Creates a matcher that matches only when the examined object is the
same instance as
+ * the specified target object.
+ *
+ * @param target
+ * the target instance against which others should be assessed
+ */
+ @Factory
+ public static <T> Matcher<T> theInstance(T target) {
+ return new IsSame<T>(target);
+ }
+}
=======================================
--- /dev/null
+++ /test/java/hamcrest-core-1.3/org/hamcrest/core/ShortcutCombination.java
Sun Nov 16 21:58:55 2014 UTC
@@ -0,0 +1,33 @@
+package org.hamcrest.core;
+
+import org.hamcrest.BaseMatcher;
+import org.hamcrest.Description;
+import org.hamcrest.Matcher;
+
+abstract class ShortcutCombination<T> extends BaseMatcher<T> {
+
+ private final Iterable<Matcher<? super T>> matchers;
+
+ public ShortcutCombination(Iterable<Matcher<? super T>> matchers) {
+ this.matchers = matchers;
+ }
+
+ @Override
+ public abstract boolean matches(Object o);
+
+ @Override
+ public abstract void describeTo(Description description);
+
+ protected boolean matches(Object o, boolean shortcut) {
+ for (Matcher<? super T> matcher : matchers) {
+ if (matcher.matches(o) == shortcut) {
+ return shortcut;
+ }
+ }
+ return !shortcut;
+ }
+
+ public void describeTo(Description description, String operator) {
+ description.appendList("(", " " + operator + " ", ")", matchers);
+ }
+}
=======================================
--- /dev/null
+++ /test/java/hamcrest-core-1.3/org/hamcrest/core/StringContains.java Sun
Nov 16 21:58:55 2014 UTC
@@ -0,0 +1,42 @@
+/* Copyright (c) 2000-2006 hamcrest.org
+ */
+package org.hamcrest.core;
+
+import org.hamcrest.Factory;
+import org.hamcrest.Matcher;
+
+/**
+ * Tests if the argument is a string that contains a substring.
+ */
+public class StringContains extends SubstringMatcher {
+ public StringContains(String substring) {
+ super(substring);
+ }
+
+ @Override
+ protected boolean evalSubstringOf(String s) {
+ return s.indexOf(substring) >= 0;
+ }
+
+ @Override
+ protected String relationship() {
+ return "containing";
+ }
+
+ /**
+ * Creates a matcher that matches if the examined {@link String}
contains the specified
+ * {@link String} anywhere.
+ * <p/>
+ * For example:
+ * <pre>assertThat("myStringOfNote", containsString("ring"))</pre>
+ *
+ * @param substring
+ * the substring that the returned matcher will expect to find
within any examined string
+ *
+ */
+ @Factory
+ public static Matcher<String> containsString(String substring) {
+ return new StringContains(substring);
+ }
+
+}
=======================================
--- /dev/null
+++ /test/java/hamcrest-core-1.3/org/hamcrest/core/StringEndsWith.java Sun
Nov 16 21:58:55 2014 UTC
@@ -0,0 +1,41 @@
+/* Copyright (c) 2000-2006 hamcrest.org
+ */
+package org.hamcrest.core;
+
+import org.hamcrest.Factory;
+import org.hamcrest.Matcher;
+
+/**
+ * Tests if the argument is a string that contains a substring.
+ */
+public class StringEndsWith extends SubstringMatcher {
+ public StringEndsWith(String substring) {
+ super(substring);
+ }
+
+ @Override
+ protected boolean evalSubstringOf(String s) {
+ return s.endsWith(substring);
+ }
+
+ @Override
+ protected String relationship() {
+ return "ending with";
+ }
+
+ /**
+ * Creates a matcher that matches if the examined {@link String} ends
with the specified
+ * {@link String}.
+ * <p/>
+ * For example:
+ * <pre>assertThat("myStringOfNote", endsWith("Note"))</pre>
+ *
+ * @param suffix
+ * the substring that the returned matcher will expect at the end
of any examined string
+ */
+ @Factory
+ public static Matcher<String> endsWith(String suffix) {
+ return new StringEndsWith(suffix);
+ }
+
+}
=======================================
--- /dev/null
+++ /test/java/hamcrest-core-1.3/org/hamcrest/core/StringStartsWith.java
Sun Nov 16 21:58:55 2014 UTC
@@ -0,0 +1,41 @@
+/* Copyright (c) 2000-2006 hamcrest.org
+ */
+package org.hamcrest.core;
+
+import org.hamcrest.Factory;
+import org.hamcrest.Matcher;
+
+/**
+ * Tests if the argument is a string that contains a substring.
+ */
+public class StringStartsWith extends SubstringMatcher {
+ public StringStartsWith(String substring) {
+ super(substring);
+ }
+
+ @Override
+ protected boolean evalSubstringOf(String s) {
+ return s.startsWith(substring);
+ }
+
+ @Override
+ protected String relationship() {
+ return "starting with";
+ }
+
+ /**
+ * Creates a matcher that matches if the examined {@link String}
starts with the specified
+ * {@link String}.
+ * <p/>
+ * For example:
+ * <pre>assertThat("myStringOfNote", startsWith("my"))</pre>
+ *
+ * @param prefix
+ * the substring that the returned matcher will expect at the
start of any examined string
+ */
+ @Factory
+ public static Matcher<String> startsWith(String prefix) {
+ return new StringStartsWith(prefix);
+ }
+
+}
=======================================
--- /dev/null
+++ /test/java/hamcrest-core-1.3/org/hamcrest/core/SubstringMatcher.java
Sun Nov 16 21:58:55 2014 UTC
@@ -0,0 +1,37 @@
+package org.hamcrest.core;
+
+import org.hamcrest.Description;
+import org.hamcrest.TypeSafeMatcher;
+
+public abstract class SubstringMatcher extends TypeSafeMatcher<String> {
+
+ // TODO: Replace String with CharSequence to allow for easy
interopability between
+ // String, StringBuffer, StringBuilder, CharBuffer, etc (joe).
+
+ protected final String substring;
+
+ protected SubstringMatcher(final String substring) {
+ this.substring = substring;
+ }
+
+ @Override
+ public boolean matchesSafely(String item) {
+ return evalSubstringOf(item);
+ }
+ @Override
+ public void describeMismatchSafely(String item, Description
mismatchDescription) {
+ mismatchDescription.appendText("was
\"").appendText(item).appendText("\"");
+ }
+
+ @Override
+ public void describeTo(Description description) {
+ description.appendText("a string ")
+ .appendText(relationship())
+ .appendText(" ")
+ .appendValue(substring);
+ }
+
+ protected abstract boolean evalSubstringOf(String string);
+
+ protected abstract String relationship();
+}
=======================================
--- /dev/null
+++ /test/java/hamcrest-core-1.3/org/hamcrest/core/package.html Sun Nov 16
21:58:55 2014 UTC
@@ -0,0 +1,7 @@
+<html>
+<head>
+</head>
+<body>
+ <p>Fundamental matchers of objects and values, and composite
matchers.</p>
+</body>
+</html>
=======================================
--- /dev/null
+++ /test/java/hamcrest-core-1.3/org/hamcrest/internal/ArrayIterator.java
Sun Nov 16 21:58:55 2014 UTC
@@ -0,0 +1,31 @@
+package org.hamcrest.internal;
+
+import java.lang.reflect.Array;
+import java.util.Iterator;
+
+public class ArrayIterator implements Iterator<Object> {
+ private final Object array;
+ private int currentIndex = 0;
+
+ public ArrayIterator(Object array) {
+ if (!array.getClass().isArray()) {
+ throw new IllegalArgumentException("not an array");
+ }
+ this.array = array;
+ }
+
+ @Override
+ public boolean hasNext() {
+ return currentIndex < Array.getLength(array);
+ }
+
+ @Override
+ public Object next() {
+ return Array.get(array, currentIndex++);
+ }
+
+ @Override
+ public void remove() {
+ throw new UnsupportedOperationException("cannot remove items from
an array");
+ }
+}
=======================================
--- /dev/null
+++
/test/java/hamcrest-core-1.3/org/hamcrest/internal/ReflectiveTypeFinder.java
Sun Nov 16 21:58:55 2014 UTC
@@ -0,0 +1,70 @@
+/**
+ * The TypeSafe classes, and their descendants, need a mechanism to find
out what type has been used as a parameter
+ * for the concrete matcher. Unfortunately, this type is lost during type
erasure so we need to use reflection
+ * to get it back, by picking out the type of a known parameter to a known
method.
+ * The catch is that, with bridging methods, this type is only visible in
the class that actually implements
+ * the expected method, so the ReflectiveTypeFinder needs to be applied to
that class or a subtype.
+ *
+ * For example, the abstract
<code>TypeSafeDiagnosingMatcher&lt;T&gt;</code> defines an abstract method
+ * <pre>protected abstract boolean matchesSafely(T item, Description
mismatchDescription);</pre>
+ * By default it uses <code>new ReflectiveTypeFinder("matchesSafely", 2,
0); </code> to find the
+ * parameterised type. If we create a
<code>TypeSafeDiagnosingMatcher&lt;String&gt;</code>, the type
+ * finder will return <code>String.class</code>.
+ *
+ * A <code>FeatureMatcher</code> is an abstract subclass of
<code>TypeSafeDiagnosingMatcher</code>.
+ * Although it has a templated implementation of
<code>matchesSafely(&lt;T&gt;, Decription);</code>, the
+ * actualy run-time signature of this is <code>matchesSafely(Object,
Description);</code>. Instead,
+ * we must find the type by reflecting on the concrete implementation of
+ * <pre>protected abstract U featureValueOf(T actual);</pre>
+ * a method which is declared in <code>FeatureMatcher</code>.
+ *
+ * In short, use this to extract a type from a method in the leaf class of
a templated class hierarchy.
+ *
+ * @author Steve Freeman
+ * @author Nat Pryce
+ */
+package org.hamcrest.internal;
+
+import java.lang.reflect.Method;
+
+public class ReflectiveTypeFinder {
+ private final String methodName;
+ private final int expectedNumberOfParameters;
+ private final int typedParameter;
+
+ public ReflectiveTypeFinder(String methodName, int
expectedNumberOfParameters, int typedParameter) {
+ this.methodName = methodName;
+ this.expectedNumberOfParameters = expectedNumberOfParameters;
+ this.typedParameter = typedParameter;
+ }
+
+ public Class<?> findExpectedType(Class<?> fromClass) {
+ for (Class<?> c = fromClass; c != Object.class; c = c.getSuperclass())
{
+ for (Method method : c.getDeclaredMethods()) {
+ if (canObtainExpectedTypeFrom(method)) {
+ return expectedTypeFrom(method);
+ }
+ }
+ }
+ throw new Error("Cannot determine correct type for " + methodName
+ "() method.");
+ }
+
+ /**
+ * @param method The method to examine.
+ * @return true if this method references the relevant type
+ */
+ protected boolean canObtainExpectedTypeFrom(Method method) {
+ return method.getName().equals(methodName)
+ && method.getParameterTypes().length ==
expectedNumberOfParameters
+ && !method.isSynthetic();
+ }
+
+
+ /**
+ * @param method The method from which to extract
+ * @return The type we're looking for
+ */
+ protected Class<?> expectedTypeFrom(Method method) {
+ return method.getParameterTypes()[typedParameter];
+ }
+}
=======================================
--- /dev/null
+++
/test/java/hamcrest-core-1.3/org/hamcrest/internal/SelfDescribingValue.java
Sun Nov 16 21:58:55 2014 UTC
@@ -0,0 +1,17 @@
+package org.hamcrest.internal;
+
+import org.hamcrest.Description;
+import org.hamcrest.SelfDescribing;
+
+public class SelfDescribingValue<T> implements SelfDescribing {
+ private T value;
+
+ public SelfDescribingValue(T value) {
+ this.value = value;
+ }
+
+ @Override
+ public void describeTo(Description description) {
+ description.appendValue(value);
+ }
+}
=======================================
--- /dev/null
+++
/test/java/hamcrest-core-1.3/org/hamcrest/internal/SelfDescribingValueIterator.java
Sun Nov 16 21:58:55 2014 UTC
@@ -0,0 +1,28 @@
+package org.hamcrest.internal;
+
+import java.util.Iterator;
+
+import org.hamcrest.SelfDescribing;
+
+public class SelfDescribingValueIterator<T> implements
Iterator<SelfDescribing> {
+ private Iterator<T> values;
+
+ public SelfDescribingValueIterator(Iterator<T> values) {
+ this.values = values;
+ }
+
+ @Override
+ public boolean hasNext() {
+ return values.hasNext();
+ }
+
+ @Override
+ public SelfDescribing next() {
+ return new SelfDescribingValue<T>(values.next());
+ }
+
+ @Override
+ public void remove() {
+ values.remove();
+ }
+}
=======================================
--- /dev/null
+++ /test/java/hamcrest-core-1.3/org/hamcrest/package.html Sun Nov 16
21:58:55 2014 UTC
@@ -0,0 +1,9 @@
+<html>
+<head>
+</head>
+<body>
+ <p>The stable API defining Matcher and its associated interfaces and
classes.
+ Hamcrest sub-projects define their convenience classes in the
org.hamcrest package.
+ </p>
+</body>
+</html>
=======================================
--- /dev/null
+++ /test/java/junit-4.11/META-INF/MANIFEST.MF Sun Nov 16 21:58:55 2014 UTC
@@ -0,0 +1,4 @@
+Manifest-Version: 1.0
+Ant-Version: Apache Ant 1.8.2
+Created-By: 1.7.0_04-b20 (Oracle Corporation)
+
=======================================
--- /dev/null
+++ /test/java/junit-4.11/junit/extensions/ActiveTestSuite.java Sun Nov 16
21:58:55 2014 UTC
@@ -0,0 +1,70 @@
+package junit.extensions;
+
+import junit.framework.Test;
+import junit.framework.TestCase;
+import junit.framework.TestResult;
+import junit.framework.TestSuite;
+
+/**
+ * A TestSuite for active Tests. It runs each
+ * test in a separate thread and waits until all
+ * threads have terminated.
+ * -- Aarhus Radisson Scandinavian Center 11th floor
+ */
+public class ActiveTestSuite extends TestSuite {
+ private volatile int fActiveTestDeathCount;
+
+ public ActiveTestSuite() {
+ }
+
+ public ActiveTestSuite(Class<? extends TestCase> theClass) {
+ super(theClass);
+ }
+
+ public ActiveTestSuite(String name) {
+ super(name);
+ }
+
+ public ActiveTestSuite(Class<? extends TestCase> theClass, String
name) {
+ super(theClass, name);
+ }
+
+ @Override
+ public void run(TestResult result) {
+ fActiveTestDeathCount = 0;
+ super.run(result);
+ waitUntilFinished();
+ }
+
+ @Override
+ public void runTest(final Test test, final TestResult result) {
+ Thread t = new Thread() {
+ @Override
+ public void run() {
+ try {
+ // inlined due to limitation in VA/Java
+ //ActiveTestSuite.super.runTest(test, result);
+ test.run(result);
+ } finally {
+ ActiveTestSuite.this.runFinished();
+ }
+ }
+ };
+ t.start();
+ }
+
+ synchronized void waitUntilFinished() {
+ while (fActiveTestDeathCount < testCount()) {
+ try {
+ wait();
+ } catch (InterruptedException e) {
+ return; // ignore
+ }
+ }
+ }
+
+ synchronized public void runFinished() {
+ fActiveTestDeathCount++;
+ notifyAll();
+ }
+}
=======================================
--- /dev/null
+++ /test/java/junit-4.11/junit/extensions/RepeatedTest.java Sun Nov 16
21:58:55 2014 UTC
@@ -0,0 +1,39 @@
+package junit.extensions;
+
+import junit.framework.Test;
+import junit.framework.TestResult;
+
+/**
+ * A Decorator that runs a test repeatedly.
+ */
+public class RepeatedTest extends TestDecorator {
+ private int fTimesRepeat;
+
+ public RepeatedTest(Test test, int repeat) {
+ super(test);
+ if (repeat < 0) {
+ throw new IllegalArgumentException("Repetition count must be
>= 0");
+ }
+ fTimesRepeat = repeat;
+ }
+
+ @Override
+ public int countTestCases() {
+ return super.countTestCases() * fTimesRepeat;
+ }
+
+ @Override
+ public void run(TestResult result) {
+ for (int i = 0; i < fTimesRepeat; i++) {
+ if (result.shouldStop()) {
+ break;
+ }
+ super.run(result);
+ }
+ }
+
+ @Override
+ public String toString() {
+ return super.toString() + "(repeated)";
+ }
+}
=======================================
--- /dev/null
+++ /test/java/junit-4.11/junit/extensions/TestDecorator.java Sun Nov 16
21:58:55 2014 UTC
@@ -0,0 +1,42 @@
+package junit.extensions;
+
+import junit.framework.Assert;
+import junit.framework.Test;
+import junit.framework.TestResult;
+
+/**
+ * A Decorator for Tests. Use TestDecorator as the base class for defining
new
+ * test decorators. Test decorator subclasses can be introduced to add
behaviour
+ * before or after a test is run.
+ */
+public class TestDecorator extends Assert implements Test {
+ protected Test fTest;
+
+ public TestDecorator(Test test) {
+ fTest = test;
+ }
+
+ /**
+ * The basic run behaviour.
+ */
+ public void basicRun(TestResult result) {
+ fTest.run(result);
+ }
+
+ public int countTestCases() {
+ return fTest.countTestCases();
+ }
+
+ public void run(TestResult result) {
+ basicRun(result);
+ }
+
+ @Override
+ public String toString() {
+ return fTest.toString();
+ }
+
+ public Test getTest() {
+ return fTest;
+ }
+}
=======================================
--- /dev/null
+++ /test/java/junit-4.11/junit/extensions/TestSetup.java Sun Nov 16
21:58:55 2014 UTC
@@ -0,0 +1,42 @@
+package junit.extensions;
+
+import junit.framework.Protectable;
+import junit.framework.Test;
+import junit.framework.TestResult;
+
+/**
+ * A Decorator to set up and tear down additional fixture state. Subclass
+ * TestSetup and insert it into your tests when you want to set up
additional
+ * state once before the tests are run.
+ */
+public class TestSetup extends TestDecorator {
+
+ public TestSetup(Test test) {
+ super(test);
+ }
+
+ @Override
+ public void run(final TestResult result) {
+ Protectable p = new Protectable() {
+ public void protect() throws Exception {
+ setUp();
+ basicRun(result);
+ tearDown();
+ }
+ };
+ result.runProtected(this, p);
+ }
+
+ /**
+ * Sets up the fixture. Override to set up additional fixture state.
+ */
+ protected void setUp() throws Exception {
+ }
+
+ /**
+ * Tears down the fixture. Override to tear down the additional fixture
+ * state.
+ */
+ protected void tearDown() throws Exception {
+ }
+}
=======================================
--- /dev/null
+++ /test/java/junit-4.11/junit/extensions/package-info.java Sun Nov 16
21:58:55 2014 UTC
@@ -0,0 +1,4 @@
+/**
+ * Provides extended functionality for JUnit v3.x.
+ */
+package junit.extensions;
=======================================
--- /dev/null
+++ /test/java/junit-4.11/junit/framework/Assert.java Sun Nov 16 21:58:55
2014 UTC
@@ -0,0 +1,339 @@
+package junit.framework;
+
+/**
+ * A set of assert methods. Messages are only displayed when an assert
fails.
+ *
+ * @deprecated Please use {@link org.junit.Assert} instead.
+ */
+@Deprecated
+public class Assert {
+ /**
+ * Protect constructor since it is a static only class
+ */
+ protected Assert() {
+ }
+
+ /**
+ * Asserts that a condition is true. If it isn't it throws
+ * an AssertionFailedError with the given message.
+ */
+ static public void assertTrue(String message, boolean condition) {
+ if (!condition) {
+ fail(message);
+ }
+ }
+
+ /**
+ * Asserts that a condition is true. If it isn't it throws
+ * an AssertionFailedError.
+ */
+ static public void assertTrue(boolean condition) {
+ assertTrue(null, condition);
+ }
+
+ /**
+ * Asserts that a condition is false. If it isn't it throws
+ * an AssertionFailedError with the given message.
+ */
+ static public void assertFalse(String message, boolean condition) {
+ assertTrue(message, !condition);
+ }
+
+ /**
+ * Asserts that a condition is false. If it isn't it throws
+ * an AssertionFailedError.
+ */
+ static public void assertFalse(boolean condition) {
+ assertFalse(null, condition);
+ }
+
+ /**
+ * Fails a test with the given message.
+ */
+ static public void fail(String message) {
+ if (message == null) {
+ throw new AssertionFailedError();
+ }
+ throw new AssertionFailedError(message);
+ }
+
+ /**
+ * Fails a test with no message.
+ */
+ static public void fail() {
+ fail(null);
+ }
+
+ /**
+ * Asserts that two objects are equal. If they are not
+ * an AssertionFailedError is thrown with the given message.
+ */
+ static public void assertEquals(String message, Object expected,
Object actual) {
+ if (expected == null && actual == null) {
+ return;
+ }
+ if (expected != null && expected.equals(actual)) {
+ return;
+ }
+ failNotEquals(message, expected, actual);
+ }
+
+ /**
+ * Asserts that two objects are equal. If they are not
+ * an AssertionFailedError is thrown.
+ */
+ static public void assertEquals(Object expected, Object actual) {
+ assertEquals(null, expected, actual);
+ }
+
+ /**
+ * Asserts that two Strings are equal.
+ */
+ static public void assertEquals(String message, String expected,
String actual) {
+ if (expected == null && actual == null) {
+ return;
+ }
+ if (expected != null && expected.equals(actual)) {
+ return;
+ }
+ String cleanMessage = message == null ? "" : message;
+ throw new ComparisonFailure(cleanMessage, expected, actual);
+ }
+
+ /**
+ * Asserts that two Strings are equal.
+ */
+ static public void assertEquals(String expected, String actual) {
+ assertEquals(null, expected, actual);
+ }
+
+ /**
+ * Asserts that two doubles are equal concerning a delta. If they are
not
+ * an AssertionFailedError is thrown with the given message. If the
expected
+ * value is infinity then the delta value is ignored.
+ */
+ static public void assertEquals(String message, double expected,
double actual, double delta) {
+ if (Double.compare(expected, actual) == 0) {
+ return;
+ }
+ if (!(Math.abs(expected - actual) <= delta)) {
+ failNotEquals(message, new Double(expected), new
Double(actual));
+ }
+ }
+
+ /**
+ * Asserts that two doubles are equal concerning a delta. If the
expected
+ * value is infinity then the delta value is ignored.
+ */
+ static public void assertEquals(double expected, double actual, double
delta) {
+ assertEquals(null, expected, actual, delta);
+ }
+
+ /**
+ * Asserts that two floats are equal concerning a positive delta. If
they
+ * are not an AssertionFailedError is thrown with the given message.
If the
+ * expected value is infinity then the delta value is ignored.
+ */
+ static public void assertEquals(String message, float expected, float
actual, float delta) {
+ if (Float.compare(expected, actual) == 0) {
+ return;
+ }
+ if (!(Math.abs(expected - actual) <= delta)) {
+ failNotEquals(message, new Float(expected), new Float(actual));
+ }
+ }
+
+ /**
+ * Asserts that two floats are equal concerning a delta. If the
expected
+ * value is infinity then the delta value is ignored.
+ */
+ static public void assertEquals(float expected, float actual, float
delta) {
+ assertEquals(null, expected, actual, delta);
+ }
+
+ /**
+ * Asserts that two longs are equal. If they are not
+ * an AssertionFailedError is thrown with the given message.
+ */
+ static public void assertEquals(String message, long expected, long
actual) {
+ assertEquals(message, new Long(expected), new Long(actual));
+ }
+
+ /**
+ * Asserts that two longs are equal.
+ */
+ static public void assertEquals(long expected, long actual) {
+ assertEquals(null, expected, actual);
+ }
+
+ /**
+ * Asserts that two booleans are equal. If they are not
+ * an AssertionFailedError is thrown with the given message.
+ */
+ static public void assertEquals(String message, boolean expected,
boolean actual) {
+ assertEquals(message, Boolean.valueOf(expected),
Boolean.valueOf(actual));
+ }
+
+ /**
+ * Asserts that two booleans are equal.
+ */
+ static public void assertEquals(boolean expected, boolean actual) {
+ assertEquals(null, expected, actual);
+ }
+
+ /**
+ * Asserts that two bytes are equal. If they are not
+ * an AssertionFailedError is thrown with the given message.
+ */
+ static public void assertEquals(String message, byte expected, byte
actual) {
+ assertEquals(message, new Byte(expected), new Byte(actual));
+ }
+
+ /**
+ * Asserts that two bytes are equal.
+ */
+ static public void assertEquals(byte expected, byte actual) {
+ assertEquals(null, expected, actual);
+ }
+
+ /**
+ * Asserts that two chars are equal. If they are not
+ * an AssertionFailedError is thrown with the given message.
+ */
+ static public void assertEquals(String message, char expected, char
actual) {
+ assertEquals(message, new Character(expected), new
Character(actual));
+ }
+
+ /**
+ * Asserts that two chars are equal.
+ */
+ static public void assertEquals(char expected, char actual) {
+ assertEquals(null, expected, actual);
+ }
+
+ /**
+ * Asserts that two shorts are equal. If they are not
+ * an AssertionFailedError is thrown with the given message.
+ */
+ static public void assertEquals(String message, short expected, short
actual) {
+ assertEquals(message, new Short(expected), new Short(actual));
+ }
+
+ /**
+ * Asserts that two shorts are equal.
+ */
+ static public void assertEquals(short expected, short actual) {
+ assertEquals(null, expected, actual);
+ }
+
+ /**
+ * Asserts that two ints are equal. If they are not
+ * an AssertionFailedError is thrown with the given message.
+ */
+ static public void assertEquals(String message, int expected, int
actual) {
+ assertEquals(message, new Integer(expected), new Integer(actual));
+ }
+
+ /**
+ * Asserts that two ints are equal.
+ */
+ static public void assertEquals(int expected, int actual) {
+ assertEquals(null, expected, actual);
+ }
+
+ /**
+ * Asserts that an object isn't null.
+ */
+ static public void assertNotNull(Object object) {
+ assertNotNull(null, object);
+ }
+
+ /**
+ * Asserts that an object isn't null. If it is
+ * an AssertionFailedError is thrown with the given message.
+ */
+ static public void assertNotNull(String message, Object object) {
+ assertTrue(message, object != null);
+ }
+
+ /**
+ * Asserts that an object is null. If it isn't an {@link
AssertionError} is
+ * thrown.
+ * Message contains: Expected: <null> but was: object
+ *
+ * @param object Object to check or <code>null</code>
+ */
+ static public void assertNull(Object object) {
+ if (object != null) {
+ assertNull("Expected: <null> but was: " + object.toString(),
object);
+ }
+ }
+
+ /**
+ * Asserts that an object is null. If it is not
+ * an AssertionFailedError is thrown with the given message.
+ */
+ static public void assertNull(String message, Object object) {
+ assertTrue(message, object == null);
+ }
+
+ /**
+ * Asserts that two objects refer to the same object. If they are not
+ * an AssertionFailedError is thrown with the given message.
+ */
+ static public void assertSame(String message, Object expected, Object
actual) {
+ if (expected == actual) {
+ return;
+ }
+ failNotSame(message, expected, actual);
+ }
+
+ /**
+ * Asserts that two objects refer to the same object. If they are not
+ * the same an AssertionFailedError is thrown.
+ */
+ static public void assertSame(Object expected, Object actual) {
+ assertSame(null, expected, actual);
+ }
+
+ /**
+ * Asserts that two objects do not refer to the same object. If they do
+ * refer to the same object an AssertionFailedError is thrown with the
+ * given message.
+ */
+ static public void assertNotSame(String message, Object expected,
Object actual) {
+ if (expected == actual) {
+ failSame(message);
+ }
+ }
+
+ /**
+ * Asserts that two objects do not refer to the same object. If they do
+ * refer to the same object an AssertionFailedError is thrown.
+ */
+ static public void assertNotSame(Object expected, Object actual) {
+ assertNotSame(null, expected, actual);
+ }
+
+ static public void failSame(String message) {
+ String formatted = (message != null) ? message + " " : "";
+ fail(formatted + "expected not same");
+ }
+
+ static public void failNotSame(String message, Object expected, Object
actual) {
+ String formatted = (message != null) ? message + " " : "";
+ fail(formatted + "expected same:<" + expected + "> was not:<" +
actual + ">");
+ }
+
+ static public void failNotEquals(String message, Object expected,
Object actual) {
+ fail(format(message, expected, actual));
+ }
+
+ public static String format(String message, Object expected, Object
actual) {
+ String formatted = "";
+ if (message != null && message.length() > 0) {
+ formatted = message + " ";
+ }
+ return formatted + "expected:<" + expected + "> but was:<" +
actual + ">";
+ }
+}
=======================================
--- /dev/null
+++ /test/java/junit-4.11/junit/framework/AssertionFailedError.java Sun Nov
16 21:58:55 2014 UTC
@@ -0,0 +1,20 @@
+package junit.framework;
+
+/**
+ * Thrown when an assertion failed.
+ */
+public class AssertionFailedError extends AssertionError {
+
+ private static final long serialVersionUID = 1L;
+
+ public AssertionFailedError() {
+ }
+
+ public AssertionFailedError(String message) {
+ super(defaultString(message));
+ }
+
+ private static String defaultString(String message) {
+ return message == null ? "" : message;
+ }
+}
=======================================
--- /dev/null
+++ /test/java/junit-4.11/junit/framework/ComparisonCompactor.java Sun Nov
16 21:58:55 2014 UTC
@@ -0,0 +1,77 @@
+package junit.framework;
+
+public class ComparisonCompactor {
+
+ private static final String ELLIPSIS = "...";
+ private static final String DELTA_END = "]";
+ private static final String DELTA_START = "[";
+
+ private int fContextLength;
+ private String fExpected;
+ private String fActual;
+ private int fPrefix;
+ private int fSuffix;
+
+ public ComparisonCompactor(int contextLength, String expected, String
actual) {
+ fContextLength = contextLength;
+ fExpected = expected;
+ fActual = actual;
+ }
+
+ public String compact(String message) {
+ if (fExpected == null || fActual == null || areStringsEqual()) {
+ return Assert.format(message, fExpected, fActual);
+ }
+
+ findCommonPrefix();
+ findCommonSuffix();
+ String expected = compactString(fExpected);
+ String actual = compactString(fActual);
+ return Assert.format(message, expected, actual);
+ }
+
+ private String compactString(String source) {
+ String result = DELTA_START + source.substring(fPrefix,
source.length() - fSuffix + 1) + DELTA_END;
+ if (fPrefix > 0) {
+ result = computeCommonPrefix() + result;
+ }
+ if (fSuffix > 0) {
+ result = result + computeCommonSuffix();
+ }
+ return result;
+ }
+
+ private void findCommonPrefix() {
+ fPrefix = 0;
+ int end = Math.min(fExpected.length(), fActual.length());
+ for (; fPrefix < end; fPrefix++) {
+ if (fExpected.charAt(fPrefix) != fActual.charAt(fPrefix)) {
+ break;
+ }
+ }
+ }
+
+ private void findCommonSuffix() {
+ int expectedSuffix = fExpected.length() - 1;
+ int actualSuffix = fActual.length() - 1;
+ for (; actualSuffix >= fPrefix && expectedSuffix >= fPrefix;
actualSuffix--, expectedSuffix--) {
+ if (fExpected.charAt(expectedSuffix) !=
fActual.charAt(actualSuffix)) {
+ break;
+ }
+ }
+ fSuffix = fExpected.length() - expectedSuffix;
+ }
+
+ private String computeCommonPrefix() {
+ return (fPrefix > fContextLength ? ELLIPSIS : "") +
fExpected.substring(Math.max(0, fPrefix - fContextLength), fPrefix);
+ }
+
+ private String computeCommonSuffix() {
+ int end = Math.min(fExpected.length() - fSuffix + 1 +
fContextLength, fExpected.length());
+ return fExpected.substring(fExpected.length() - fSuffix + 1, end)
+ (fExpected.length() - fSuffix + 1 < fExpected.length() - fContextLength ?
ELLIPSIS : "");
+ }
+
+ private boolean areStringsEqual() {
+ return fExpected.equals(fActual);
+ }
+}
=======================================
***Additional files exist in this changeset.***
Reply all
Reply to author
Forward
0 new messages