<commit_before>#include "include/rados/librados.h"
#include "include/rados/librados.hpp"
#include "test/rados-api/test.h"

#include <errno.h>
#include "gtest/gtest.h"

using namespace librados;

TEST(LibRadosIo, SimpleWrite) {
  char buf[128];
  rados_t cluster;
  rados_ioctx_t ioctx;
  std::string pool_name = get_temp_pool_name();
  ASSERT_EQ("", create_one_pool(pool_name, &cluster));
  rados_ioctx_create(cluster, pool_name.c_str(), &ioctx);
  memset(buf, 0xcc, sizeof(buf));
  ASSERT_EQ((int)sizeof(buf), rados_write(ioctx, "foo", buf, sizeof(buf), 0));
  rados_ioctx_destroy(ioctx);
  ASSERT_EQ(0, destroy_one_pool(pool_name, &cluster));
}

TEST(LibRadosIo, SimpleWritePP) {
  char buf[128];
  std::string pool_name = get_temp_pool_name();
  Rados cluster;
  ASSERT_EQ("", create_one_pool_pp(pool_name, cluster));
  IoCtx ioctx;
  cluster.ioctx_create(pool_name.c_str(), ioctx);
  memset(buf, 0xcc, sizeof(buf));
  bufferlist bl;
  bl.append(buf, sizeof(buf));
  ASSERT_EQ((int)sizeof(buf), ioctx.write("foo", bl, sizeof(buf), 0));
  ioctx.close();
  ASSERT_EQ(0, destroy_one_pool_pp(pool_name, cluster));
}

TEST(LibRadosIo, RoundTrip) {
  char buf[128];
  char buf2[128];
  rados_t cluster;
  rados_ioctx_t ioctx;
  std::string pool_name = get_temp_pool_name();
  ASSERT_EQ("", create_one_pool(pool_name, &cluster));
  rados_ioctx_create(cluster, pool_name.c_str(), &ioctx);
  memset(buf, 0xcc, sizeof(buf));
  ASSERT_EQ((int)sizeof(buf), rados_write(ioctx, "foo", buf, sizeof(buf), 0));
  memset(buf2, 0, sizeof(buf2));
  ASSERT_EQ((int)sizeof(buf2), rados_read(ioctx, "foo", buf2, sizeof(buf2), 0));
  ASSERT_EQ(0, memcmp(buf, buf2, sizeof(buf)));
  rados_ioctx_destroy(ioctx);
  ASSERT_EQ(0, destroy_one_pool(pool_name, &cluster));
}

TEST(LibRadosIo, OverlappingWriteRoundTrip) {
  char buf[128];
  char buf2[64];
  char buf3[128];
  rados_t cluster;
  rados_ioctx_t ioctx;
  std::string pool_name = get_temp_pool_name();
  ASSERT_EQ("", create_one_pool(pool_name, &cluster));
  rados_ioctx_create(cluster, pool_name.c_str(), &ioctx);
  memset(buf, 0xcc, sizeof(buf));
  ASSERT_EQ((int)sizeof(buf), rados_write(ioctx, "foo", buf, sizeof(buf), 0));
  memset(buf2, 0xdd, sizeof(buf2));
  ASSERT_EQ((int)sizeof(buf2), rados_write(ioctx, "foo", buf2, sizeof(buf2), 0));
  memset(buf3, 0xdd, sizeof(buf3));
  ASSERT_EQ((int)sizeof(buf3), rados_read(ioctx, "foo", buf3, sizeof(buf3), 0));
  ASSERT_EQ(0, memcmp(buf3, buf2, sizeof(buf2)));
  ASSERT_EQ(0, memcmp(buf3 + sizeof(buf2), buf, sizeof(buf) - sizeof(buf2)));
  rados_ioctx_destroy(ioctx);
  ASSERT_EQ(0, destroy_one_pool(pool_name, &cluster));
}

TEST(LibRadosIo, WriteFullRoundTrip) {
  char buf[128];
  char buf2[64];
  char buf3[128];
  rados_t cluster;
  rados_ioctx_t ioctx;
  std::string pool_name = get_temp_pool_name();
  ASSERT_EQ("", create_one_pool(pool_name, &cluster));
  rados_ioctx_create(cluster, pool_name.c_str(), &ioctx);
  memset(buf, 0xcc, sizeof(buf));
  ASSERT_EQ((int)sizeof(buf), rados_write(ioctx, "foo", buf, sizeof(buf), 0));
  memset(buf2, 0xdd, sizeof(buf2));
  ASSERT_EQ(0, rados_write_full(ioctx, "foo", buf2, sizeof(buf2), 0));
  memset(buf3, 0xdd, sizeof(buf3));
  ASSERT_EQ((int)sizeof(buf2), rados_read(ioctx, "foo", buf3, sizeof(buf3), 0));
  ASSERT_EQ(0, memcmp(buf2, buf2, sizeof(buf2)));
  rados_ioctx_destroy(ioctx);
  ASSERT_EQ(0, destroy_one_pool(pool_name, &cluster));
}

TEST(LibRadosIo, AppendRoundTrip) {
  char buf[64];
  char buf2[64];
  char buf3[sizeof(buf) + sizeof(buf2)];
  rados_t cluster;
  rados_ioctx_t ioctx;
  std::string pool_name = get_temp_pool_name();
  ASSERT_EQ("", create_one_pool(pool_name, &cluster));
  rados_ioctx_create(cluster, pool_name.c_str(), &ioctx);
  memset(buf, 0xde, sizeof(buf));
  ASSERT_EQ((int)sizeof(buf), rados_append(ioctx, "foo", buf, sizeof(buf)));
  memset(buf2, 0xad, sizeof(buf2));
  ASSERT_EQ((int)sizeof(buf2), rados_append(ioctx, "foo", buf2, sizeof(buf2)));
  memset(buf3, 0, sizeof(buf3));
  ASSERT_EQ((int)sizeof(buf3), rados_read(ioctx, "foo", buf3, sizeof(buf3), 0));
  ASSERT_EQ(0, memcmp(buf3, buf, sizeof(buf)));
  ASSERT_EQ(0, memcmp(buf3 + sizeof(buf), buf2, sizeof(buf2)));
  rados_ioctx_destroy(ioctx);
  ASSERT_EQ(0, destroy_one_pool(pool_name, &cluster));
}

TEST(LibRadosIo, TruncTest) {
  char buf[128];
  char buf2[sizeof(buf)];
  rados_t cluster;
  rados_ioctx_t ioctx;
  std::string pool_name = get_temp_pool_name();
  ASSERT_EQ("", create_one_pool(pool_name, &cluster));
  rados_ioctx_create(cluster, pool_name.c_str(), &ioctx);
  memset(buf, 0xaa, sizeof(buf));
  ASSERT_EQ((int)sizeof(buf), rados_append(ioctx, "foo", buf, sizeof(buf)));
  ASSERT_EQ(0, rados_trunc(ioctx, "foo", sizeof(buf) / 2));
  memset(buf2, 0, sizeof(buf2));
  ASSERT_EQ((int)(sizeof(buf)/2), rados_read(ioctx, "foo", buf2, sizeof(buf2), 0));
  ASSERT_EQ(0, memcmp(buf, buf2, sizeof(buf)/2));
  rados_ioctx_destroy(ioctx);
  ASSERT_EQ(0, destroy_one_pool(pool_name, &cluster));
}

TEST(LibRadosIo, RemoveTest) {
  char buf[128];
  char buf2[sizeof(buf)];
  rados_t cluster;
  rados_ioctx_t ioctx;
  std::string pool_name = get_temp_pool_name();
  ASSERT_EQ("", create_one_pool(pool_name, &cluster));
  rados_ioctx_create(cluster, pool_name.c_str(), &ioctx);
  memset(buf, 0xaa, sizeof(buf));
  ASSERT_EQ((int)sizeof(buf), rados_append(ioctx, "foo", buf, sizeof(buf)));
  ASSERT_EQ(0, rados_remove(ioctx, "foo"));
  memset(buf2, 0, sizeof(buf2));
  ASSERT_EQ(-ENOENT, rados_read(ioctx, "foo", buf2, sizeof(buf2), 0));
  rados_ioctx_destroy(ioctx);
  ASSERT_EQ(0, destroy_one_pool(pool_name, &cluster));
}

TEST(LibRadosIo, XattrsRoundTrip) {
  char buf[128];
  char attr1[] = "attr1";
  char attr1_buf[] = "foo bar baz";
  rados_t cluster;
  rados_ioctx_t ioctx;
  std::string pool_name = get_temp_pool_name();
  ASSERT_EQ("", create_one_pool(pool_name, &cluster));
  rados_ioctx_create(cluster, pool_name.c_str(), &ioctx);
  memset(buf, 0xaa, sizeof(buf));
  ASSERT_EQ((int)sizeof(buf), rados_append(ioctx, "foo", buf, sizeof(buf)));
  ASSERT_EQ(-ENODATA, rados_getxattr(ioctx, "foo", attr1, buf, sizeof(buf)));
  ASSERT_EQ((int)sizeof(attr1_buf),
      rados_setxattr(ioctx, "foo", attr1, attr1_buf, sizeof(attr1_buf)));
  ASSERT_EQ((int)sizeof(attr1_buf),
	    rados_getxattr(ioctx, "foo", attr1, buf, sizeof(buf)));
  ASSERT_EQ(0, memcmp(attr1_buf, buf, sizeof(attr1_buf)));
  rados_ioctx_destroy(ioctx);
  ASSERT_EQ(0, destroy_one_pool(pool_name, &cluster));
}

TEST(LibRadosIo, RmXattr) {
  char buf[128];
  char attr1[] = "attr1";
  char attr1_buf[] = "foo bar baz";
  rados_t cluster;
  rados_ioctx_t ioctx;
  std::string pool_name = get_temp_pool_name();
  ASSERT_EQ("", create_one_pool(pool_name, &cluster));
  rados_ioctx_create(cluster, pool_name.c_str(), &ioctx);
  memset(buf, 0xaa, sizeof(buf));
  ASSERT_EQ((int)sizeof(buf), rados_append(ioctx, "foo", buf, sizeof(buf)));
  ASSERT_EQ((int)sizeof(attr1_buf),
      rados_setxattr(ioctx, "foo", attr1, attr1_buf, sizeof(attr1_buf)));
  ASSERT_EQ(0, rados_rmxattr(ioctx, "foo", attr1));
  ASSERT_EQ(-ENODATA, rados_getxattr(ioctx, "foo", attr1, buf, sizeof(buf)));
  rados_ioctx_destroy(ioctx);
  ASSERT_EQ(0, destroy_one_pool(pool_name, &cluster));
}

TEST(LibRadosIo, XattrIter) {
  char buf[128];
  char attr1[] = "attr1";
  char attr1_buf[] = "foo bar baz";
  char attr2[] = "attr2";
  char attr2_buf[256];
  for (size_t j = 0; j < sizeof(attr2_buf); ++j) {
    attr2_buf[j] = j % 0xff;
  }
  rados_t cluster;
  rados_ioctx_t ioctx;
  std::string pool_name = get_temp_pool_name();
  ASSERT_EQ("", create_one_pool(pool_name, &cluster));
  rados_ioctx_create(cluster, pool_name.c_str(), &ioctx);
  memset(buf, 0xaa, sizeof(buf));
  ASSERT_EQ((int)sizeof(buf), rados_append(ioctx, "foo", buf, sizeof(buf)));
  ASSERT_EQ((int)sizeof(attr1_buf),
      rados_setxattr(ioctx, "foo", attr1, attr1_buf, sizeof(attr1_buf)));
  ASSERT_EQ((int)sizeof(attr2_buf),
      rados_setxattr(ioctx, "foo", attr2, attr2_buf, sizeof(attr2_buf)));
  rados_xattrs_iter_t iter;
  ASSERT_EQ(0, rados_getxattrs(ioctx, "foo", &iter));
  int num_seen = 0;
  while (true) {
    const char *name;
    const char *val;
    size_t len;
    ASSERT_EQ(0, rados_getxattrs_next(iter, &name, &val, &len));
    if (name == NULL) {
      break;
    }
    ASSERT_LT(num_seen, 2);
    if ((strcmp(name, attr1) == 0) && (memcmp(val, attr1_buf, len) == 0)) {
      num_seen++;
      continue;
    }
    else if ((strcmp(name, attr2) == 0) && (memcmp(val, attr2_buf, len) == 0)) {
      num_seen++;
      continue;
    }
    else {
      ASSERT_EQ(0, 1);
    }
  }
  rados_getxattrs_end(iter);
  rados_ioctx_destroy(ioctx);
  ASSERT_EQ(0, destroy_one_pool(pool_name, &cluster));
}
<commit_msg>test/rados-api/io.cc: test RoundTripPP, etc.<commit_after>#include "include/rados/librados.h"
#include "include/rados/librados.hpp"
#include "test/rados-api/test.h"

#include <errno.h>
#include "gtest/gtest.h"

using namespace librados;

TEST(LibRadosIo, SimpleWrite) {
  char buf[128];
  rados_t cluster;
  rados_ioctx_t ioctx;
  std::string pool_name = get_temp_pool_name();
  ASSERT_EQ("", create_one_pool(pool_name, &cluster));
  rados_ioctx_create(cluster, pool_name.c_str(), &ioctx);
  memset(buf, 0xcc, sizeof(buf));
  ASSERT_EQ((int)sizeof(buf), rados_write(ioctx, "foo", buf, sizeof(buf), 0));
  rados_ioctx_destroy(ioctx);
  ASSERT_EQ(0, destroy_one_pool(pool_name, &cluster));
}

TEST(LibRadosIo, SimpleWritePP) {
  char buf[128];
  std::string pool_name = get_temp_pool_name();
  Rados cluster;
  ASSERT_EQ("", create_one_pool_pp(pool_name, cluster));
  IoCtx ioctx;
  cluster.ioctx_create(pool_name.c_str(), ioctx);
  memset(buf, 0xcc, sizeof(buf));
  bufferlist bl;
  bl.append(buf, sizeof(buf));
  ASSERT_EQ((int)sizeof(buf), ioctx.write("foo", bl, sizeof(buf), 0));
  ioctx.close();
  ASSERT_EQ(0, destroy_one_pool_pp(pool_name, cluster));
}

TEST(LibRadosIo, RoundTrip) {
  char buf[128];
  char buf2[128];
  rados_t cluster;
  rados_ioctx_t ioctx;
  std::string pool_name = get_temp_pool_name();
  ASSERT_EQ("", create_one_pool(pool_name, &cluster));
  rados_ioctx_create(cluster, pool_name.c_str(), &ioctx);
  memset(buf, 0xcc, sizeof(buf));
  ASSERT_EQ((int)sizeof(buf), rados_write(ioctx, "foo", buf, sizeof(buf), 0));
  memset(buf2, 0, sizeof(buf2));
  ASSERT_EQ((int)sizeof(buf2), rados_read(ioctx, "foo", buf2, sizeof(buf2), 0));
  ASSERT_EQ(0, memcmp(buf, buf2, sizeof(buf)));
  rados_ioctx_destroy(ioctx);
  ASSERT_EQ(0, destroy_one_pool(pool_name, &cluster));
}

TEST(LibRadosIo, RoundTripPP) {
  char buf[128];
  char buf2[128];
  Rados cluster;
  std::string pool_name = get_temp_pool_name();
  ASSERT_EQ("", create_one_pool_pp(pool_name, cluster));
  IoCtx ioctx;
  cluster.ioctx_create(pool_name.c_str(), ioctx);
  memset(buf, 0xcc, sizeof(buf));
  bufferlist bl;
  bl.append(buf, sizeof(buf));
  ASSERT_EQ((int)sizeof(buf), ioctx.write("foo", bl, sizeof(buf), 0));
  bufferlist cl;
  ASSERT_EQ((int)sizeof(buf2), ioctx.read("foo", cl, sizeof(buf), 0));
  ASSERT_EQ(0, memcmp(buf, cl.c_str(), sizeof(buf)));
  ioctx.close();
  ASSERT_EQ(0, destroy_one_pool_pp(pool_name, cluster));
}

TEST(LibRadosIo, OverlappingWriteRoundTrip) {
  char buf[128];
  char buf2[64];
  char buf3[128];
  rados_t cluster;
  rados_ioctx_t ioctx;
  std::string pool_name = get_temp_pool_name();
  ASSERT_EQ("", create_one_pool(pool_name, &cluster));
  rados_ioctx_create(cluster, pool_name.c_str(), &ioctx);
  memset(buf, 0xcc, sizeof(buf));
  ASSERT_EQ((int)sizeof(buf), rados_write(ioctx, "foo", buf, sizeof(buf), 0));
  memset(buf2, 0xdd, sizeof(buf2));
  ASSERT_EQ((int)sizeof(buf2), rados_write(ioctx, "foo", buf2, sizeof(buf2), 0));
  memset(buf3, 0xdd, sizeof(buf3));
  ASSERT_EQ((int)sizeof(buf3), rados_read(ioctx, "foo", buf3, sizeof(buf3), 0));
  ASSERT_EQ(0, memcmp(buf3, buf2, sizeof(buf2)));
  ASSERT_EQ(0, memcmp(buf3 + sizeof(buf2), buf, sizeof(buf) - sizeof(buf2)));
  rados_ioctx_destroy(ioctx);
  ASSERT_EQ(0, destroy_one_pool(pool_name, &cluster));
}

TEST(LibRadosIo, OverlappingWriteRoundTripPP) {
  char buf[128];
  char buf2[64];
  Rados cluster;
  std::string pool_name = get_temp_pool_name();
  ASSERT_EQ("", create_one_pool_pp(pool_name, cluster));
  IoCtx ioctx;
  cluster.ioctx_create(pool_name.c_str(), ioctx);
  memset(buf, 0xcc, sizeof(buf));
  bufferlist bl1;
  bl1.append(buf, sizeof(buf));
  ASSERT_EQ((int)sizeof(buf), ioctx.write("foo", bl1, sizeof(buf), 0));
  memset(buf2, 0xdd, sizeof(buf2));
  bufferlist bl2;
  bl2.append(buf2, sizeof(buf2));
  ASSERT_EQ((int)sizeof(buf2), ioctx.write("foo", bl2, sizeof(buf2), 0));
  bufferlist bl3;
  ASSERT_EQ((int)sizeof(buf), ioctx.read("foo", bl3, sizeof(buf), 0));
  ASSERT_EQ(0, memcmp(bl3.c_str(), buf2, sizeof(buf2)));
  ASSERT_EQ(0, memcmp(bl3.c_str() + sizeof(buf2), buf, sizeof(buf) - sizeof(buf2)));
  ioctx.close();
  ASSERT_EQ(0, destroy_one_pool_pp(pool_name, cluster));
}

TEST(LibRadosIo, WriteFullRoundTrip) {
  char buf[128];
  char buf2[64];
  char buf3[128];
  rados_t cluster;
  rados_ioctx_t ioctx;
  std::string pool_name = get_temp_pool_name();
  ASSERT_EQ("", create_one_pool(pool_name, &cluster));
  rados_ioctx_create(cluster, pool_name.c_str(), &ioctx);
  memset(buf, 0xcc, sizeof(buf));
  ASSERT_EQ((int)sizeof(buf), rados_write(ioctx, "foo", buf, sizeof(buf), 0));
  memset(buf2, 0xdd, sizeof(buf2));
  ASSERT_EQ(0, rados_write_full(ioctx, "foo", buf2, sizeof(buf2), 0));
  memset(buf3, 0xdd, sizeof(buf3));
  ASSERT_EQ((int)sizeof(buf2), rados_read(ioctx, "foo", buf3, sizeof(buf3), 0));
  ASSERT_EQ(0, memcmp(buf2, buf2, sizeof(buf2)));
  rados_ioctx_destroy(ioctx);
  ASSERT_EQ(0, destroy_one_pool(pool_name, &cluster));
}

TEST(LibRadosIo, AppendRoundTrip) {
  char buf[64];
  char buf2[64];
  char buf3[sizeof(buf) + sizeof(buf2)];
  rados_t cluster;
  rados_ioctx_t ioctx;
  std::string pool_name = get_temp_pool_name();
  ASSERT_EQ("", create_one_pool(pool_name, &cluster));
  rados_ioctx_create(cluster, pool_name.c_str(), &ioctx);
  memset(buf, 0xde, sizeof(buf));
  ASSERT_EQ((int)sizeof(buf), rados_append(ioctx, "foo", buf, sizeof(buf)));
  memset(buf2, 0xad, sizeof(buf2));
  ASSERT_EQ((int)sizeof(buf2), rados_append(ioctx, "foo", buf2, sizeof(buf2)));
  memset(buf3, 0, sizeof(buf3));
  ASSERT_EQ((int)sizeof(buf3), rados_read(ioctx, "foo", buf3, sizeof(buf3), 0));
  ASSERT_EQ(0, memcmp(buf3, buf, sizeof(buf)));
  ASSERT_EQ(0, memcmp(buf3 + sizeof(buf), buf2, sizeof(buf2)));
  rados_ioctx_destroy(ioctx);
  ASSERT_EQ(0, destroy_one_pool(pool_name, &cluster));
}

TEST(LibRadosIo, TruncTest) {
  char buf[128];
  char buf2[sizeof(buf)];
  rados_t cluster;
  rados_ioctx_t ioctx;
  std::string pool_name = get_temp_pool_name();
  ASSERT_EQ("", create_one_pool(pool_name, &cluster));
  rados_ioctx_create(cluster, pool_name.c_str(), &ioctx);
  memset(buf, 0xaa, sizeof(buf));
  ASSERT_EQ((int)sizeof(buf), rados_append(ioctx, "foo", buf, sizeof(buf)));
  ASSERT_EQ(0, rados_trunc(ioctx, "foo", sizeof(buf) / 2));
  memset(buf2, 0, sizeof(buf2));
  ASSERT_EQ((int)(sizeof(buf)/2), rados_read(ioctx, "foo", buf2, sizeof(buf2), 0));
  ASSERT_EQ(0, memcmp(buf, buf2, sizeof(buf)/2));
  rados_ioctx_destroy(ioctx);
  ASSERT_EQ(0, destroy_one_pool(pool_name, &cluster));
}

TEST(LibRadosIo, RemoveTest) {
  char buf[128];
  char buf2[sizeof(buf)];
  rados_t cluster;
  rados_ioctx_t ioctx;
  std::string pool_name = get_temp_pool_name();
  ASSERT_EQ("", create_one_pool(pool_name, &cluster));
  rados_ioctx_create(cluster, pool_name.c_str(), &ioctx);
  memset(buf, 0xaa, sizeof(buf));
  ASSERT_EQ((int)sizeof(buf), rados_append(ioctx, "foo", buf, sizeof(buf)));
  ASSERT_EQ(0, rados_remove(ioctx, "foo"));
  memset(buf2, 0, sizeof(buf2));
  ASSERT_EQ(-ENOENT, rados_read(ioctx, "foo", buf2, sizeof(buf2), 0));
  rados_ioctx_destroy(ioctx);
  ASSERT_EQ(0, destroy_one_pool(pool_name, &cluster));
}

TEST(LibRadosIo, XattrsRoundTrip) {
  char buf[128];
  char attr1[] = "attr1";
  char attr1_buf[] = "foo bar baz";
  rados_t cluster;
  rados_ioctx_t ioctx;
  std::string pool_name = get_temp_pool_name();
  ASSERT_EQ("", create_one_pool(pool_name, &cluster));
  rados_ioctx_create(cluster, pool_name.c_str(), &ioctx);
  memset(buf, 0xaa, sizeof(buf));
  ASSERT_EQ((int)sizeof(buf), rados_append(ioctx, "foo", buf, sizeof(buf)));
  ASSERT_EQ(-ENODATA, rados_getxattr(ioctx, "foo", attr1, buf, sizeof(buf)));
  ASSERT_EQ((int)sizeof(attr1_buf),
      rados_setxattr(ioctx, "foo", attr1, attr1_buf, sizeof(attr1_buf)));
  ASSERT_EQ((int)sizeof(attr1_buf),
	    rados_getxattr(ioctx, "foo", attr1, buf, sizeof(buf)));
  ASSERT_EQ(0, memcmp(attr1_buf, buf, sizeof(attr1_buf)));
  rados_ioctx_destroy(ioctx);
  ASSERT_EQ(0, destroy_one_pool(pool_name, &cluster));
}

TEST(LibRadosIo, RmXattr) {
  char buf[128];
  char attr1[] = "attr1";
  char attr1_buf[] = "foo bar baz";
  rados_t cluster;
  rados_ioctx_t ioctx;
  std::string pool_name = get_temp_pool_name();
  ASSERT_EQ("", create_one_pool(pool_name, &cluster));
  rados_ioctx_create(cluster, pool_name.c_str(), &ioctx);
  memset(buf, 0xaa, sizeof(buf));
  ASSERT_EQ((int)sizeof(buf), rados_append(ioctx, "foo", buf, sizeof(buf)));
  ASSERT_EQ((int)sizeof(attr1_buf),
      rados_setxattr(ioctx, "foo", attr1, attr1_buf, sizeof(attr1_buf)));
  ASSERT_EQ(0, rados_rmxattr(ioctx, "foo", attr1));
  ASSERT_EQ(-ENODATA, rados_getxattr(ioctx, "foo", attr1, buf, sizeof(buf)));
  rados_ioctx_destroy(ioctx);
  ASSERT_EQ(0, destroy_one_pool(pool_name, &cluster));
}

TEST(LibRadosIo, XattrIter) {
  char buf[128];
  char attr1[] = "attr1";
  char attr1_buf[] = "foo bar baz";
  char attr2[] = "attr2";
  char attr2_buf[256];
  for (size_t j = 0; j < sizeof(attr2_buf); ++j) {
    attr2_buf[j] = j % 0xff;
  }
  rados_t cluster;
  rados_ioctx_t ioctx;
  std::string pool_name = get_temp_pool_name();
  ASSERT_EQ("", create_one_pool(pool_name, &cluster));
  rados_ioctx_create(cluster, pool_name.c_str(), &ioctx);
  memset(buf, 0xaa, sizeof(buf));
  ASSERT_EQ((int)sizeof(buf), rados_append(ioctx, "foo", buf, sizeof(buf)));
  ASSERT_EQ((int)sizeof(attr1_buf),
      rados_setxattr(ioctx, "foo", attr1, attr1_buf, sizeof(attr1_buf)));
  ASSERT_EQ((int)sizeof(attr2_buf),
      rados_setxattr(ioctx, "foo", attr2, attr2_buf, sizeof(attr2_buf)));
  rados_xattrs_iter_t iter;
  ASSERT_EQ(0, rados_getxattrs(ioctx, "foo", &iter));
  int num_seen = 0;
  while (true) {
    const char *name;
    const char *val;
    size_t len;
    ASSERT_EQ(0, rados_getxattrs_next(iter, &name, &val, &len));
    if (name == NULL) {
      break;
    }
    ASSERT_LT(num_seen, 2);
    if ((strcmp(name, attr1) == 0) && (memcmp(val, attr1_buf, len) == 0)) {
      num_seen++;
      continue;
    }
    else if ((strcmp(name, attr2) == 0) && (memcmp(val, attr2_buf, len) == 0)) {
      num_seen++;
      continue;
    }
    else {
      ASSERT_EQ(0, 1);
    }
  }
  rados_getxattrs_end(iter);
  rados_ioctx_destroy(ioctx);
  ASSERT_EQ(0, destroy_one_pool(pool_name, &cluster));
}
<|endoftext|>


<commit_before>/*The MIT License (MIT)

Copyright (c) 2017 k-brac

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
/**
* Switch betwenn member and static operator<< for serializing.
* Usefull if both are defined
*/
//#define CUTI_USE_MEMBER_SERIALIZE

/**
* Prepend test_ to all function declared using CUTI_TEST in XCode.
* Indeed XCode needs the prefix "test" to automatically detect test methods
*/
#define CUTI_PREPEND_TEST
#include "Cuti.h"
#undef CUTI_PREPEND_TEST
#include "ComputeInt.h"

CUTI_DEFAULT_TO_STRING(ComputeInt);

CUTI_TEST_CLASS(TestLibInt){
public:
	void simpleAssertTest() {
		ComputeInt c(5);
		CUTI_ASSERT(c.add(-2) != 0);
		CUTI_ASSERT(c.add(-2) != 0, "c.add should have returned a value != 0");
	}

	void assertThrowTest() {
		ComputeInt c(1);
		CUTI_ASSERT_THROW(c.divide(0), std::runtime_error);
		CUTI_ASSERT_THROW(c.divide(0), std::runtime_error, "Tried to divide by 0");
		//CUTI_ASSERT_ASSERTION_FAIL(CUTI_ASSERT_THROW(c.divide(0), std::logic_error));
	}

	void assertNoThrowTest() {
		ComputeInt c(1);
		CUTI_ASSERT_NO_THROW(c.divide(1));
		CUTI_ASSERT_NO_THROW(c.divide(1), "Should not have thrown");
		//CUTI_ASSERT_ASSERTION_FAIL(CUTI_ASSERT_NO_THROW(c.divide(0)));
	}

	void assertFailTest() {
			//CUTI_ASSERT_ASSERTION_FAIL(CUTI_FAIL("This test has failed"));
        uint16_t a = 0, b = 0;
        CUTI_ASSERT_EQUAL(a, b);
	}

	void assertLessTest() {
		ComputeInt c(5);
		//CUTI_ASSERT_ASSERTION_FAIL(CUTI_ASSERT_LESS(10, c.add(5)));
		CUTI_ASSERT_LESS(10, c.add(1));
		CUTI_ASSERT_LESSEQUAL(10, c.add(5));
		CUTI_ASSERT_LESSEQUAL(10, c.add(1));
		//CUTI_ASSERT_ASSERTION_FAIL(CUTI_ASSERT_LESSEQUAL(10, c.add(6)));
	}

	void assertGreaterTest() {
		ComputeInt c(5);
		//CUTI_ASSERT_ASSERTION_FAIL(CUTI_ASSERT_GREATER(11, c.add(5)));
		CUTI_ASSERT_GREATER(1, c.add(1));
		CUTI_ASSERT_GREATEREQUAL(1, c.add(5));
		CUTI_ASSERT_GREATEREQUAL(10, c.add(6));
		//CUTI_ASSERT_ASSERTION_FAIL(CUTI_ASSERT_GREATEREQUAL(10, c.add(1)));
	}

	void assertEqual() {
		ComputeInt c(5);
        ComputeInt c2(5);
		CUTI_ASSERT_EQUAL(5, c.add(0), "Should be equal");
		CUTI_ASSERT_EQUAL(5, c.add(0));
		//CUTI_ASSERT_ASSERTION_FAIL(CUTI_ASSERT_EQUAL(10, c.add(1)));
        CUTI_ASSERT_EQUAL(c, c2);
	}

    CUTI_BEGIN_TESTS_REGISTRATION(TestLibInt);
    CUTI_TEST(simpleAssertTest);
    CUTI_TEST(assertThrowTest);
    CUTI_TEST(assertNoThrowTest);
    CUTI_TEST(assertFailTest);
    CUTI_TEST(assertLessTest);
    CUTI_TEST(assertGreaterTest);
    CUTI_TEST(assertEqual);
    CUTI_END_TESTS_REGISTRATION();//must be the last statement in the class
};
<commit_msg>should fix visual studio 2017 compilation<commit_after>/*The MIT License (MIT)

Copyright (c) 2017 k-brac

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

/**
* Switch between member and static operator<< for serializing.
* Usefull if both are defined
*/
#define CUTI_USE_MEMBER_SERIALIZE

/**
* Prepend test_ to all function declared using CUTI_TEST in XCode.
* Indeed XCode needs the prefix "test" to automatically detect test methods
*/
#define CUTI_PREPEND_TEST
#include "Cuti.h"
#undef CUTI_PREPEND_TEST
#include "ComputeInt.h"

CUTI_DEFAULT_TO_STRING(ComputeInt);

CUTI_TEST_CLASS(TestLibInt){
public:
	void simpleAssertTest() {
		ComputeInt c(5);
		CUTI_ASSERT(c.add(-2) != 0);
		CUTI_ASSERT(c.add(-2) != 0, "c.add should have returned a value != 0");
	}

	void assertThrowTest() {
		ComputeInt c(1);
		CUTI_ASSERT_THROW(c.divide(0), std::runtime_error);
		CUTI_ASSERT_THROW(c.divide(0), std::runtime_error, "Tried to divide by 0");
		//CUTI_ASSERT_ASSERTION_FAIL(CUTI_ASSERT_THROW(c.divide(0), std::logic_error));
	}

	void assertNoThrowTest() {
		ComputeInt c(1);
		CUTI_ASSERT_NO_THROW(c.divide(1));
		CUTI_ASSERT_NO_THROW(c.divide(1), "Should not have thrown");
		//CUTI_ASSERT_ASSERTION_FAIL(CUTI_ASSERT_NO_THROW(c.divide(0)));
	}

	void assertFailTest() {
			//CUTI_ASSERT_ASSERTION_FAIL(CUTI_FAIL("This test has failed"));
        uint16_t a = 0, b = 0;
        CUTI_ASSERT_EQUAL(a, b);
	}

	void assertLessTest() {
		ComputeInt c(5);
		//CUTI_ASSERT_ASSERTION_FAIL(CUTI_ASSERT_LESS(10, c.add(5)));
		CUTI_ASSERT_LESS(10, c.add(1));
		CUTI_ASSERT_LESSEQUAL(10, c.add(5));
		CUTI_ASSERT_LESSEQUAL(10, c.add(1));
		//CUTI_ASSERT_ASSERTION_FAIL(CUTI_ASSERT_LESSEQUAL(10, c.add(6)));
	}

	void assertGreaterTest() {
		ComputeInt c(5);
		//CUTI_ASSERT_ASSERTION_FAIL(CUTI_ASSERT_GREATER(11, c.add(5)));
		CUTI_ASSERT_GREATER(1, c.add(1));
		CUTI_ASSERT_GREATEREQUAL(1, c.add(5));
		CUTI_ASSERT_GREATEREQUAL(10, c.add(6));
		//CUTI_ASSERT_ASSERTION_FAIL(CUTI_ASSERT_GREATEREQUAL(10, c.add(1)));
	}

	void assertEqual() {
		ComputeInt c(5);
        ComputeInt c2(5);
		CUTI_ASSERT_EQUAL(5, c.add(0), "Should be equal");
		CUTI_ASSERT_EQUAL(5, c.add(0));
		//CUTI_ASSERT_ASSERTION_FAIL(CUTI_ASSERT_EQUAL(10, c.add(1)));
        CUTI_ASSERT_EQUAL(c, c2);
	}

    CUTI_BEGIN_TESTS_REGISTRATION(TestLibInt);
    CUTI_TEST(simpleAssertTest);
    CUTI_TEST(assertThrowTest);
    CUTI_TEST(assertNoThrowTest);
    CUTI_TEST(assertFailTest);
    CUTI_TEST(assertLessTest);
    CUTI_TEST(assertGreaterTest);
    CUTI_TEST(assertEqual);
    CUTI_END_TESTS_REGISTRATION();//must be the last statement in the class
};
<|endoftext|>


<commit_before>#include "util.h"

#include "clientversion.h"
#include "primitives/transaction.h"
#include "random.h"
#include "sync.h"
#include "utilstrencodings.h"
#include "utilmoneystr.h"
#include "test/test_bitcoin.h"

#include <stdint.h>
#include <vector>

#include "chainparams.h"
#include "consensus/consensus.h"
#include "consensus/validation.h"
#include "key.h"
#include "validation.h"
#include "miner.h"
#include "pubkey.h"
#include "random.h"
#include "txdb.h"
#include "txmempool.h"
#include "ui_interface.h"
#include "rpc/server.h"
#include "rpc/register.h"
#include "zerocoin.h"
#include "znodeman.h"
#include "znode-sync.h"
#include "znode-payments.h"

#include "test/testutil.h"
#include "consensus/merkle.h"

#include "wallet/db.h"
#include "wallet/wallet.h"

#include <boost/filesystem.hpp>
#include <boost/test/unit_test.hpp>
#include <boost/thread.hpp>

extern CCriticalSection cs_main;
using namespace std;

CScript scriptPubKeyZnode;

struct ZnodeTestingSetup : public TestingSetup {
    ZnodeTestingSetup() : TestingSetup(CBaseChainParams::REGTEST)
    {
        CPubKey newKey;
        BOOST_CHECK(pwalletMain->GetKeyFromPool(newKey));

        string strAddress = CBitcoinAddress(newKey.GetID()).ToString();
        pwalletMain->SetAddressBook(CBitcoinAddress(strAddress).Get(), "",
                               ( "receive"));

        scriptPubKeyZnode = CScript() <<  ToByteVector(newKey/*coinbaseKey.GetPubKey()*/) << OP_CHECKSIG;
        bool mtp = false;
        CBlock b;
        for (int i = 0; i < 150; i++)
        {
            std::vector<CMutableTransaction> noTxns;
            b = CreateAndProcessBlock(noTxns, scriptPubKeyZnode, mtp);
            coinbaseTxns.push_back(*b.vtx[0]);
            LOCK(cs_main);
            {
                LOCK(pwalletMain->cs_wallet);
                pwalletMain->AddToWalletIfInvolvingMe(*b.vtx[0], chainActive.Tip(), 0, true);
            }
        }
    }

    CBlock CreateBlock(const std::vector<CMutableTransaction>& txns,
                       const CScript& scriptPubKeyZnode, bool mtp = false) {
        const CChainParams& chainparams = Params();
        std::unique_ptr<CBlockTemplate> pblocktemplate = BlockAssembler(chainparams).CreateNewBlock(scriptPubKeyZnode);
        CBlock block = pblocktemplate->block;

        // Replace mempool-selected txns with just coinbase plus passed-in txns:
        if(txns.size() > 0) {
            block.vtx.resize(1);
            BOOST_FOREACH(const CMutableTransaction& tx, txns)
                block.vtx.push_back(MakeTransactionRef(tx));
        }
        // IncrementExtraNonce creates a valid coinbase and merkleRoot
        unsigned int extraNonce = 0;
        IncrementExtraNonce(&block, chainActive.Tip(), extraNonce);

        while (!CheckProofOfWork(block.GetHash(), block.nBits, chainparams.GetConsensus())){
            ++block.nNonce;
        }
        if(mtp) {
            while (!CheckMerkleTreeProof(block, chainparams.GetConsensus())){
                block.mtpHashValue = mtp::hash(block, Params().GetConsensus().powLimit);
            }
        }
        else {
            while (!CheckProofOfWork(block.GetHash(), block.nBits, chainparams.GetConsensus())){
                ++block.nNonce;
            }
        }

        //delete pblocktemplate;
        return block;
    }

    bool ProcessBlock(const CBlock &block) {
        const CChainParams& chainparams = Params();
        return ProcessNewBlock(chainparams, std::make_shared<const CBlock>(block), true, NULL);
    }

    // Create a new block with just given transactions, coinbase paying to
    // scriptPubKeyZnode, and try to add it to the current chain.
    CBlock CreateAndProcessBlock(const std::vector<CMutableTransaction>& txns,
                                 const CScript& scriptPubKeyZnode, bool mtp = false){

        CBlock block = CreateBlock(txns, scriptPubKeyZnode, mtp);
        BOOST_CHECK_MESSAGE(ProcessBlock(block), "Processing block failed");
        return block;
    }

    std::vector<CTransaction> coinbaseTxns; // For convenience, coinbase transactions
    CKey coinbaseKey; // private/public key needed to spend coinbase transactions
};

BOOST_FIXTURE_TEST_SUITE(znode_tests, ZnodeTestingSetup)

BOOST_AUTO_TEST_CASE(Test_EnforceZnodePayment)
{

    std::vector<CMutableTransaction> noTxns;
    CBlock b = CreateAndProcessBlock(noTxns, scriptPubKeyZnode, false);
    const CChainParams& chainparams = Params();

    CMutableTransaction tx = *b.vtx[0];
    bool mutated;
    b.fChecked = false;
    b.hashMerkleRoot = BlockMerkleRoot(b, &mutated);
    while (!CheckProofOfWork(b.GetHash(), b.nBits, chainparams.GetConsensus())){
        ++b.nNonce;
    }

    BOOST_CHECK(CTransaction(tx).IsCoinBase());

    CValidationState state;
    BOOST_CHECK(true == CheckBlock(b, state, chainparams.GetConsensus()));
    //BOOST_CHECK(true == CheckTransaction(tx, state, tx.GetHash(), false, INT_MAX));

    auto const before_block = ZC_ZNODE_PAYMENT_BUG_FIXED_AT_BLOCK
             , after_block = ZC_ZNODE_PAYMENT_BUG_FIXED_AT_BLOCK + 1;
    // Emulates synced state of znodes.
    for(size_t i =0; i < 4; ++i)
        znodeSync.SwitchToNextAsset();

    ///////////////////////////////////////////////////////////////////////////
    // Paying to the best payee
    CZnodePayee payee1(tx.vout[1].scriptPubKey, uint256());
    // Emulates 6 votes for the payee
    for(size_t i =0; i < 5; ++i)
        payee1.AddVoteHash(uint256());

    CZnodeBlockPayees payees;
    payees.vecPayees.push_back(payee1);

    znpayments.mapZnodeBlocks[after_block] = payees;

    b.fChecked = false;
    b.hashMerkleRoot = BlockMerkleRoot(b, &mutated);
    while (!CheckProofOfWork(b.GetHash(), b.nBits, chainparams.GetConsensus())){
        ++b.nNonce;
    }
    BOOST_CHECK(true == CheckBlock(b, state, chainparams.GetConsensus()));
    BOOST_CHECK(true == CheckTransaction(tx, state, true, tx.GetHash(), false, after_block));

    ///////////////////////////////////////////////////////////////////////////
    // Paying to a completely wrong payee
    CMutableTransaction txCopy = tx;
    txCopy.vout[1].scriptPubKey = txCopy.vout[0].scriptPubKey;
    b.vtx[0] = MakeTransactionRef(txCopy);
    b.fChecked = false;
    b.hashMerkleRoot = BlockMerkleRoot(b, &mutated);
    while (!CheckProofOfWork(b.GetHash(), b.nBits, chainparams.GetConsensus())){
        ++b.nNonce;
    }
    BOOST_CHECK(false == CheckBlock(b, state, chainparams.GetConsensus()));
    BOOST_CHECK(true == CheckTransaction(*b.vtx[0], state, true, tx.GetHash(), false, after_block));

    ///////////////////////////////////////////////////////////////////////////
    // Making znodes not synchronized and checking the functionality is disabled
    znodeSync.Reset();
    b.fChecked = false;
    b.hashMerkleRoot = BlockMerkleRoot(b, &mutated);
    while (!CheckProofOfWork(b.GetHash(), b.nBits, chainparams.GetConsensus())){
        ++b.nNonce;
    }
    BOOST_CHECK(true == CheckTransaction(*b.vtx[0], state, true, tx.GetHash(), false, after_block));

    ///////////////////////////////////////////////////////////////////////////
    // Paying to an acceptable payee
    for(size_t i =0; i < 4; ++i)
        znodeSync.SwitchToNextAsset();

    CZnodePayee payee2(tx.vout[0].scriptPubKey, uint256());
    // Emulates 9 votes for the payee
    for(size_t i =0; i < 8; ++i)
        payee2.AddVoteHash(uint256());

    znpayments.mapZnodeBlocks[after_block].vecPayees.insert(znpayments.mapZnodeBlocks[after_block].vecPayees.begin(), payee2);

    txCopy.vout[1].scriptPubKey = payee1.GetPayee();
    b.vtx[0] = MakeTransactionRef(txCopy);
    b.fChecked = false;
    b.hashMerkleRoot = BlockMerkleRoot(b, &mutated);
    while (!CheckProofOfWork(b.GetHash(), b.nBits, chainparams.GetConsensus())){
        ++b.nNonce;
    }
    BOOST_CHECK(true == CheckBlock(b, state, chainparams.GetConsensus()));
    BOOST_CHECK(true == CheckTransaction(*b.vtx[0], state, true, tx.GetHash(), false, after_block));

    ///////////////////////////////////////////////////////////////////////////
    // Checking the functionality is disabled for previous blocks
    txCopy.vout[1].scriptPubKey = txCopy.vout[2].scriptPubKey;
    b.vtx[0] = MakeTransactionRef(txCopy);
    b.fChecked = false;
    b.hashMerkleRoot = BlockMerkleRoot(b, &mutated);
    while (!CheckProofOfWork(b.GetHash(), b.nBits, chainparams.GetConsensus())){
        ++b.nNonce;
    }
    BOOST_CHECK(false == CheckBlock(b, state, chainparams.GetConsensus()));
    BOOST_CHECK(true == CheckTransaction(*b.vtx[0], state, true, tx.GetHash(), false, after_block));

    znpayments.mapZnodeBlocks[before_block] = payees;

    b.fChecked = false;
    b.hashMerkleRoot = BlockMerkleRoot(b, &mutated);
    while (!CheckProofOfWork(b.GetHash(), b.nBits, chainparams.GetConsensus())){
        ++b.nNonce;
    }
    BOOST_CHECK(true == CheckTransaction(*b.vtx[0], state, true, tx.GetHash(), false, before_block));
}

BOOST_AUTO_TEST_SUITE_END()
<commit_msg>Znode test fix<commit_after>#include "util.h"

#include "clientversion.h"
#include "primitives/transaction.h"
#include "random.h"
#include "sync.h"
#include "utilstrencodings.h"
#include "utilmoneystr.h"
#include "test/test_bitcoin.h"

#include <stdint.h>
#include <vector>

#include "chainparams.h"
#include "consensus/consensus.h"
#include "consensus/validation.h"
#include "key.h"
#include "validation.h"
#include "miner.h"
#include "pubkey.h"
#include "random.h"
#include "txdb.h"
#include "txmempool.h"
#include "ui_interface.h"
#include "rpc/server.h"
#include "rpc/register.h"
#include "zerocoin.h"
#include "znodeman.h"
#include "znode-sync.h"
#include "znode-payments.h"

#include "test/testutil.h"
#include "consensus/merkle.h"

#include "wallet/db.h"
#include "wallet/wallet.h"

#include <boost/filesystem.hpp>
#include <boost/test/unit_test.hpp>
#include <boost/thread.hpp>

extern CCriticalSection cs_main;
using namespace std;

CScript scriptPubKeyZnode;

struct ZnodeTestingSetup : public TestingSetup {
    ZnodeTestingSetup() : TestingSetup(CBaseChainParams::REGTEST)
    {
        CPubKey newKey;
        BOOST_CHECK(pwalletMain->GetKeyFromPool(newKey));

        string strAddress = CBitcoinAddress(newKey.GetID()).ToString();
        pwalletMain->SetAddressBook(CBitcoinAddress(strAddress).Get(), "",
                               ( "receive"));

        scriptPubKeyZnode = CScript() <<  ToByteVector(newKey/*coinbaseKey.GetPubKey()*/) << OP_CHECKSIG;
        bool mtp = false;
        CBlock b;
        for (int i = 0; i < 150; i++)
        {
            std::vector<CMutableTransaction> noTxns;
            b = CreateAndProcessBlock(noTxns, scriptPubKeyZnode, mtp);
            coinbaseTxns.push_back(*b.vtx[0]);
            LOCK(cs_main);
            {
                LOCK(pwalletMain->cs_wallet);
                pwalletMain->AddToWalletIfInvolvingMe(*b.vtx[0], chainActive.Tip(), 0, true);
            }
        }
    }

    CBlock CreateBlock(const std::vector<CMutableTransaction>& txns,
                       const CScript& scriptPubKeyZnode, bool mtp = false) {
        const CChainParams& chainparams = Params();
        std::unique_ptr<CBlockTemplate> pblocktemplate = BlockAssembler(chainparams).CreateNewBlock(scriptPubKeyZnode);
        CBlock block = pblocktemplate->block;

        // Replace mempool-selected txns with just coinbase plus passed-in txns:
        if(txns.size() > 0) {
            block.vtx.resize(1);
            BOOST_FOREACH(const CMutableTransaction& tx, txns)
                block.vtx.push_back(MakeTransactionRef(tx));
        }
        // IncrementExtraNonce creates a valid coinbase and merkleRoot
        unsigned int extraNonce = 0;
        IncrementExtraNonce(&block, chainActive.Tip(), extraNonce);

        while (!CheckProofOfWork(block.GetHash(), block.nBits, chainparams.GetConsensus())){
            ++block.nNonce;
        }
        if(mtp) {
            while (!CheckMerkleTreeProof(block, chainparams.GetConsensus())){
                block.mtpHashValue = mtp::hash(block, Params().GetConsensus().powLimit);
            }
        }
        else {
            while (!CheckProofOfWork(block.GetHash(), block.nBits, chainparams.GetConsensus())){
                ++block.nNonce;
            }
        }

        //delete pblocktemplate;
        return block;
    }

    bool ProcessBlock(const CBlock &block) {
        const CChainParams& chainparams = Params();
        return ProcessNewBlock(chainparams, std::make_shared<const CBlock>(block), true, NULL);
    }

    // Create a new block with just given transactions, coinbase paying to
    // scriptPubKeyZnode, and try to add it to the current chain.
    CBlock CreateAndProcessBlock(const std::vector<CMutableTransaction>& txns,
                                 const CScript& scriptPubKeyZnode, bool mtp = false){

        CBlock block = CreateBlock(txns, scriptPubKeyZnode, mtp);
        BOOST_CHECK_MESSAGE(ProcessBlock(block), "Processing block failed");
        return block;
    }

    std::vector<CTransaction> coinbaseTxns; // For convenience, coinbase transactions
    CKey coinbaseKey; // private/public key needed to spend coinbase transactions
};

BOOST_FIXTURE_TEST_SUITE(znode_tests, ZnodeTestingSetup)

namespace {
    size_t FindZnodeOutput(CTransaction const & tx) {
        static std::vector<CScript> const founders {
            GetScriptForDestination(CBitcoinAddress("TDk19wPKYq91i18qmY6U9FeTdTxwPeSveo").Get()),
            GetScriptForDestination(CBitcoinAddress("TWZZcDGkNixTAMtRBqzZkkMHbq1G6vUTk5").Get()),
            GetScriptForDestination(CBitcoinAddress("TRZTFdNCKCKbLMQV8cZDkQN9Vwuuq4gDzT").Get()),
            GetScriptForDestination(CBitcoinAddress("TG2ruj59E5b1u9G3F7HQVs6pCcVDBxrQve").Get()),
            GetScriptForDestination(CBitcoinAddress("TCsTzQZKVn4fao8jDmB9zQBk9YQNEZ3XfS").Get()),
        };

        BOOST_CHECK(tx.IsCoinBase());
        for(size_t i = 0; i < tx.vout.size(); ++i) {
            CTxOut const & out = tx.vout[i];
             if(std::find(founders.begin(), founders.end(), out.scriptPubKey) == founders.end()) {
                if(out.nValue == GetZnodePayment(Params().GetConsensus(), false))
                    return i;
            }
        }
        throw std::runtime_error("Cannot find the Znode output");
    }
}
BOOST_AUTO_TEST_CASE(Test_EnforceZnodePayment)
{

    std::vector<CMutableTransaction> noTxns;
    CBlock b = CreateAndProcessBlock(noTxns, scriptPubKeyZnode, false);
    const CChainParams& chainparams = Params();

    CMutableTransaction tx = *b.vtx[0];
    bool mutated;
    b.fChecked = false;
    b.hashMerkleRoot = BlockMerkleRoot(b, &mutated);
    while (!CheckProofOfWork(b.GetHash(), b.nBits, chainparams.GetConsensus())){
        ++b.nNonce;
    }

    BOOST_CHECK(CTransaction(tx).IsCoinBase());

    CValidationState state;
    BOOST_CHECK(true == CheckBlock(b, state, chainparams.GetConsensus()));
    //BOOST_CHECK(true == CheckTransaction(tx, state, tx.GetHash(), false, INT_MAX));

    auto const before_block = ZC_ZNODE_PAYMENT_BUG_FIXED_AT_BLOCK
             , after_block = ZC_ZNODE_PAYMENT_BUG_FIXED_AT_BLOCK + 1;
    // Emulates synced state of znodes.
    for(size_t i =0; i < 4; ++i)
        znodeSync.SwitchToNextAsset();

    ///////////////////////////////////////////////////////////////////////////
    // Paying to the best payee
    CZnodePayee payee1(tx.vout[1].scriptPubKey, uint256());
    // Emulates 6 votes for the payee
    for(size_t i =0; i < 5; ++i)
        payee1.AddVoteHash(uint256());

    CZnodeBlockPayees payees;
    payees.vecPayees.push_back(payee1);

    znpayments.mapZnodeBlocks[after_block] = payees;

    b.fChecked = false;
    b.hashMerkleRoot = BlockMerkleRoot(b, &mutated);
    while (!CheckProofOfWork(b.GetHash(), b.nBits, chainparams.GetConsensus())){
        ++b.nNonce;
    }
    BOOST_CHECK(true == CheckBlock(b, state, chainparams.GetConsensus()));
    BOOST_CHECK(true == CheckTransaction(tx, state, true, tx.GetHash(), false, after_block));

    ///////////////////////////////////////////////////////////////////////////
    // Paying to a completely wrong payee
    size_t const znodeOutput = FindZnodeOutput(tx);
    CMutableTransaction txCopy = tx;
    txCopy.vout[znodeOutput].scriptPubKey = txCopy.vout[0].scriptPubKey;
    b.vtx[0] = MakeTransactionRef(txCopy);
    b.fChecked = false;
    b.hashMerkleRoot = BlockMerkleRoot(b, &mutated);
    while (!CheckProofOfWork(b.GetHash(), b.nBits, chainparams.GetConsensus())){
        ++b.nNonce;
    }
    BOOST_CHECK(false == CheckBlock(b, state, chainparams.GetConsensus(), true, true, after_block));
    BOOST_CHECK(true == CheckTransaction(*b.vtx[0], state, true, tx.GetHash(), false, after_block));

    ///////////////////////////////////////////////////////////////////////////
    // Making znodes not synchronized and checking the functionality is disabled
    CTxOut storedCopy = tx.vout[znodeOutput];
    tx.vout.erase(tx.vout.begin() + znodeOutput);
    b.fChecked = false;
    b.hashMerkleRoot = BlockMerkleRoot(b, &mutated);
    while (!CheckProofOfWork(b.GetHash(), b.nBits, chainparams.GetConsensus())){
        ++b.nNonce;
    }

    BOOST_CHECK(false == CheckBlock(b, state, chainparams.GetConsensus(), true, true, after_block));
    BOOST_CHECK(true == CheckTransaction(*b.vtx[0], state, true, tx.GetHash(), false, after_block));

    tx.vout.insert(tx.vout.begin() + znodeOutput, storedCopy);

    ///////////////////////////////////////////////////////////////////////////
    // Making znodes not synchronized and checking the functionality is disabled
    znodeSync.Reset();
    b.fChecked = false;
    b.hashMerkleRoot = BlockMerkleRoot(b, &mutated);
    while (!CheckProofOfWork(b.GetHash(), b.nBits, chainparams.GetConsensus())){
        ++b.nNonce;
    }
    BOOST_CHECK(true == CheckTransaction(*b.vtx[0], state, true, tx.GetHash(), false, after_block));

    ///////////////////////////////////////////////////////////////////////////
    // Paying to an acceptable payee
    for(size_t i =0; i < 4; ++i)
        znodeSync.SwitchToNextAsset();

    CZnodePayee payee2(tx.vout[0].scriptPubKey, uint256());
    // Emulates 9 votes for the payee
    for(size_t i =0; i < 8; ++i)
        payee2.AddVoteHash(uint256());

    znpayments.mapZnodeBlocks[after_block].vecPayees.insert(znpayments.mapZnodeBlocks[after_block].vecPayees.begin(), payee2);

    txCopy.vout[1].scriptPubKey = payee1.GetPayee();
    b.vtx[0] = MakeTransactionRef(txCopy);
    b.fChecked = false;
    b.hashMerkleRoot = BlockMerkleRoot(b, &mutated);
    while (!CheckProofOfWork(b.GetHash(), b.nBits, chainparams.GetConsensus())){
        ++b.nNonce;
    }
    BOOST_CHECK(true == CheckBlock(b, state, chainparams.GetConsensus()));
    BOOST_CHECK(true == CheckTransaction(*b.vtx[0], state, true, tx.GetHash(), false, after_block));

    ///////////////////////////////////////////////////////////////////////////
    // Checking the functionality is disabled for previous blocks
    txCopy.vout[1].scriptPubKey = txCopy.vout[2].scriptPubKey;
    b.vtx[0] = MakeTransactionRef(txCopy);
    b.fChecked = false;
    b.hashMerkleRoot = BlockMerkleRoot(b, &mutated);
    while (!CheckProofOfWork(b.GetHash(), b.nBits, chainparams.GetConsensus())){
        ++b.nNonce;
    }
    BOOST_CHECK(false == CheckBlock(b, state, chainparams.GetConsensus()));
    BOOST_CHECK(true == CheckTransaction(*b.vtx[0], state, true, tx.GetHash(), false, after_block));

    znpayments.mapZnodeBlocks[before_block] = payees;

    b.fChecked = false;
    b.hashMerkleRoot = BlockMerkleRoot(b, &mutated);
    while (!CheckProofOfWork(b.GetHash(), b.nBits, chainparams.GetConsensus())){
        ++b.nNonce;
    }
    BOOST_CHECK(true == CheckTransaction(*b.vtx[0], state, true, tx.GetHash(), false, before_block));
}

BOOST_AUTO_TEST_SUITE_END()
<|endoftext|>


<commit_before>#include <QtCore/QString>
#include <QtCore/QHash>
#include <QtWidgets/QAction>
#include <QtGui/QKeySequence>
#include <QtCore/QDebug>
#include <QtCore/QEvent>
#include <QtGui/QActionEvent>
#include <QtGui/QKeyEvent>
#include <QtGui/QWheelEvent>

#include "hotKeyManager.h"

using namespace qReal;

HotKeyManager::HotKeyManager()
	: mCurrentModifer("")
{
}

HotKeyManager& HotKeyManager::instance()
{
	static HotKeyManager instance;
	return instance;
}

void HotKeyManager::setCommand(const QString &id, const QString &label, QAction *command)
{
	command->setWhatsThis(label);

	instance().registerCommand(id, command);
}

void HotKeyManager::deleteCommand(QString const &id)
{
	resetShortcuts(id);
	instance().deleteCommandPrivate(id);
}

bool HotKeyManager::setShortcut(QString const &id, QKeySequence const &keyseq)
{
	return instance().registerShortcut(id, keyseq);
}

bool HotKeyManager::setShortcut(QString const &id, QKeySequence const &modifier, MouseButtons mousebutton)
{
	return instance().registerShortcut(id, modifier, mousebutton);
}

void HotKeyManager::resetShortcuts(QString const &id)
{
	instance().resetShortcutsPrivate(id);
}

void HotKeyManager::resetAllShortcuts()
{
	instance().resetAllShortcutsPrivate();
}

void HotKeyManager::deleteShortcut(const QString &id, const QString &shortcut)
{
	instance().deleteShortcutPrivate(id, shortcut);
}

void HotKeyManager::doShortcut(QEvent *event)
{
	MouseButtons mb = None;
	switch(event->type()) {
		case QEvent::Wheel: {
			mb = static_cast<QWheelEvent *>(event)->delta() > 0 ? MouseWU : MouseWD;
			break;
		}
		case QEvent::MouseButtonPress: {
			switch(static_cast<QMouseEvent *>(event)->button()) {
				case Qt::RightButton:
					mb = MouseRB;
					break;
				case Qt::LeftButton:
					mb = MouseLB;
					break;
				case Qt::MiddleButton:
					mb = MouseMB;
					break;
				default:
					return;
			}
			break;
		}
		default: {
			return;
		}
	}

	instance().findShortcut(sequence(instance().currentModifier(), mb));
}

void HotKeyManager::setCurrentModifier(const QString &modifier)
{
	instance().setCurrentModifierPrivate(modifier);
}

QHash<QString, QAction *> HotKeyManager::commands()
{
	return instance().commandsPrivate();
}

QHash<QString, QString> HotKeyManager::shortcuts()
{
	return instance().shortcutsPrivate();
}

void HotKeyManager::registerCommand(const QString &id, QAction *command)
{
	QList<QKeySequence> shortcuts = command->shortcuts();

	foreach (QKeySequence const &shortcut, shortcuts) {
		instance().registerShortcut(id, shortcut.toString());
	}

	mCommands[id] = command;
}

bool HotKeyManager::registerShortcut(QString const &id, QKeySequence const &keyseq)
{
	if (mCommands.contains(id)) {
		QString const shortcut = keyseq.toString();

		if (!hasPrefixOf(shortcut)) {
			addPrefixes(shortcut);
			mShortcuts[shortcut] = id;
			mCommands[id]->setShortcuts(mCommands[id]->shortcuts() << keyseq);
			return true;
		}
	}
	return false;
}

bool HotKeyManager::registerShortcut(QString const &id, QKeySequence const &modifier, MouseButtons mousebutton)
{
	if (mCommands.contains(id)) {
		QString const shortcut = sequence(modifier.toString(), mousebutton);

		if (!mShortcuts.contains(shortcut)) {
			addPrefixes(shortcut);
			mShortcuts[shortcut] = id;
			return true;
		}
	}

	return false;
}

void HotKeyManager::registerShortcut(QString const &id, QString const &shortcut)
{
	if (!hasPrefixOf(shortcut)) {
		addPrefixes(shortcut);
		mShortcuts[shortcut] = id;
	}
}

void HotKeyManager::findShortcut(QString const &shortcut)
{
	if (mShortcuts.contains(shortcut) && mCommands[mShortcuts.value(shortcut)]->parentWidget()->isActiveWindow()) {
		mCommands[mShortcuts.value(shortcut)]->trigger();
	}
}

QString HotKeyManager::sequence(const QString &modifier, MouseButtons mousebutton)
{
	QString seq = modifier;

	switch(mousebutton) {
	case MouseLB:
		seq += "MouseLB";
		break;
	case MouseRB:
		seq += "MouseRB";
		break;
	case MouseMB:
		seq += "MouseMB";
		break;
	case MouseWU:
		seq += "MouseWU";
		break;
	case MouseWD:
		seq += "MouseWD";
	}

	return seq;
}

void HotKeyManager::setCurrentModifierPrivate(QString const &modifier)
{
	mCurrentModifer = modifier;
}

QString HotKeyManager::currentModifier()
{
	return mCurrentModifer;
}

void HotKeyManager::resetShortcutsPrivate(QString const &id)
{
	if (mCommands.contains(id)) {
		QList<QString> shortcuts = mShortcuts.keys(id);

		foreach (QString const &shortcut, shortcuts) {
			deletePrefixes(shortcut);
			mShortcuts.remove(shortcut);
		}

		mCommands[id]->setShortcuts(QList<QKeySequence>());
	}
}

void HotKeyManager::resetAllShortcutsPrivate()
{
	QList<QAction *> cmds = mCommands.values();

	foreach (QAction *cmd, cmds) {
		cmd->setShortcuts(QList<QKeySequence>());
	}

	mShortcuts.clear();
	mPrefixes.clear();
}

void HotKeyManager::deleteShortcutPrivate(const QString &id, const QString &shortcut)
{
	mShortcuts.remove(shortcut);
	deletePrefixes(shortcut);
	//if == "" then shortcut with mouse
	if (QKeySequence(shortcut).toString() != "" ) {
		QList<QKeySequence> shortcuts = mCommands[id]->shortcuts();

		shortcuts.removeOne(shortcut);
		mCommands[id]->setShortcuts(shortcuts);
	}
}

void HotKeyManager::deleteCommandPrivate(QString const &id)
{
	if (mCommands.contains(id)) {
		mCommands.remove(id);
	}
}

QHash<QString, QAction *> HotKeyManager::commandsPrivate()
{
	return mCommands;
}

QHash<QString, QString> HotKeyManager::shortcutsPrivate()
{
	return mShortcuts;
}

bool HotKeyManager::hasPrefixOf(QString const &keyseq)
{
	if (!mPrefixes.contains(keyseq)) {
		QStringList seqlist = keyseq.split(", ");
		QString prefix;

		foreach (QString const &seq, seqlist) {
			prefix += seq;
			if (mShortcuts.contains(prefix) || mShortcuts.contains(seq)) {
				return true;
			}
			prefix += ", ";
		}
		return false;
	}
	return true;
}

void HotKeyManager::addPrefixes(QString const &keyseq)
{
	QStringList seqlist = keyseq.split(", ");
	QString prefix;

	foreach (QString const &seq, seqlist) {
		prefix += seq;
		if (mPrefixes.contains(prefix)) {
			++mPrefixes[prefix];
		} else {
			mPrefixes[prefix] = 1;
		}
		prefix += ", ";
	}
}

void HotKeyManager::deletePrefixes(QString const &keyseq)
{
	QStringList seqlist = keyseq.split(", ");
	QString prefix;

	foreach (QString const &seq, seqlist) {
		prefix += seq;
		--mPrefixes[prefix];
		if (mPrefixes.value(prefix) == 0) {
			mPrefixes.remove(prefix);
		}
		prefix += ", ";
	}
}
<commit_msg>fixed method hasPrefixOf<commit_after>#include <QtCore/QString>
#include <QtCore/QHash>
#include <QtWidgets/QAction>
#include <QtGui/QKeySequence>
#include <QtCore/QDebug>
#include <QtCore/QEvent>
#include <QtGui/QActionEvent>
#include <QtGui/QKeyEvent>
#include <QtGui/QWheelEvent>

#include "hotKeyManager.h"

using namespace qReal;

HotKeyManager::HotKeyManager()
	: mCurrentModifer("")
{
}

HotKeyManager& HotKeyManager::instance()
{
	static HotKeyManager instance;
	return instance;
}

void HotKeyManager::setCommand(const QString &id, const QString &label, QAction *command)
{
	command->setWhatsThis(label);

	instance().registerCommand(id, command);
}

void HotKeyManager::deleteCommand(QString const &id)
{
	resetShortcuts(id);
	instance().deleteCommandPrivate(id);
}

bool HotKeyManager::setShortcut(QString const &id, QKeySequence const &keyseq)
{
	return instance().registerShortcut(id, keyseq);
}

bool HotKeyManager::setShortcut(QString const &id, QKeySequence const &modifier, MouseButtons mousebutton)
{
	return instance().registerShortcut(id, modifier, mousebutton);
}

void HotKeyManager::resetShortcuts(QString const &id)
{
	instance().resetShortcutsPrivate(id);
}

void HotKeyManager::resetAllShortcuts()
{
	instance().resetAllShortcutsPrivate();
}

void HotKeyManager::deleteShortcut(const QString &id, const QString &shortcut)
{
	instance().deleteShortcutPrivate(id, shortcut);
}

void HotKeyManager::doShortcut(QEvent *event)
{
	MouseButtons mb = None;
	switch(event->type()) {
		case QEvent::Wheel: {
			mb = static_cast<QWheelEvent *>(event)->delta() > 0 ? MouseWU : MouseWD;
			break;
		}
		case QEvent::MouseButtonPress: {
			switch(static_cast<QMouseEvent *>(event)->button()) {
				case Qt::RightButton:
					mb = MouseRB;
					break;
				case Qt::LeftButton:
					mb = MouseLB;
					break;
				case Qt::MiddleButton:
					mb = MouseMB;
					break;
				default:
					return;
			}
			break;
		}
		default: {
			return;
		}
	}

	instance().findShortcut(sequence(instance().currentModifier(), mb));
}

void HotKeyManager::setCurrentModifier(const QString &modifier)
{
	instance().setCurrentModifierPrivate(modifier);
}

QHash<QString, QAction *> HotKeyManager::commands()
{
	return instance().commandsPrivate();
}

QHash<QString, QString> HotKeyManager::shortcuts()
{
	return instance().shortcutsPrivate();
}

void HotKeyManager::registerCommand(const QString &id, QAction *command)
{
	QList<QKeySequence> shortcuts = command->shortcuts();

	foreach (QKeySequence const &shortcut, shortcuts) {
		instance().registerShortcut(id, shortcut.toString());
	}

	mCommands[id] = command;
}

bool HotKeyManager::registerShortcut(QString const &id, QKeySequence const &keyseq)
{
	if (mCommands.contains(id)) {
		QString const shortcut = keyseq.toString();

		if (!hasPrefixOf(shortcut)) {
			addPrefixes(shortcut);
			mShortcuts[shortcut] = id;
			mCommands[id]->setShortcuts(mCommands[id]->shortcuts() << keyseq);
			return true;
		}
	}
	return false;
}

bool HotKeyManager::registerShortcut(QString const &id, QKeySequence const &modifier, MouseButtons mousebutton)
{
	if (mCommands.contains(id)) {
		QString const shortcut = sequence(modifier.toString(), mousebutton);

		if (!mShortcuts.contains(shortcut)) {
			addPrefixes(shortcut);
			mShortcuts[shortcut] = id;
			return true;
		}
	}

	return false;
}

void HotKeyManager::registerShortcut(QString const &id, QString const &shortcut)
{
	if (!hasPrefixOf(shortcut)) {
		addPrefixes(shortcut);
		mShortcuts[shortcut] = id;
	}
}

void HotKeyManager::findShortcut(QString const &shortcut)
{
	if (mShortcuts.contains(shortcut) && mCommands[mShortcuts.value(shortcut)]->parentWidget()->isActiveWindow()) {
		mCommands[mShortcuts.value(shortcut)]->trigger();
	}
}

QString HotKeyManager::sequence(const QString &modifier, MouseButtons mousebutton)
{
	QString seq = modifier;

	switch(mousebutton) {
	case MouseLB:
		seq += "MouseLB";
		break;
	case MouseRB:
		seq += "MouseRB";
		break;
	case MouseMB:
		seq += "MouseMB";
		break;
	case MouseWU:
		seq += "MouseWU";
		break;
	case MouseWD:
		seq += "MouseWD";
	}

	return seq;
}

void HotKeyManager::setCurrentModifierPrivate(QString const &modifier)
{
	mCurrentModifer = modifier;
}

QString HotKeyManager::currentModifier()
{
	return mCurrentModifer;
}

void HotKeyManager::resetShortcutsPrivate(QString const &id)
{
	if (mCommands.contains(id)) {
		QList<QString> shortcuts = mShortcuts.keys(id);

		foreach (QString const &shortcut, shortcuts) {
			deletePrefixes(shortcut);
			mShortcuts.remove(shortcut);
		}

		mCommands[id]->setShortcuts(QList<QKeySequence>());
	}
}

void HotKeyManager::resetAllShortcutsPrivate()
{
	QList<QAction *> cmds = mCommands.values();

	foreach (QAction *cmd, cmds) {
		cmd->setShortcuts(QList<QKeySequence>());
	}

	mShortcuts.clear();
	mPrefixes.clear();
}

void HotKeyManager::deleteShortcutPrivate(const QString &id, const QString &shortcut)
{
	mShortcuts.remove(shortcut);
	deletePrefixes(shortcut);
	//if == "" then shortcut with mouse
	if (QKeySequence(shortcut).toString() != "" ) {
		QList<QKeySequence> shortcuts = mCommands[id]->shortcuts();

		shortcuts.removeOne(shortcut);
		mCommands[id]->setShortcuts(shortcuts);
	}
}

void HotKeyManager::deleteCommandPrivate(QString const &id)
{
	if (mCommands.contains(id)) {
		mCommands.remove(id);
	}
}

QHash<QString, QAction *> HotKeyManager::commandsPrivate()
{
	return mCommands;
}

QHash<QString, QString> HotKeyManager::shortcutsPrivate()
{
	return mShortcuts;
}

bool HotKeyManager::hasPrefixOf(QString const &keyseq)
{
	if (!mPrefixes.contains(keyseq)) {
		QStringList seqlist = keyseq.split(", ");
		QString prefix;

		foreach (QString const &seq, seqlist) {
			prefix += seq;
			if (mShortcuts.contains(prefix)) {
				return true;
			}
			prefix += ", ";
		}
		return false;
	}
	return true;
}

void HotKeyManager::addPrefixes(QString const &keyseq)
{
	QStringList seqlist = keyseq.split(", ");
	QString prefix;

	foreach (QString const &seq, seqlist) {
		prefix += seq;
		if (mPrefixes.contains(prefix)) {
			++mPrefixes[prefix];
		} else {
			mPrefixes[prefix] = 1;
		}
		prefix += ", ";
	}
}

void HotKeyManager::deletePrefixes(QString const &keyseq)
{
	QStringList seqlist = keyseq.split(", ");
	QString prefix;

	foreach (QString const &seq, seqlist) {
		prefix += seq;
		--mPrefixes[prefix];
		if (mPrefixes.value(prefix) == 0) {
			mPrefixes.remove(prefix);
		}
		prefix += ", ";
	}
}
<|endoftext|>


<commit_before>// Copyright (c) Microsoft Corporation
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

#include "pch.h"
#include "lhc_mock.h"
#include "../HTTP/httpcall.h"

using namespace xbox::httpclient;

bool DoesMockCallMatch(_In_ const HC_CALL* mockCall, _In_ const HC_CALL* originalCall)
{
    if (mockCall->url.empty())
    {
        return true;
    }
    else
    {
        if (originalCall->url.substr(0, mockCall->url.size()) == mockCall->url)
        {
            if (mockCall->requestBodyBytes.empty())
            {
                return true;
            }
            else
            {
                if (originalCall->requestBodyBytes == mockCall->requestBodyBytes)
                {
                    return true;
                }
            }
        }
    }

    return false;
}

bool Mock_Internal_HCHttpCallPerformAsync(
    _In_ HCCallHandle originalCall
    )
{
    auto httpSingleton = get_http_singleton(false);
    if (nullptr == httpSingleton)
    {
        return false;
    }

    std::lock_guard<std::recursive_mutex> guard(httpSingleton->m_mocksLock);

    if (httpSingleton->m_mocks.size() == 0)
    {
        return false;
    }

    auto& mocks{ httpSingleton->m_mocks };
    HC_MOCK_CALL* mock{ nullptr };

    // Use the most recently added mock that matches (similar to a stack).
    for (auto iter = mocks.rbegin(); iter != mocks.rend(); ++iter)
    {
        if (DoesMockCallMatch(*iter, originalCall))
        {
            mock = *iter;
            break;
        }
    }

    if (mock->matchedCallback)
    {
        mock->matchedCallback(
            mock,
            originalCall->method.data(),
            originalCall->url.data(),
            originalCall->requestBodyBytes.data(),
            static_cast<uint32_t>(originalCall->requestBodyBytes.size()),
            mock->matchCallbackContext
        );
    }

    size_t byteBuf;
    HCHttpCallResponseGetResponseBodyBytesSize(mock, &byteBuf);
    http_memory_buffer buffer(byteBuf);
    HCHttpCallResponseGetResponseBodyBytes(mock, byteBuf, static_cast<uint8_t*>(buffer.get()), nullptr);
    HCHttpCallResponseSetResponseBodyBytes(originalCall, static_cast<uint8_t*>(buffer.get()), byteBuf);

    uint32_t code;
    HCHttpCallResponseGetStatusCode(mock, &code);
    HCHttpCallResponseSetStatusCode(originalCall, code);

    HRESULT genCode;
    HCHttpCallResponseGetNetworkErrorCode(mock, &genCode, &code);
    HCHttpCallResponseSetNetworkErrorCode(originalCall, genCode, code);

    uint32_t numheaders;
    HCHttpCallResponseGetNumHeaders(mock, &numheaders);

    const char* str1;
    const char* str2;
    for (uint32_t i = 0; i < numheaders; i++)
    {
        HCHttpCallResponseGetHeaderAtIndex(mock, i, &str1, &str2);
        HCHttpCallResponseSetHeader(originalCall, str1, str2);
    }

    return true;
}
<commit_msg>Add missed null check in mock stack (#474)<commit_after>// Copyright (c) Microsoft Corporation
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

#include "pch.h"
#include "lhc_mock.h"
#include "../HTTP/httpcall.h"

using namespace xbox::httpclient;

bool DoesMockCallMatch(_In_ const HC_CALL* mockCall, _In_ const HC_CALL* originalCall)
{
    if (mockCall->url.empty())
    {
        return true;
    }
    else
    {
        if (originalCall->url.substr(0, mockCall->url.size()) == mockCall->url)
        {
            if (mockCall->requestBodyBytes.empty())
            {
                return true;
            }
            else
            {
                if (originalCall->requestBodyBytes == mockCall->requestBodyBytes)
                {
                    return true;
                }
            }
        }
    }

    return false;
}

bool Mock_Internal_HCHttpCallPerformAsync(
    _In_ HCCallHandle originalCall
    )
{
    auto httpSingleton = get_http_singleton(false);
    if (nullptr == httpSingleton)
    {
        return false;
    }

    std::lock_guard<std::recursive_mutex> guard(httpSingleton->m_mocksLock);

    if (httpSingleton->m_mocks.size() == 0)
    {
        return false;
    }

    auto& mocks{ httpSingleton->m_mocks };
    HC_MOCK_CALL* mock{ nullptr };

    // Use the most recently added mock that matches (similar to a stack).
    for (auto iter = mocks.rbegin(); iter != mocks.rend(); ++iter)
    {
        if (DoesMockCallMatch(*iter, originalCall))
        {
            mock = *iter;
            break;
        }
    }

    if (!mock)
    {
        return false;
    }

    if (mock->matchedCallback)
    {
        mock->matchedCallback(
            mock,
            originalCall->method.data(),
            originalCall->url.data(),
            originalCall->requestBodyBytes.data(),
            static_cast<uint32_t>(originalCall->requestBodyBytes.size()),
            mock->matchCallbackContext
        );
    }

    size_t byteBuf;
    HCHttpCallResponseGetResponseBodyBytesSize(mock, &byteBuf);
    http_memory_buffer buffer(byteBuf);
    HCHttpCallResponseGetResponseBodyBytes(mock, byteBuf, static_cast<uint8_t*>(buffer.get()), nullptr);
    HCHttpCallResponseSetResponseBodyBytes(originalCall, static_cast<uint8_t*>(buffer.get()), byteBuf);

    uint32_t code;
    HCHttpCallResponseGetStatusCode(mock, &code);
    HCHttpCallResponseSetStatusCode(originalCall, code);

    HRESULT genCode;
    HCHttpCallResponseGetNetworkErrorCode(mock, &genCode, &code);
    HCHttpCallResponseSetNetworkErrorCode(originalCall, genCode, code);

    uint32_t numheaders;
    HCHttpCallResponseGetNumHeaders(mock, &numheaders);

    const char* str1;
    const char* str2;
    for (uint32_t i = 0; i < numheaders; i++)
    {
        HCHttpCallResponseGetHeaderAtIndex(mock, i, &str1, &str2);
        HCHttpCallResponseSetHeader(originalCall, str1, str2);
    }

    return true;
}
<|endoftext|>


<commit_before>/*
 * Copyright 2009-2018 The VOTCA Development Team (http://www.votca.org)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
#define BOOST_TEST_MAIN

#define BOOST_TEST_MODULE qmpair_test
#include <boost/test/unit_test.hpp>
#include <votca/xtp/qmpair.h>
#include <votca/xtp/topology.h>
#include <votca/xtp/segment.h>
#include <votca/xtp/atom.h>

#include <votca/tools/matrix.h>
#include <votca/tools/vec.h>

#include <votca/csg/boundarycondition.h>

using namespace votca::tools;

using namespace votca::xtp;

BOOST_AUTO_TEST_SUITE(qmpair_test)

BOOST_AUTO_TEST_CASE(constructors_test) { QMPair qm_p; }

BOOST_AUTO_TEST_CASE( getters_test ) {

  double tolerancePerc = 0.01;
  // Box takes a vector
  double x1 = 12.0;
  double y1 = 0.0;
  double z1 = 0.0;

  double x2 = 0.0;
  double y2 = 12.0;
  double z2 = 0.0;

  double x3 = 0.0;
  double y3 = 0.0;
  double z3 = 12.0;

  vec v1(x1,y1,z1);
  vec v2(x2,y2,z2);
  vec v3(x3,y3,z3);

  matrix box(v1,v2,v3);

  Topology top;
  top.setBox(box);
  vec p1;
  p1.setX(0.0);
  p1.setY(0.0);
  p1.setZ(0.0);

  vec p2;
  p2.setX(10.0);
  p2.setY(0.0);
  p2.setZ(0.0);
  top.PbShortestConnect(p1,p2);

  bool hasQM = true;
  vec qmpos;
  qmpos.setX(2.0);
  qmpos.setY(2.0);
  qmpos.setZ(2.0);

  vec pos;
  pos.setX(3.0);
  pos.setY(3.0);
  pos.setZ(3.0);

  Atom * atm = new Atom(nullptr, "res1",1,"CSP",2,hasQM,3,qmpos,"C",1.0);
  atm->setPos(pos);
  Segment * seg1 = new Segment(1, "seg1");
  seg1->AddAtom(atm);
  seg1->setTopology(&top);

  vec qmpos_2;
  qmpos_2.setX(4.0);
  qmpos_2.setY(4.0);
  qmpos_2.setZ(4.0);

  vec pos_2;
  pos_2.setX(1.0);
  pos_2.setY(1.0);
  pos_2.setZ(1.0);

  Atom * atm_2 = new Atom(nullptr, "res1",1,"CSP",2,hasQM,3,qmpos_2,"H",1.0);
  atm->setPos(pos_2);
  Segment * seg2 = new Segment(2, "seg2");
  seg2->AddAtom(atm_2);
  seg2->setTopology(&top);

  int pair_num = 1;
  QMPair qm_p(pair_num,seg1,seg2);
  BOOST_CHECK_EQUAL(qm_p.getId(),1);
  auto r = qm_p.R();
  BOOST_CHECK_EQUAL(r.x(),0.0);
  BOOST_CHECK_EQUAL(r.y(),0.0);
  BOOST_CHECK_EQUAL(r.z(),0.0);
  BOOST_CHECK_EQUAL(qm_p.HasGhost(),false);

  int state = -1;
  BOOST_CHECK_CLOSE(qm_p.getLambdaO(state),0.0,(tolerancePerc));
  BOOST_CHECK_CLOSE(qm_p.getReorg12(state),0.0,(tolerancePerc));
  BOOST_CHECK_CLOSE(qm_p.getReorg21(state),0.0,(tolerancePerc));
  BOOST_CHECK_CLOSE(qm_p.getReorg12_x(state),0.0,(tolerancePerc));
  BOOST_CHECK_CLOSE(qm_p.getReorg21_x(state),0.0,(tolerancePerc));
  BOOST_CHECK_CLOSE(qm_p.getRate12(state),0.0,(tolerancePerc));
  BOOST_CHECK_CLOSE(qm_p.getRate21(state),0.0,(tolerancePerc));
  BOOST_CHECK_CLOSE(qm_p.getJeff2(state),0.0,(tolerancePerc));
  BOOST_CHECK_CLOSE(qm_p.getdE12(state),0.0,(tolerancePerc));

  state = 1;
  BOOST_CHECK_CLOSE(qm_p.getLambdaO(state),0.0,(tolerancePerc));
  BOOST_CHECK_CLOSE(qm_p.getReorg12(state),0.0,(tolerancePerc));
  BOOST_CHECK_CLOSE(qm_p.getReorg21(state),0.0,(tolerancePerc));
  BOOST_CHECK_CLOSE(qm_p.getReorg12_x(state),0.0,(tolerancePerc));
  BOOST_CHECK_CLOSE(qm_p.getReorg21_x(state),0.0,(tolerancePerc));
  BOOST_CHECK_CLOSE(qm_p.getRate12(state),0.0,(tolerancePerc));
  BOOST_CHECK_CLOSE(qm_p.getRate21(state),0.0,(tolerancePerc));
  BOOST_CHECK_CLOSE(qm_p.getJeff2(state),0.0,(tolerancePerc));
  BOOST_CHECK_CLOSE(qm_p.getdE12(state),0.0,(tolerancePerc));

  state = 2;
  BOOST_CHECK_CLOSE(qm_p.getLambdaO(state),0.0,(tolerancePerc));
  BOOST_CHECK_CLOSE(qm_p.getReorg12(state),0.0,(tolerancePerc));
  BOOST_CHECK_CLOSE(qm_p.getReorg21(state),0.0,(tolerancePerc));
  BOOST_CHECK_CLOSE(qm_p.getReorg12_x(state),0.0,(tolerancePerc));
  BOOST_CHECK_CLOSE(qm_p.getReorg21_x(state),0.0,(tolerancePerc));
  BOOST_CHECK_CLOSE(qm_p.getRate12(state),0.0,(tolerancePerc));
  BOOST_CHECK_CLOSE(qm_p.getRate21(state),0.0,(tolerancePerc));
  BOOST_CHECK_CLOSE(qm_p.getJeff2(state),0.0,(tolerancePerc));
  BOOST_CHECK_CLOSE(qm_p.getdE12(state),0.0,(tolerancePerc));

  state = 3;
  BOOST_CHECK_CLOSE(qm_p.getLambdaO(state),0.0,(tolerancePerc));
  BOOST_CHECK_CLOSE(qm_p.getReorg12(state),0.0,(tolerancePerc));
  BOOST_CHECK_CLOSE(qm_p.getReorg21(state),0.0,(tolerancePerc));
  BOOST_CHECK_CLOSE(qm_p.getReorg12_x(state),0.0,(tolerancePerc));
  BOOST_CHECK_CLOSE(qm_p.getReorg21_x(state),0.0,(tolerancePerc));
  BOOST_CHECK_CLOSE(qm_p.getRate12(state),0.0,(tolerancePerc));
  BOOST_CHECK_CLOSE(qm_p.getRate21(state),0.0,(tolerancePerc));
  BOOST_CHECK_CLOSE(qm_p.getJeff2(state),0.0,(tolerancePerc));
  BOOST_CHECK_CLOSE(qm_p.getdE12(state),0.0,(tolerancePerc));
}

BOOST_AUTO_TEST_SUITE_END()
<commit_msg>Finally figured out complicated segment configuration and testing<commit_after>/*
 * Copyright 2009-2018 The VOTCA Development Team (http://www.votca.org)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
#define BOOST_TEST_MAIN

#define BOOST_TEST_MODULE qmpair_test
#include <boost/test/unit_test.hpp>
#include <votca/xtp/qmpair.h>
#include <votca/xtp/topology.h>
#include <votca/xtp/segment.h>
#include <votca/xtp/atom.h>

#include <votca/tools/matrix.h>
#include <votca/tools/vec.h>

#include <votca/csg/boundarycondition.h>

using namespace votca::tools;

using namespace votca::xtp;

BOOST_AUTO_TEST_SUITE(qmpair_test)

BOOST_AUTO_TEST_CASE(constructors_test) { QMPair qm_p; }

BOOST_AUTO_TEST_CASE( getters_test ) {

  double tolerancePerc = 0.01;
  // Box takes a vector
  double x1 = 12.0;
  double y1 = 0.0;
  double z1 = 0.0;

  double x2 = 0.0;
  double y2 = 12.0;
  double z2 = 0.0;

  double x3 = 0.0;
  double y3 = 0.0;
  double z3 = 12.0;

  vec v1(x1,y1,z1);
  vec v2(x2,y2,z2);
  vec v3(x3,y3,z3);

  matrix box(v1,v2,v3);

  Topology top;
  top.setBox(box);
  vec p1;
  p1.setX(0.0);
  p1.setY(0.0);
  p1.setZ(0.0);

  vec p2;
  p2.setX(10.0);
  p2.setY(0.0);
  p2.setZ(0.0);
  top.PbShortestConnect(p1,p2);

  bool hasQM = true;
  vec qmpos;
  qmpos.setX(2.0);
  qmpos.setY(2.0);
  qmpos.setZ(2.0);

  vec pos;
  pos.setX(3.0);
  pos.setY(3.0);
  pos.setZ(3.0);

  Atom * atm = new Atom(nullptr, "res1",1,"CSP",2,hasQM,3,qmpos,"C",1.0);
  atm->setPos(pos);
  Segment * seg1 = new Segment(1, "seg1");
  seg1->AddAtom(atm);
  seg1->setTopology(&top);

  int state  = -1;
  seg1->setU_cC_nN(0.0,state);
  seg1->setU_nC_nN(0.0,state);
  seg1->setU_cN_cC(0.0,state);
  state  = 1;
  seg1->setU_cC_nN(0.0,state);
  seg1->setU_nC_nN(0.0,state);
  seg1->setU_cN_cC(0.0,state);
  state  = 2;
  seg1->setU_xX_nN(0.0,state);
  seg1->setU_nX_nN(0.0,state);
  seg1->setU_xN_xX(0.0,state);
  state  = 3;
  seg1->setU_xX_nN(0.0,state);
  seg1->setU_nX_nN(0.0,state);
  seg1->setU_xN_xX(0.0,state);

  vec qmpos_2;
  qmpos_2.setX(4.0);
  qmpos_2.setY(4.0);
  qmpos_2.setZ(4.0);

  vec pos_2;
  pos_2.setX(1.0);
  pos_2.setY(1.0);
  pos_2.setZ(1.0);

  Atom * atm_2 = new Atom(nullptr, "res1",1,"CSP",2,hasQM,3,qmpos_2,"H",1.0);
  atm->setPos(pos_2);
  Segment * seg2 = new Segment(2, "seg2");
  seg2->AddAtom(atm_2);
  seg2->setTopology(&top);
  state  = -1;
  seg2->setU_cC_nN(0.0,state);
  seg2->setU_nC_nN(0.0,state);
  seg2->setU_cN_cC(0.0,state);
  state  = 1;
  seg2->setU_cC_nN(0.0,state);
  seg2->setU_nC_nN(0.0,state);
  seg2->setU_cN_cC(0.0,state);
  state  = 2;
  seg2->setU_xX_nN(0.0,state);
  seg2->setU_nX_nN(0.0,state);
  seg2->setU_xN_xX(0.0,state);
  state  = 3;
  seg2->setU_xX_nN(0.0,state);
  seg2->setU_nX_nN(0.0,state);
  seg2->setU_xN_xX(0.0,state);

  int pair_num = 1;
  QMPair qm_p(pair_num,seg1,seg2);
  BOOST_CHECK_EQUAL(qm_p.getId(),1);
  auto r = qm_p.R();
  BOOST_CHECK_CLOSE(r.x(),0.0,tolerancePerc);
  BOOST_CHECK_CLOSE(r.y(),0.0,tolerancePerc);
  BOOST_CHECK_CLOSE(r.z(),0.0,tolerancePerc);
  BOOST_CHECK(qm_p.HasGhost()==false);

  state = -1;
  BOOST_CHECK_CLOSE(qm_p.getLambdaO(state),0.0,(tolerancePerc));
  BOOST_CHECK_CLOSE(qm_p.getReorg12(state),0.0,(tolerancePerc));
  BOOST_CHECK_CLOSE(qm_p.getReorg21(state),0.0,(tolerancePerc));
  BOOST_CHECK_CLOSE(qm_p.getReorg12_x(state),0.0,(tolerancePerc));
  BOOST_CHECK_CLOSE(qm_p.getReorg21_x(state),0.0,(tolerancePerc));
  BOOST_CHECK_CLOSE(qm_p.getRate12(state),0.0,(tolerancePerc));
  BOOST_CHECK_CLOSE(qm_p.getRate21(state),0.0,(tolerancePerc));
  BOOST_CHECK_CLOSE(qm_p.getJeff2(state),0.0,(tolerancePerc));
  BOOST_CHECK_CLOSE(qm_p.getdE12(state),0.0,(tolerancePerc));

  state = 1;
  BOOST_CHECK_CLOSE(qm_p.getLambdaO(state),0.0,(tolerancePerc));
  BOOST_CHECK_CLOSE(qm_p.getReorg12(state),0.0,(tolerancePerc));
  BOOST_CHECK_CLOSE(qm_p.getReorg21(state),0.0,(tolerancePerc));
  BOOST_CHECK_CLOSE(qm_p.getReorg12_x(state),0.0,(tolerancePerc));
  BOOST_CHECK_CLOSE(qm_p.getReorg21_x(state),0.0,(tolerancePerc));
  BOOST_CHECK_CLOSE(qm_p.getRate12(state),0.0,(tolerancePerc));
  BOOST_CHECK_CLOSE(qm_p.getRate21(state),0.0,(tolerancePerc));
  BOOST_CHECK_CLOSE(qm_p.getJeff2(state),0.0,(tolerancePerc));
  BOOST_CHECK_CLOSE(qm_p.getdE12(state),0.0,(tolerancePerc));

  state = 2;
  BOOST_CHECK_CLOSE(qm_p.getLambdaO(state),0.0,(tolerancePerc));
  BOOST_CHECK_CLOSE(qm_p.getReorg12(state),0.0,(tolerancePerc));
  BOOST_CHECK_CLOSE(qm_p.getReorg21(state),0.0,(tolerancePerc));
  BOOST_CHECK_CLOSE(qm_p.getReorg12_x(state),0.0,(tolerancePerc));
  BOOST_CHECK_CLOSE(qm_p.getReorg21_x(state),0.0,(tolerancePerc));
  BOOST_CHECK_CLOSE(qm_p.getRate12(state),0.0,(tolerancePerc));
  BOOST_CHECK_CLOSE(qm_p.getRate21(state),0.0,(tolerancePerc));
  BOOST_CHECK_CLOSE(qm_p.getJeff2(state),0.0,(tolerancePerc));
  BOOST_CHECK_CLOSE(qm_p.getdE12(state),0.0,(tolerancePerc));

  state = 3;
  BOOST_CHECK_CLOSE(qm_p.getLambdaO(state),0.0,(tolerancePerc));
  BOOST_CHECK_CLOSE(qm_p.getReorg12(state),0.0,(tolerancePerc));
  BOOST_CHECK_CLOSE(qm_p.getReorg21(state),0.0,(tolerancePerc));
  BOOST_CHECK_CLOSE(qm_p.getReorg12_x(state),0.0,(tolerancePerc));
  BOOST_CHECK_CLOSE(qm_p.getReorg21_x(state),0.0,(tolerancePerc));
  BOOST_CHECK_CLOSE(qm_p.getRate12(state),0.0,(tolerancePerc));
  BOOST_CHECK_CLOSE(qm_p.getRate21(state),0.0,(tolerancePerc));
  BOOST_CHECK_CLOSE(qm_p.getJeff2(state),0.0,(tolerancePerc));
  BOOST_CHECK_CLOSE(qm_p.getdE12(state),0.0,(tolerancePerc));
}

BOOST_AUTO_TEST_SUITE_END()
<|endoftext|>


<commit_before>// texturetest.cc a test app for Textures
// Copyright (c) 2004 - 2006 Henrik Kinnunen (fluxgen at fluxbox dot org)

#include "ImageControl.hh"
#include "Color.hh"
#include "GContext.hh"
#include "FbPixmap.hh"
#include "Texture.hh"
#include "FbWindow.hh"
#include "EventHandler.hh"
#include "EventManager.hh"
#include "Theme.hh"
#include "Font.hh"
#include "App.hh"

#include <memory>
#include <string>

using namespace std;
using namespace FbTk;

class TestTheme: public Theme {
public:
    TestTheme(int screen):Theme(screen) { }
    bool fallback(ThemeItem_base &item) { return false; }
    void reconfigTheme() { }
};

class Application: public FbTk::FbWindow, public FbTk::EventHandler {
public:
    Application(int box_size, int num):
        FbWindow(0,  0, 0, 640, box_size*num/8 - 3*5, ExposureMask | KeyPressMask),
        m_box_size(box_size),
        m_num(num),
        m_font("fixed"),
        m_imgctrl(screenNumber(), true, 8,
                  100, 100),
        m_background(*this, 640, 480, depth()),
        m_gc(m_background) {
        setName("Texture Test");
        setBackgroundPixmap(m_background.drawable());

        FbTk::EventManager::instance()->add(*this, *this);

        renderPixmaps();

        show();
    }
    void keyPressEvent(XKeyEvent &ev) {
        App::instance()->end();
    }
    void exposeEvent(XExposeEvent &ev) {
        clear();
    }

private:

    void renderPixmap(const Texture &text, int x, int y) {
        Pixmap pm = m_imgctrl.renderImage(m_box_size, m_box_size,
                                          text);

        m_background.copyArea(pm, m_gc.gc(),
                              0, 0,
                              x, y,
                              m_box_size, m_box_size);
        m_imgctrl.removeImage(pm);
    }

    void renderPixmaps() {

        m_gc.setForeground(Color("gray", screenNumber()));

        m_background.fillRectangle(m_gc.gc(),
                                   0, 0,
                                   width(), height());
        // for text color
        m_gc.setForeground(Color("black", screenNumber()));

        const int step_size = m_box_size + 5;
        int next_x = 5;
        int next_y = 5;

        TestTheme tm(screenNumber());
        std::auto_ptr<ThemeItem<Texture> > text;
        char value[18];
        for (int i=0; i<m_num; ++i) {
            sprintf(value, "%d", i);
            text.reset(new ThemeItem<Texture>
                       (tm,
                        string("texture") + value,
                        string("Texture") + value));
            // load new style
            ThemeManager::instance().load("test.theme");

            renderPixmap(**text.get(), next_x, next_y);

            next_x += step_size;
            if (next_x + m_box_size > width()) {
                m_font.drawText(m_background,
                                screenNumber(),
                                m_gc.gc(),
                                value, strlen(value),
                                next_x, next_y + m_box_size/2);
                next_x = 5;
                next_y += step_size;
            }

        }

    }

    const int m_box_size;
    const int m_num;
    FbTk::Font m_font;
    ImageControl m_imgctrl;
    FbPixmap m_background;
    FbTk::GContext m_gc;
};

int main(int argc, char **argv) {
    int boxsize= 60;
    int num = 63;
    for (int i=1; i<argc; ++i) {
        if (strcmp(argv[i], "-boxsize") == 0 && i + 1 < argc)
            boxsize = atoi(argv[++i]);
        else if (strcmp(argv[i], "-num") == 0 && i + 1 < argc)
            num = atoi(argv[++i]);
     }
    App realapp;
    Application app(boxsize, num);

    realapp.eventLoop();

}
<commit_msg>updated 'texturetest.cc' to work with current API<commit_after>// texturetest.cc a test app for Textures
// Copyright (c) 2004 - 2006 Henrik Kinnunen (fluxgen at fluxbox dot org)

#include "ImageControl.hh"
#include "Color.hh"
#include "GContext.hh"
#include "FbPixmap.hh"
#include "Texture.hh"
#include "FbWindow.hh"
#include "EventHandler.hh"
#include "EventManager.hh"
#include "Theme.hh"
#include "Font.hh"
#include "App.hh"

#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <memory>
#include <string>

using namespace std;
using namespace FbTk;

class TestTheme: public Theme {
public:
    TestTheme(int screen):Theme(screen) { }
    bool fallback(ThemeItem_base &item) { return false; }
    void reconfigTheme() { }
};

class Application: public FbTk::FbWindow, public FbTk::EventHandler {
public:
    Application(int box_size, int num):
        FbWindow(0,  0, 0, 640, box_size*num/8 - 3*5, ExposureMask | KeyPressMask),
        m_box_size(box_size),
        m_num(num),
        m_font("fixed"),
        m_imgctrl(screenNumber()),
        m_background(*this, 640, 480, depth()),
        m_gc(m_background) {
        setName("Texture Test");
        setBackgroundPixmap(m_background.drawable());

        FbTk::EventManager::instance()->add(*this, *this);

        renderPixmaps();

        show();
    }
    void keyPressEvent(XKeyEvent &ev) {
        //App::instance()->end();
    }
    void exposeEvent(XExposeEvent &ev) {
        clear();
    }

private:

    void renderPixmap(const Texture &text, int x, int y) {
        Pixmap pm = m_imgctrl.renderImage(m_box_size, m_box_size,
                                          text);

        m_background.copyArea(pm, m_gc.gc(),
                              0, 0,
                              x, y,
                              m_box_size, m_box_size);
        m_imgctrl.removeImage(pm);
    }

    void renderPixmaps() {

        m_gc.setForeground(Color("gray", screenNumber()));

        m_background.fillRectangle(m_gc.gc(),
                                   0, 0,
                                   width(), height());
        // for text color
        m_gc.setForeground(Color("black", screenNumber()));

        const int step_size = m_box_size + 5;
        int next_x = 5;
        int next_y = 5;

        TestTheme tm(screenNumber());
        std::auto_ptr<ThemeItem<Texture> > text;
        char value[18];
        for (int i=0; i<m_num; ++i) {
            sprintf(value, "%d", i);
            text.reset(new ThemeItem<Texture>
                       (tm,
                        string("texture") + value,
                        string("Texture") + value));
            // load new style
            ThemeManager::instance().load("test.theme", "");

            renderPixmap(**text.get(), next_x, next_y);

            next_x += step_size;
            if (next_x + m_box_size > width()) {
                m_font.drawText(m_background,
                                screenNumber(),
                                m_gc.gc(),
                                value, strlen(value),
                                next_x, next_y + m_box_size/2);
                next_x = 5;
                next_y += step_size;
            }

        }

    }

    const int m_box_size;
    const int m_num;
    FbTk::Font m_font;
    ImageControl m_imgctrl;
    FbPixmap m_background;
    FbTk::GContext m_gc;
};

int main(int argc, char **argv) {
    int boxsize= 60;
    int num = 63;
    for (int i=1; i<argc; ++i) {
        if (strcmp(argv[i], "-boxsize") == 0 && i + 1 < argc)
            boxsize = atoi(argv[++i]);
        else if (strcmp(argv[i], "-num") == 0 && i + 1 < argc)
            num = atoi(argv[++i]);
     }
    App realapp;
    Application app(boxsize, num);

    realapp.eventLoop();

}
<|endoftext|>


<commit_before>// texturetest.cc a test app for Textures
// Copyright (c) 2004 - 2006 Henrik Kinnunen (fluxgen at fluxbox dot org)

#include "ImageControl.hh"
#include "Color.hh"
#include "GContext.hh"
#include "FbPixmap.hh"
#include "Texture.hh"
#include "FbWindow.hh"
#include "EventHandler.hh"
#include "EventManager.hh"
#include "Theme.hh"
#include "Font.hh"
#include "App.hh"

#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <memory>
#include <string>

using namespace std;
using namespace FbTk;

class TestTheme: public Theme {
public:
    TestTheme(int screen):Theme(screen) { }
    bool fallback(ThemeItem_base &item) { return false; }
    void reconfigTheme() { }
};

class Application: public FbTk::FbWindow, public FbTk::EventHandler {
public:
    Application(int box_size, int num):
        FbWindow(0,  0, 0, 640, box_size*num/8 - 3*5, ExposureMask | KeyPressMask),
        m_box_size(box_size),
        m_num(num),
        m_font("fixed"),
        m_imgctrl(screenNumber()),
        m_background(*this, 640, 480, depth()),
        m_gc(m_background) {
        setName("Texture Test");
        setBackgroundPixmap(m_background.drawable());

        FbTk::EventManager::instance()->add(*this, *this);

        renderPixmaps();

        show();
    }
    void keyPressEvent(XKeyEvent &ev) {
        //App::instance()->end();
    }
    void exposeEvent(XExposeEvent &ev) {
        clear();
    }

private:

    void renderPixmap(const Texture &text, int x, int y) {
        Pixmap pm = m_imgctrl.renderImage(m_box_size, m_box_size,
                                          text);

        m_background.copyArea(pm, m_gc.gc(),
                              0, 0,
                              x, y,
                              m_box_size, m_box_size);
        m_imgctrl.removeImage(pm);
    }

    void renderPixmaps() {

        m_gc.setForeground(Color("gray", screenNumber()));

        m_background.fillRectangle(m_gc.gc(),
                                   0, 0,
                                   width(), height());
        // for text color
        m_gc.setForeground(Color("black", screenNumber()));

        const int step_size = m_box_size + 5;
        int next_x = 5;
        int next_y = 5;

        TestTheme tm(screenNumber());
        std::auto_ptr<ThemeItem<Texture> > text;
        char value[18];
        for (int i=0; i<m_num; ++i) {
            sprintf(value, "%d", i);
            text.reset(new ThemeItem<Texture>
                       (tm,
                        string("texture") + value,
                        string("Texture") + value));
            // load new style
            ThemeManager::instance().load("test.theme", "");

            renderPixmap(**text.get(), next_x, next_y);

            next_x += step_size;
            if (next_x + m_box_size > width()) {
                m_font.drawText(m_background,
                                screenNumber(),
                                m_gc.gc(),
                                value, strlen(value),
                                next_x, next_y + m_box_size/2);
                next_x = 5;
                next_y += step_size;
            }

        }

    }

    const int m_box_size;
    const int m_num;
    FbTk::Font m_font;
    ImageControl m_imgctrl;
    FbPixmap m_background;
    FbTk::GContext m_gc;
};

int main(int argc, char **argv) {
    int boxsize= 60;
    int num = 63;
    for (int i=1; i<argc; ++i) {
        if (strcmp(argv[i], "-boxsize") == 0 && i + 1 < argc)
            boxsize = atoi(argv[++i]);
        else if (strcmp(argv[i], "-num") == 0 && i + 1 < argc)
            num = atoi(argv[++i]);
     }
    App realapp;
    Application app(boxsize, num);

    realapp.eventLoop();

}
<commit_msg>Render rectangles instead of squares to test TextureRender.cc<commit_after>// texturetest.cc a test app for Textures
// Copyright (c) 2004 - 2006 Henrik Kinnunen (fluxgen at fluxbox dot org)

#include "ImageControl.hh"
#include "Color.hh"
#include "GContext.hh"
#include "FbPixmap.hh"
#include "Texture.hh"
#include "FbWindow.hh"
#include "EventHandler.hh"
#include "EventManager.hh"
#include "Theme.hh"
#include "Font.hh"
#include "App.hh"

#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <memory>
#include <string>

using namespace std;
using namespace FbTk;

class TestTheme: public Theme {
public:
    TestTheme(int screen):Theme(screen) { }
    bool fallback(ThemeItem_base &item) { return false; }
    void reconfigTheme() { }
};

class Application: public FbTk::FbWindow, public FbTk::EventHandler {
public:
    Application(int box_size, int num):
        FbWindow(0,  0, 0, 640, ((5+box_size)*num)/9 + 5, ExposureMask | KeyPressMask),
        m_box_size(box_size),
        m_num(num),
        m_font("fixed"),
        m_imgctrl(screenNumber()),
        m_background(*this, width(), height(), depth()),
        m_gc(m_background) {
        setName("Texture Test");
        setBackgroundPixmap(m_background.drawable());

        FbTk::EventManager::instance()->add(*this, *this);

        renderPixmaps();

        show();
    }
    void keyPressEvent(XKeyEvent &ev) {
        //App::instance()->end();
    }
    void exposeEvent(XExposeEvent &ev) {
        clear();
    }

private:

    void renderPixmap(const Texture &text, int x, int y) {
        Pixmap pm = m_imgctrl.renderImage(2*m_box_size, m_box_size,
                                          text);

        m_background.copyArea(pm, m_gc.gc(),
                              0, 0,
                              x, y,
                              2*m_box_size, m_box_size);
        m_imgctrl.removeImage(pm);
    }

    void renderPixmaps() {

        m_gc.setForeground(Color("gray", screenNumber()));

        m_background.fillRectangle(m_gc.gc(),
                                   0, 0,
                                   width(), height());
        // for text color
        m_gc.setForeground(Color("black", screenNumber()));

        const int step_size = m_box_size + 5;
        int next_x = 5;
        int next_y = 5;

        TestTheme tm(screenNumber());
        std::auto_ptr<ThemeItem<Texture> > text;
        char value[18];
        for (int i=0; i<m_num; ++i) {
            sprintf(value, "%d", i);
            text.reset(new ThemeItem<Texture> (tm, string("texture") + value, string("Texture") + value));

            ThemeManager::instance().load("test.theme", "");
            renderPixmap(**text.get(), next_x, next_y);

            next_x += (step_size + m_box_size);
            if (next_x + 2*m_box_size > width()) {
                m_font.drawText(m_background,
                                screenNumber(),
                                m_gc.gc(),
                                value, strlen(value),
                                next_x, next_y + m_box_size/2);
                next_x = 5;
                next_y += step_size;
            }

        }

    }

    const int m_box_size;
    const int m_num;
    FbTk::Font m_font;
    ImageControl m_imgctrl;
    FbPixmap m_background;
    FbTk::GContext m_gc;
};

int main(int argc, char **argv) {
    int boxsize= 30;
    int num = 63;
    for (int i=1; i<argc; ++i) {
        if (strcmp(argv[i], "-boxsize") == 0 && i + 1 < argc)
            boxsize = atoi(argv[++i]);
        else if (strcmp(argv[i], "-num") == 0 && i + 1 < argc)
            num = atoi(argv[++i]);
     }
    App realapp;
    Application app(boxsize, num);

    realapp.eventLoop();

}
<|endoftext|>