示例#1
0
TEST(MAPPING, MAPPING5) {
    mkdir("tmp", 0700);
    TemporaryFile tmpfile("dbbuilder5", ".dat", "./tmp");

    FILE *filew = fopen(tmpfile.path(), "w");
    GenomeHash genomeHash;
    genomeHash.open(4, 4);
    genomeHash.insert("ATCG", 1);
    genomeHash.insert("GCTA", 2);
    genomeHash.save(filew);
    fprintf(filew, "1\tX\t1.0\n");
    fprintf(filew, "2\tY\t2.0\n");
    fclose(filew);

    {
        PFILE *pfile = pipedopen("./data/paired1.fastq", false);
        ASSERT_TRUE(pfile);
        cppfasta::FastqReader2 reader(pfile->file);

        std::map<std::string, int> result;
        std::map<std::string, double> fpkm;
        uint64_t num;
    
        ASSERT_TRUE(domapping(tmpfile.path(), &reader, &result, &fpkm, NULL, &num, 1, 1, false, false));
        ASSERT_EQ(4U, num);
        ASSERT_EQ(2, result["X"]);
        ASSERT_EQ(2, result["UNMAPPED"]);
        pipedclose(pfile);
    }

    {
        PFILE *pfile1 = pipedopen("./data/paired1.fastq", false);
        ASSERT_TRUE(pfile1);
        PFILE *pfile2 = pipedopen("./data/paired2.fastq", false);
        ASSERT_TRUE(pfile2);
        cppfasta::FastqReader2 reader(pfile1->file, pfile2->file);

        std::map<std::string, int> result;
        std::map<std::string, double> fpkm;
        uint64_t num;
    
        ASSERT_TRUE(domapping(tmpfile.path(), &reader, &result, &fpkm, NULL, &num, 1, 1, false, true));
        ASSERT_EQ(4U, num);
        ASSERT_EQ(3, result["X"]);
        ASSERT_EQ(1, result["UNMAPPED"]);

        pipedclose(pfile1);
        pipedclose(pfile2);
    }

    {
        PFILE *pfile = pipedopen("./data/paired-unified.fastq", false);
        ASSERT_TRUE(pfile);
        cppfasta::FastqReader2 reader(pfile->file);

        std::map<std::string, int> result;
        std::map<std::string, double> fpkm;
        uint64_t num;
    
        ASSERT_TRUE(domapping(tmpfile.path(), &reader, &result, &fpkm, NULL, &num, 1, 1, false, true));
        ASSERT_EQ(4U, num);
        ASSERT_EQ(3, result["X"]);
        ASSERT_EQ(1, result["UNMAPPED"]);

        pipedclose(pfile);
    }

    rmdir("tmp");
}
示例#2
0
/* Basic nominal test of a service.
 */
TEST_F(TestServiceFixture, test_service_nominal) {
  stop_memory_checking();
  rcl_ret_t ret;
  const rosidl_service_type_support_t * ts = ROSIDL_GET_TYPE_SUPPORT(
    example_interfaces, srv, AddTwoInts);
  const char * topic = "add_two_ints";

  rcl_service_t service = rcl_get_zero_initialized_service();
  rcl_service_options_t service_options = rcl_service_get_default_options();
  ret = rcl_service_init(&service, this->node_ptr, ts, topic, &service_options);
  ASSERT_EQ(RCL_RET_OK, ret) << rcl_get_error_string_safe();

  // Check that the service name matches what we assigned.
  EXPECT_EQ(strcmp(rcl_service_get_service_name(&service), topic), 0);
  auto service_exit = make_scope_exit([&service, this]() {
    stop_memory_checking();
    rcl_ret_t ret = rcl_service_fini(&service, this->node_ptr);
    EXPECT_EQ(RCL_RET_OK, ret) << rcl_get_error_string_safe();
  });

  rcl_client_t client = rcl_get_zero_initialized_client();
  rcl_client_options_t client_options = rcl_client_get_default_options();
  ret = rcl_client_init(&client, this->node_ptr, ts, topic, &client_options);
  ASSERT_EQ(RCL_RET_OK, ret) << rcl_get_error_string_safe();
  auto client_exit = make_scope_exit([&client, this]() {
    stop_memory_checking();
    rcl_ret_t ret = rcl_client_fini(&client, this->node_ptr);
    EXPECT_EQ(RCL_RET_OK, ret) << rcl_get_error_string_safe();
  });


  // TODO(wjwwood): add logic to wait for the connection to be established
  //                use count_services busy wait mechanism
  //                until then we will sleep for a short period of time
  std::this_thread::sleep_for(std::chrono::milliseconds(1000));

  // Initialize a request.
  example_interfaces__srv__AddTwoInts_Request client_request;
  example_interfaces__srv__AddTwoInts_Request__init(&client_request);
  client_request.a = 1;
  client_request.b = 2;
  int64_t sequence_number;
  ret = rcl_send_request(&client, &client_request, &sequence_number);
  EXPECT_EQ(sequence_number, 1);
  example_interfaces__srv__AddTwoInts_Request__fini(&client_request);
  ASSERT_EQ(RCL_RET_OK, ret) << rcl_get_error_string_safe();

  bool success;
  wait_for_service_to_be_ready(&service, 10, 100, success);
  ASSERT_TRUE(success);

  // This scope simulates the service responding in a different context so that we can
  // test take_request/send_response in a single-threaded, deterministic execution.
  {
    // Initialize a response.
    example_interfaces__srv__AddTwoInts_Response service_response;
    example_interfaces__srv__AddTwoInts_Response__init(&service_response);
    auto msg_exit = make_scope_exit([&service_response]() {
      stop_memory_checking();
      example_interfaces__srv__AddTwoInts_Response__fini(&service_response);
    });

    // Initialize a separate instance of the request and take the pending request.
    example_interfaces__srv__AddTwoInts_Request service_request;
    example_interfaces__srv__AddTwoInts_Request__init(&service_request);
    rmw_request_id_t header;
    ret = rcl_take_request(&service, &header, &service_request);
    ASSERT_EQ(RCL_RET_OK, ret) << rcl_get_error_string_safe();

    EXPECT_EQ(1, service_request.a);
    EXPECT_EQ(2, service_request.b);
    // Simulate a response callback by summing the request and send the response..
    service_response.sum = service_request.a + service_request.b;
    ret = rcl_send_response(&service, &header, &service_response);
    ASSERT_EQ(RCL_RET_OK, ret) << rcl_get_error_string_safe();
  }
  wait_for_service_to_be_ready(&service, 10, 100, success);

  // Initialize the response owned by the client and take the response.
  example_interfaces__srv__AddTwoInts_Response client_response;
  example_interfaces__srv__AddTwoInts_Response__init(&client_response);

  rmw_request_id_t header;
  ret = rcl_take_response(&client, &header, &client_response);
  ASSERT_EQ(RCL_RET_OK, ret) << rcl_get_error_string_safe();
  EXPECT_EQ(client_response.sum, 3);
  EXPECT_EQ(header.sequence_number, 1);
}
示例#3
0
sgraph& unity_sgraph::get_graph() const {
  ASSERT_TRUE(m_graph);
  return (*m_graph)();
};
示例#4
0
TEST_F(TestGet, test_get_one_row)
{
  int err = 0;
  CommonSchemaManagerWrapper schema_mgr;
  tbsys::CConfig config;
  bool ret_val = schema_mgr.parse_from_file("scan_schema.ini", config);
  ASSERT_TRUE(ret_val);
  ObUpsTableMgr& mgr = ObUpdateServerMain::get_instance()->get_update_server().get_table_mgr();
  err = mgr.init();
  ASSERT_EQ(0, err);
  err = mgr.set_schemas(schema_mgr);
  ASSERT_EQ(0, err);

  TestUpsTableMgrHelper test_helper(mgr);

  TableMgr& table_mgr = test_helper.get_table_mgr();
  table_mgr.sstable_scan_finished(10);

  TableItem* active_memtable_item = table_mgr.get_active_memtable();
  MemTable& active_memtable = active_memtable_item->get_memtable();

  // construct multi-row mutator
  static const int64_t ROW_NUM = 1;
  static const int64_t COL_NUM = 10;

  ObCellInfo cell_infos[ROW_NUM][COL_NUM];
  std::bitset<COL_NUM> check_flags[ROW_NUM];
  char row_key_strs[ROW_NUM][50];
  uint64_t table_id = 10;
  // init cell infos
  for (int64_t i = 0; i < ROW_NUM; ++i)
  {
    sprintf(row_key_strs[i], "row_key_%08ld", i);
    for (int64_t j = 0; j < COL_NUM; ++j)
    {
      cell_infos[i][j].table_id_ = table_id;
      cell_infos[i][j].row_key_ = make_rowkey(row_key_strs[i], &allocator_);

      cell_infos[i][j].column_id_ = j + 10;

      cell_infos[i][j].value_.set_int(1000 + i * COL_NUM + j);
    }
  }

  ObUpsMutator ups_mutator;
  ObMutator &mutator = ups_mutator.get_mutator();
  // add cell to array
  for (int64_t i = 0; i < ROW_NUM; ++i)
  {
    for (int64_t j = 0; j < COL_NUM; ++j)
    {
      ObMutatorCellInfo mutator_cell;
      mutator_cell.cell_info = cell_infos[i][j];
      mutator_cell.op_type.set_ext(ObActionFlag::OP_UPDATE);
      err = mutator.add_cell(mutator_cell);
      EXPECT_EQ(0, err);
    }
  }
  prepare_mutator(mutator);

  // write row to active memtable
  uint64_t trans_descriptor = 0;
  err = active_memtable.start_transaction(WRITE_TRANSACTION, trans_descriptor);
  ASSERT_EQ(0, err);
  err = active_memtable.start_mutation(trans_descriptor);
  ASSERT_EQ(0, err);
  err = active_memtable.set(trans_descriptor, ups_mutator);
  EXPECT_EQ(0, err);
  err = active_memtable.end_mutation(trans_descriptor, false);
  ASSERT_EQ(0, err);
  err = active_memtable.end_transaction(trans_descriptor, false);
  ASSERT_EQ(0, err);
  /*
  ObString text;
  text.assign("/tmp", strlen("/tmp"));
  active_memtable.dump2text(text);
  */

  for (int64_t i = 0; i < ROW_NUM; ++i)
  {
    ObScanner scanner;
    ObGetParam get_param;
    //get_param.set_timestamp(version);
    ObVersionRange version_range;
    //version_range.start_version_ = version;
    //version_range.end_version_ = version;
    version_range.start_version_ = 2;
    //version_range.end_version_ = 2;
    version_range.border_flag_.set_inclusive_start();
    //version_range.border_flag_.set_inclusive_end();
    version_range.border_flag_.set_max_value();
    get_param.set_version_range(version_range);
    for (int64_t j = 0; j < COL_NUM; ++j)
    {
      get_param.add_cell(cell_infos[i][j]);
    }

    int64_t count = 0;
    err = mgr.get(get_param, scanner, tbsys::CTimeUtil::getTime(), 2000000000 * 1000L * 1000L);
    EXPECT_EQ(0, err);

    // check result
    count = 0;
    while (OB_SUCCESS == scanner.next_cell())
    {
      ObCellInfo* p_cell = NULL;
      scanner.get_cell(&p_cell);
      ASSERT_TRUE(p_cell != NULL);
      ObCellInfo expected = cell_infos[count / COL_NUM + i][p_cell->column_id_ - 10];
      check_cell(expected, *p_cell);
      check_flags[count / COL_NUM].set(p_cell->column_id_ - 10);
      ++count;
    }
    EXPECT_EQ(COL_NUM, count);
    for (int64_t i = 0; i < ROW_NUM; i++)
    {
      EXPECT_EQ(COL_NUM, (int64_t)check_flags[i].size());
    }
  }
}
示例#5
0
TEST(ProcessorSet, empty) {
  ProcessorSet processor_set;
  ASSERT_TRUE(processor_set.empty());
  processor_set.set(0);
  ASSERT_FALSE(processor_set.empty());
}
示例#6
0
TEST(RandoTest, nearestToZero)
{
  Rando rando;
  int a, b;
  ASSERT_TRUE( rando.nearestToZero(a,b));
}
示例#7
0
TEST(RandoTest, isDivisbleBy)
{
	Rando rando;
	int first, second;
	ASSERT_TRUE( rando.isDivisbleBy(first,second));
}
示例#8
0
TEST_F(MorphoGeneSerializationTest,isEqualAfterSerialization) {
    ASSERT_TRUE(morphoGene != morphoGene2);
    ASSERT_TRUE(morphoGene->equals(*morphoGene2));
}
	void WriteOut()
	{
		ASSERT_TRUE(writer.WriteOut("binaryTest.dat", false));

	}
示例#10
0
TEST_F(MorphoGeneTest,hasValidColor) {
    //test valid color
    ASSERT_TRUE(0 <= gene->getColorR() <= 255);
    ASSERT_TRUE(0 <= gene->getColorG() <= 255);
    ASSERT_TRUE(0 <= gene->getColorB() <= 255);
}
示例#11
0
TEST_F(MorphoGeneTest,hasAccurateBranchQty) {
    //test if the number of branches is lower or equal to the bushiness factor
    ASSERT_TRUE(gene->getGeneBranches().size() <= 30);
}
示例#12
0
CTEST2(tube_stream, get_tube_manager)
{
    tube_manager *tm = tube_stream_manager_get_manager(data->sm);
    ASSERT_TRUE( (uintptr_t)tm == (uintptr_t)data->sm );
}
示例#13
0
	//}
	virtual void TearDown()
	{
		ASSERT_TRUE(s_pCmdParser != nullptr);
		s_pCmdParser->resetStatu();
	}
示例#14
0
void consumer(qi::atomic<long> &gSuccess, qi::Future<int> fut) {
  //wont block thread on error
  ASSERT_TRUE(fut.wait(1000));
  EXPECT_EQ(42, fut.value());
  ++gSuccess;
}
示例#15
0
TEST(is_just_whitespaces, demo_case_true)
{
   ASSERT_TRUE(mzlib::is_just_whitespaces("\t\n \r\v\f"));
}
示例#16
0
void NamenodeTest::test_namenode_server()
{
	for (int i = 1; i <= FLAGS_N; i++)
	{
		ThriftResult result;
		DatanodeHeartbeat hti;
		hti.endpoint.nodeid = i;
		mCluster.get_namenode_if()->datanode_heartbeat(result, hti);
	}

	sleep(2); //wait for heartbeat finish

	FileWriteToken token;
	mServer->get_write_token(token);

	int32_t blockid = token.blockid;

	ASSERT_TRUE(token.chunkids.size() == (size_t)FLAGS_N);

	std::set<int32_t> failed;
	int32_t failid = *token.chunkids.begin();
	LOG(ERROR) << "failed block id " << failid;
	failed.insert(failid);

	FileWriteToken fix_token;
	mServer->fix_write_token(fix_token, blockid, failed);

	ASSERT_TRUE(fix_token.chunkids[0] != token.chunkids[0]);

	for (int i = 1; i < FLAGS_N; i++) {
		ASSERT_TRUE(fix_token.chunkids[i] == token.chunkids[i]);
	}

	for (int i = 0; i < FLAGS_N; i++)
	{
		ThriftResult result;
		std::string data("hello world");
		int32_t chunkid = fix_token.chunkids[i];
		mCluster.get_datanode_if(NODE_ID(chunkid))->put_chunk(result, chunkid, data);
	}

	mServer->commit_write(blockid);

	FileReadToken read_token;
	mServer->get_read_token(read_token, blockid);

	for (int i = 0; i < FLAGS_N; i++) {
		ASSERT_TRUE(fix_token.chunkids[i] == read_token.chunkids[i]);
	}

	mServer->get_oplog_manager().uninit();
	mServer->get_oplog_manager().init();

	FileReadToken new_read;
	mServer->get_read_token(new_read, blockid);

	for (int i = 0; i < FLAGS_N; i++) {
		ASSERT_TRUE(fix_token.chunkids[i] == new_read.chunkids[i]);
	}

	mServer->delete_block(blockid);

	mServer->get_oplog_manager().uninit();
	mServer->get_oplog_manager().init();

	std::vector<int32_t> chunkids;
	mServer->get_block_manager().get_chunk_ids(blockid, chunkids, true);
	ASSERT_TRUE(chunkids.empty());
}
示例#17
0
TEST(RandoTest, allChildrenSmile)
{
	Rando rando;
	ASSERT_TRUE( rando.shouldWorry(true,true,true) );
	ASSERT_TRUE( rando.shouldWorry(true,false,false) );
}
// This test is disable because it is for generating test data.
TEST(libbacktrace, DISABLED_generate_offline_testdata) {
  // Create a thread to generate the needed stack and registers information.
  const size_t stack_size = 16 * 1024;
  void* stack = mmap(NULL, stack_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
  ASSERT_NE(MAP_FAILED, stack);
  uintptr_t stack_addr = reinterpret_cast<uintptr_t>(stack);
  pthread_attr_t attr;
  ASSERT_EQ(0, pthread_attr_init(&attr));
  ASSERT_EQ(0, pthread_attr_setstack(&attr, reinterpret_cast<void*>(stack), stack_size));
  pthread_t thread;
  OfflineThreadArg arg;
  arg.exit_flag = 0;
  ASSERT_EQ(0, pthread_create(&thread, &attr, OfflineThreadFunc, &arg));
  // Wait for the offline thread to generate the stack and unw_context information.
  sleep(1);
  // Copy the stack information.
  std::vector<uint8_t> stack_data(reinterpret_cast<uint8_t*>(stack),
                                  reinterpret_cast<uint8_t*>(stack) + stack_size);
  arg.exit_flag = 1;
  ASSERT_EQ(0, pthread_join(thread, nullptr));
  ASSERT_EQ(0, munmap(stack, stack_size));

  std::unique_ptr<BacktraceMap> map(BacktraceMap::Create(getpid()));
  ASSERT_TRUE(map != nullptr);

  backtrace_stackinfo_t stack_info;
  stack_info.start = stack_addr;
  stack_info.end = stack_addr + stack_size;
  stack_info.data = stack_data.data();

  // Generate offline testdata.
  std::string testdata;
  // 1. Dump pid, tid
  testdata += android::base::StringPrintf("pid: %d tid: %d\n", getpid(), arg.tid);
  // 2. Dump maps
  for (auto it = map->begin(); it != map->end(); ++it) {
    testdata += android::base::StringPrintf(
        "map: start: %" PRIxPTR " end: %" PRIxPTR " offset: %" PRIxPTR " load_bias: %" PRIxPTR
        " flags: %d name: %s\n",
        it->start, it->end, it->offset, it->load_bias, it->flags, it->name.c_str());
  }
  // 3. Dump registers
  testdata += android::base::StringPrintf("registers: %zu ", sizeof(arg.unw_context));
  testdata += RawDataToHexString(&arg.unw_context, sizeof(arg.unw_context));
  testdata.push_back('\n');

  // 4. Dump stack
  testdata += android::base::StringPrintf(
      "stack: start: %" PRIx64 " end: %" PRIx64 " size: %zu ",
      stack_info.start, stack_info.end, stack_data.size());
  testdata += RawDataToHexString(stack_data.data(), stack_data.size());
  testdata.push_back('\n');

  // 5. Dump function symbols
  std::vector<FunctionSymbol> function_symbols = GetFunctionSymbols();
  for (const auto& symbol : function_symbols) {
    testdata += android::base::StringPrintf(
        "function: start: %" PRIxPTR " end: %" PRIxPTR" name: %s\n",
        symbol.start, symbol.end, symbol.name.c_str());
  }

  ASSERT_TRUE(android::base::WriteStringToFile(testdata, "offline_testdata"));
}
示例#19
0
TEST(RandoTest, isPrime)
{
	Rando rando;
	int a;
	ASSERT_TRUE( rando.isPrime(a));
}
示例#20
0
int main(int argc, char** argv) {
  // Initialize control plain using mpi
  graphlab::mpi_tools::init(argc, argv);
  graphlab::distributed_control dc;
  dc_ptr = &dc;
  global_logger().set_log_level(LOG_INFO);

  // Parse command line options -----------------------------------------------
  graphlab::command_line_options clopts("./ldademo");
  std::string lda_edges;
  std::string lda_dictionary;

  bool USE_SYNC=false;

  // The dir of the link graph 
  clopts.attach_option("lda_edges", lda_edges, "The lda graph (edges). Required ");
  clopts.attach_option("lda_dictionary", lda_dictionary, "The lda word dictionary. Required ");
  clopts.attach_option("wordid_offset", lda::WORDID_OFFSET, "The starting id of the words in the lda input.");
  clopts.attach_option("ntopics", lda::NTOPICS, "Number of topics to use");
  clopts.attach_option("topklda", lda::TOPK, "Top k words in each topic for display");
  clopts.attach_option("force_lock", lda::FORCE_LOCK, "force locked words");
  clopts.attach_option("use_sync", USE_SYNC, "Use Synchronous LDA");

  if(!clopts.parse(argc, argv)) {
    dc.cout() << "Error in parsing command line arguments." << std::endl;
    return EXIT_FAILURE;
  }

  if(!clopts.is_set("lda_edges")) {
    std::cout << "LDA edge file not provided" << std::endl;
    clopts.print_description();
    return EXIT_FAILURE;
  }
  if(!clopts.is_set("lda_dictionary")) {
    std::cout << "LDA dictionary file not provided" << std::endl;
    clopts.print_description();
    return EXIT_FAILURE;
  }

  lda::INITIAL_NTOPICS = NTOPICS;

  // Build the lda (right) graph
  // The global lda_graph points to rgraph
  lda::graph_type ldagraph(dc);
  load_ldagraph(ldagraph, lda_edges, lda_dictionary);

  // Run lda -----------------------------------------------------------------
  launch_metric_server();

  graphlab::graphlab_options opts;
  std::string engine_type = "sync";
  if (!USE_SYNC) {
    opts.get_engine_args().set_option("factorized",true);
    engine_type = "async";
  }
  //opts2.get_engine_args().set_option("handler_intercept",true);
  graphlab::omni_engine<lda::cgs_lda_vertex_program> engine(dc, ldagraph, engine_type, opts);
  lda::initialize_global();
  { 
    const bool success =
        engine.add_vertex_aggregator<lda::topk_aggregator>
        ("topk", lda::topk_aggregator::map, lda::topk_aggregator::finalize) &&
        engine.aggregate_periodic("topk", 1);
    ASSERT_TRUE(success);
  }

  { // Add the Global counts aggregator
    const bool success =
        engine.add_vertex_aggregator<lda::factor_type>
        ("global_counts", 
         lda::global_counts_aggregator::map, 
         lda::global_counts_aggregator::finalize) &&
        engine.aggregate_periodic("global_counts", 1);
    ASSERT_TRUE(success);
  }
  fn_run_lda(engine);

// ------------FINALIZE------------------
// --------------------------------------
graphlab::stop_metric_server_on_eof();
graphlab::mpi_tools::finalize();

return EXIT_SUCCESS;
}
示例#21
0
TEST(auto_Object, out_of_scope) {
  {
    auto_Object<TestObject>(new TestObject);
  }
  ASSERT_TRUE(TestObject::deleted);
}
// Tests that the default container logger writes files into the sandbox.
TEST_F(ContainerLoggerTest, DefaultToSandbox)
{
  // Create a master, agent, and framework.
  Try<PID<Master>> master = StartMaster();
  ASSERT_SOME(master);

  Future<SlaveRegisteredMessage> slaveRegisteredMessage =
    FUTURE_PROTOBUF(SlaveRegisteredMessage(), _, _);

  // We'll need access to these flags later.
  slave::Flags flags = CreateSlaveFlags();

  Fetcher fetcher;

  // We use an actual containerizer + executor since we want something to run.
  Try<MesosContainerizer*> containerizer =
    MesosContainerizer::create(flags, false, &fetcher);
  CHECK_SOME(containerizer);

  Try<PID<Slave>> slave = StartSlave(containerizer.get(), flags);
  ASSERT_SOME(slave);

  AWAIT_READY(slaveRegisteredMessage);
  SlaveID slaveId = slaveRegisteredMessage.get().slave_id();

  MockScheduler sched;
  MesosSchedulerDriver driver(
      &sched, DEFAULT_FRAMEWORK_INFO, master.get(), DEFAULT_CREDENTIAL);

  Future<FrameworkID> frameworkId;
  EXPECT_CALL(sched, registered(&driver, _, _))
    .WillOnce(FutureArg<1>(&frameworkId));

  // Wait for an offer, and start a task.
  Future<vector<Offer>> offers;
  EXPECT_CALL(sched, resourceOffers(&driver, _))
    .WillOnce(FutureArg<1>(&offers))
    .WillRepeatedly(Return()); // Ignore subsequent offers.

  driver.start();
  AWAIT_READY(frameworkId);

  AWAIT_READY(offers);
  EXPECT_NE(0u, offers.get().size());

  // We'll start a task that outputs to stdout.
  TaskInfo task = createTask(offers.get()[0], "echo 'Hello World!'");

  Future<TaskStatus> status;
  EXPECT_CALL(sched, statusUpdate(&driver, _))
    .WillOnce(FutureArg<1>(&status))
    .WillRepeatedly(Return());       // Ignore subsequent updates.

  driver.launchTasks(offers.get()[0].id(), {task});

  AWAIT_READY(status);
  EXPECT_EQ(TASK_RUNNING, status.get().state());

  // Check that the sandbox was written to.
  string sandboxDirectory = path::join(
      slave::paths::getExecutorPath(
          flags.work_dir,
          slaveId,
          frameworkId.get(),
          status->executor_id()),
      "runs",
      "latest");

  ASSERT_TRUE(os::exists(sandboxDirectory));

  string stdoutPath = path::join(sandboxDirectory, "stdout");
  ASSERT_TRUE(os::exists(stdoutPath));

  Result<string> stdout = os::read(stdoutPath);
  ASSERT_SOME(stdout);
  EXPECT_TRUE(strings::contains(stdout.get(), "Hello World!"));

  driver.stop();
  driver.join();

  Shutdown();
}
TEST(OmplPlanning, PathConstrainedSimplePlan)
{
  ros::NodeHandle nh;
  ros::service::waitForService(PLANNER_SERVICE_NAME);
  ros::Publisher pub = nh.advertise<moveit_msgs::DisplayTrajectory>("display_motion_plan", 1);

  ros::ServiceClient planning_service_client = nh.serviceClient<moveit_msgs::GetMotionPlan>(PLANNER_SERVICE_NAME);
  EXPECT_TRUE(planning_service_client.exists());
  EXPECT_TRUE(planning_service_client.isValid());

  moveit_msgs::GetMotionPlan::Request mplan_req;
  moveit_msgs::GetMotionPlan::Response mplan_res;

  planning_scene_monitor::PlanningSceneMonitor psm(ROBOT_DESCRIPTION);
  planning_scene::PlanningScene &scene = *psm.getPlanningScene();
  EXPECT_TRUE(scene.isConfigured());

  mplan_req.motion_plan_request.planner_id = "RRTConnectkConfigDefault";
  mplan_req.motion_plan_request.group_name = "right_arm";
  mplan_req.motion_plan_request.num_planning_attempts = 1;
  mplan_req.motion_plan_request.allowed_planning_time = ros::Duration(15.0);
  const std::vector<std::string>& joint_names = scene.getRobotModel()->getJointModelGroup("right_arm")->getJointModelNames();

  mplan_req.motion_plan_request.start_state.joint_state.name = joint_names;
  mplan_req.motion_plan_request.start_state.joint_state.position.push_back(-1.21044517893021499);
  mplan_req.motion_plan_request.start_state.joint_state.position.push_back(0.038959594993384528);
  mplan_req.motion_plan_request.start_state.joint_state.position.push_back(-0.81412902362644646);
  mplan_req.motion_plan_request.start_state.joint_state.position.push_back(-1.0989597173881371);
  mplan_req.motion_plan_request.start_state.joint_state.position.push_back(2.3582101183671629);
  mplan_req.motion_plan_request.start_state.joint_state.position.push_back(-1.993988668449755);
  mplan_req.motion_plan_request.start_state.joint_state.position.push_back(-2.2779628049776051);


  moveit_msgs::PositionConstraint pcm;
  pcm.link_name = "r_wrist_roll_link";
  pcm.header.frame_id = psm.getPlanningScene()->getPlanningFrame();

  pcm.constraint_region.primitive_poses.resize(1);
  pcm.constraint_region.primitive_poses[0].position.x = 0.5;
  pcm.constraint_region.primitive_poses[0].position.y = 0.0;
  pcm.constraint_region.primitive_poses[0].position.z = 0.7;
  pcm.constraint_region.primitive_poses[0].orientation.w = 1.0;

  pcm.constraint_region.primitives.resize(1);
  pcm.constraint_region.primitives[0].type = shape_msgs::SolidPrimitive::BOX;
  pcm.constraint_region.primitives[0].dimensions.x = 0.1;
  pcm.constraint_region.primitives[0].dimensions.y = 0.1;
  pcm.constraint_region.primitives[0].dimensions.z = 0.1;
  pcm.weight = 1.0;
  mplan_req.motion_plan_request.goal_constraints.resize(1);
  mplan_req.motion_plan_request.goal_constraints[0].position_constraints.push_back(pcm);


  // add path constraints
  moveit_msgs::Constraints &constr = mplan_req.motion_plan_request.path_constraints;
  constr.orientation_constraints.resize(1);
  moveit_msgs::OrientationConstraint &ocm = constr.orientation_constraints[0];
  ocm.link_name = "r_wrist_roll_link";
  ocm.header.frame_id = psm.getPlanningScene()->getPlanningFrame();
  ocm.orientation.x = 0.0;
  ocm.orientation.y = 0.0;
  ocm.orientation.z = 0.0;
  ocm.orientation.w = 1.0;
  ocm.absolute_x_axis_tolerance = 0.15;
  ocm.absolute_y_axis_tolerance = 0.15;
  ocm.absolute_z_axis_tolerance = M_PI;
  ocm.weight = 1.0;
  std::cout << mplan_req.motion_plan_request << std::endl;

  ASSERT_TRUE(planning_service_client.call(mplan_req, mplan_res));
  ASSERT_EQ(mplan_res.error_code.val, mplan_res.error_code.SUCCESS);
  EXPECT_GT(mplan_res.trajectory.joint_trajectory.points.size(), 0);


  moveit_msgs::DisplayTrajectory d;
  d.model_id = scene.getRobotModel()->getName();
  d.trajectory_start = mplan_res.trajectory_start;
  d.trajectory = mplan_res.trajectory;
  pub.publish(d);
  ros::Duration(0.5).sleep();
}
示例#24
0
TEST_F(CampaignTest, testAircraftHandling)
{
	const vec2_t destination = { 10, 10 };
	base_t* base;
	aircraft_t* aircraft;
	aircraft_t* newAircraft;
	aircraft_t* aircraftTemplate;
	int firstIdx;
	int initialCount;
	int count;
	int newFound;

	base = CreateBase("unittestaircraft", destination);
	ASSERT_TRUE(nullptr != base);

	/** @todo we should not assume that initial base has aircraft. It's a campaign parameter */
	aircraft = AIR_GetFirstFromBase(base);
	ASSERT_TRUE(nullptr != aircraft);

	/* aircraft should have a template */
	aircraftTemplate = aircraft->tpl;
	ASSERT_TRUE(nullptr != aircraftTemplate);

	firstIdx = aircraft->idx;
	initialCount = AIR_BaseCountAircraft(base);

	/* test deletion (part 1) */
	AIR_DeleteAircraft(aircraft);
	count = AIR_BaseCountAircraft(base);
	ASSERT_EQ(count, initialCount - 1);

	/* test addition (part 1) */
	newAircraft = AIR_NewAircraft(base, aircraftTemplate);
	ASSERT_TRUE(nullptr != newAircraft);
	count = AIR_BaseCountAircraft(base);
	ASSERT_EQ(count, initialCount);

	/* new aircraft assigned to the right base */
	ASSERT_EQ(newAircraft->homebase, base);

	newFound = 0;
	AIR_Foreach(a) {
		/* test deletion (part 2) */
		ASSERT_NE(firstIdx, a->idx);
		/* for test addition (part 2) */
		if (a->idx == newAircraft->idx)
			newFound++;
	}
	/* test addition (part 2) */
	ASSERT_EQ(newFound, 1);

	/* check if AIR_Foreach iterates through all aircraft */
	AIR_Foreach(a) {
		AIR_DeleteAircraft(a);
	}
	aircraft = AIR_GetFirstFromBase(base);
	ASSERT_TRUE(nullptr == aircraft);
	count = AIR_BaseCountAircraft(base);
	ASSERT_EQ(count, 0);

	/* cleanup for the following tests */
	E_DeleteAllEmployees(nullptr);

	base->founded = false;
}
示例#25
0
TEST(ProcessorSet, set) {
  ProcessorSet processor_set;
  processor_set.set(0);
  ASSERT_TRUE(processor_set.isset(0));
  ASSERT_FALSE(processor_set.isset(1));
}
示例#26
0
TEST(testBattery, GetSystemPowerStatus)
{
    SYSTEM_POWER_STATUS sps;
    ASSERT_TRUE(GetSystemPowerStatus(&sps));
}
示例#27
0
TEST(EditorTest, panZoom)
{
    GamePair pair;
    EditorUserInterface editorUi(pair.getClient(0), NULL);

    // The basics
    F32 scale = 1.1f;
    editorUi.setDisplayScale(scale);
    ASSERT_EQ(scale, editorUi.getCurrentScale());

    Point center(33,44);
    editorUi.setDisplayCenter(center);
    ASSERT_FLOAT_EQ(center.x, editorUi.getDisplayCenter().x);
    ASSERT_FLOAT_EQ(center.y, editorUi.getDisplayCenter().y);

    // Changing center shouldn't change scale
    ASSERT_EQ(scale, editorUi.getCurrentScale());

    // Changing scale shouldn't change center
    scale = 1.4f;
    editorUi.setDisplayScale(scale);
    ASSERT_EQ(scale, editorUi.getCurrentScale());
    ASSERT_FLOAT_EQ(center.x, editorUi.getDisplayCenter().x);
    ASSERT_FLOAT_EQ(center.y, editorUi.getDisplayCenter().y);

    // Make sure center is what we expect after setting extents -- use non-proportionate size
    editorUi.setDisplayExtents(Rect(0,0,  1000,1000));
    ASSERT_FLOAT_EQ(0.6f, editorUi.getCurrentScale());    // Based on standard 800x600 window size
    ASSERT_FLOAT_EQ(500, editorUi.getDisplayCenter().x);
    ASSERT_FLOAT_EQ(500, editorUi.getDisplayCenter().y);

    Rect r;

    r = editorUi.getDisplayExtents();
    ASSERT_FLOAT_EQ(-166.666667f, r.min.x);   // These depend on 800x600 display aspect ratio
    ASSERT_FLOAT_EQ(1166.666667f, r.max.x);
    ASSERT_TRUE(fabs(r.min.y) < .0001);        // We're getting errors here too great to use ASSERT_FLOAT_EQ
    ASSERT_FLOAT_EQ(1000       , r.max.y);

    ASSERT_FLOAT_EQ(r.getCenter().x, editorUi.getDisplayCenter().x);
    ASSERT_FLOAT_EQ(r.getCenter().y, editorUi.getDisplayCenter().y);

    editorUi.setDisplayExtents(Rect(0,0,  800,600));
    EXPECT_FLOAT_EQ(1, editorUi.getCurrentScale());    // Based on standard 800x600 window size
    ASSERT_FLOAT_EQ(400, editorUi.getDisplayCenter().x);
    ASSERT_FLOAT_EQ(300, editorUi.getDisplayCenter().y);

    r = editorUi.getDisplayExtents();
    ASSERT_FLOAT_EQ(r.getCenter().x, editorUi.getDisplayCenter().x);
    ASSERT_FLOAT_EQ(r.getCenter().y, editorUi.getDisplayCenter().y);


    // Zooming out should double the extents, but not change the center
    scale = editorUi.getCurrentScale() / 2;
    editorUi.setDisplayScale(scale);
    ASSERT_FLOAT_EQ(400, editorUi.getDisplayCenter().x);
    ASSERT_FLOAT_EQ(300, editorUi.getDisplayCenter().y);
    r = editorUi.getDisplayExtents();
    ASSERT_FLOAT_EQ(-400, r.min.x);
    ASSERT_FLOAT_EQ(-300, r.min.y);
    ASSERT_FLOAT_EQ(1200, r.max.x);
    ASSERT_FLOAT_EQ( 900, r.max.y);
}
示例#28
0
std::string TmpDir() {
  std::string dir;
  Status s = Env::Default()->GetTestDirectory(&dir);
  ASSERT_TRUE(s.ok()) << s.ToString();
  return dir;
}
/**
 * Verify that seekg works going forward
 */
TEST_F(StreamFunctionsTest, seekgBasicForward) {
    const std::streampos step = 2;
    m_stream->seekg(step);
    ASSERT_TRUE(streamAndDataAreEqual(*m_stream, TEST_DATA + step, sizeof(TEST_DATA) - step));
}
示例#30
0
/**
 * @brief This test cycles through the list of map definitions found in the maps.ufo script
 * and builds each map with each ufo and every assembly for all valid seeds.
 * In other words: this a FULL test to check if some seed causes problems in any of the
 * possible combinations, so it should not be run on the buildserver on a daily basis.
 */
TEST_F(MapDefMassRMATest, DISABLED_MapDefsMassRMA)
{
	/** You can test a certain assembly by passing "-Dmapdef-id=assembly" to testall. */
	const char* filterId = TEST_GetStringProperty("mapdef-id");
	const mapDef_t* md;
	int mapCount = 0;

	ASSERT_TRUE(csi.numMDs > 0);

	MapDef_Foreach(md) {
		if (md->mapTheme[0] == '.')
			continue;
		if (filterId && !Q_streq(filterId, md->id))
			continue;
		if (++mapCount <= 0)		/* change 0 to n to skip the first n assemblies */
			continue;

		{
			char* p = md->mapTheme;

			if (*p == '+')
				p++;
			else
				continue;

			const char* asmName = (const char*)LIST_GetByIdx(md->params, 0);
			Com_Printf("\nMap: %s Assembly: %s AssNr: %i\n", p, asmName, mapCount);

			sv_threads->integer = 0;

			/* This is tricky. Some maps don't have any ufo on them and thus in the mapdef.
			 * That would cause a LIST_Foreach macro to never run it's body. That's why these
			 * for-loops seem to have two termination conditions. In fact, we have to manually
			 * exit the for-loops if we ran it just once (without ufos nor dropships).
			 */
			bool didItOnce = false;
			linkedList_t* iterDrop;
			for (iterDrop = md->aircraft; iterDrop || !didItOnce; iterDrop = iterDrop->next) {
				const char* craft = nullptr;
				if (iterDrop)
					craft = (const char*) (iterDrop->data);

				if (craft)
					Cvar_Set("rm_drop", "%s", Com_GetRandomMapAssemblyNameForCraft(craft));
				else
					Cvar_Set("rm_drop", "+craft_drop_firebird");

				linkedList_t* iterUfo;
				for (iterUfo = md->ufos; iterUfo || !didItOnce; iterUfo = iterUfo->next) {
					const char* ufo = nullptr;
					if (iterUfo)
						ufo = (const char*) (iterUfo->data);
					if (ufo)
						Cvar_Set("rm_ufo", "%s", Com_GetRandomMapAssemblyNameForCraft(ufo));
					else
						Cvar_Set("rm_ufo", "+craft_ufo_scout");

					Com_Printf("\nDrop: %s Ufo: %s", craft, ufo);
					Com_Printf("\nSeed:");
					for (int i = 0; i < RMA_HIGHEST_SUPPORTED_SEED; i++) {
						asmName = nullptr;
						srand(i);
						long time = Sys_Milliseconds();
						Com_Printf(" %i", i);
#if 0

						typedef struct skip_info {
							int         seed;
							char const* map;
							char const* params;
							char const* craft;
							char const* ufo;
						} skip_info;
						/* if we have known problems with some combinations, we can skip them */
						skip_info const skip_list[] = {
							/* examples: */
						//	{ 20, "forest",		"large",		"craft_drop_raptor",   0                     },
						//	{ 12, "forest",		"large"			"craft_drop_herakles", "craft_ufo_harvester" },
							{ -1, "frozen",		"nature_medium",0,                     0                     },
							{ 11, "village",	"medium",		0,                     0					 },
							{ 19, "village",	"medium",		0,                     0					 },
							{ -1, "village",	"medium_noufo",	0,                     0					 },
							{ -1, "village",	"small",		0,                     0					 },
						};

						bool skip = false;
						for (skip_info const* e = skip_list; e != endof(skip_list); ++e) {
							if (e->seed >= 0 && i != e->seed)
								continue;
							if (e->map && !Q_streq(p, e->map))
								continue;
							if (e->params && !Q_streq(md->params, e->params))
								continue;
							if (e->craft && !Q_streq(craft, e->craft))
								continue;
							if (e->ufo && !Q_streq(ufo, e->ufo))
								continue;
							skip = true;
							break;
						}
						if (skip)
							continue;
#endif
						/* for ufocrash map, the ufoname is the assemblyame */
						if (Q_streq(p, "ufocrash"))
							asmName = Com_GetRandomMapAssemblyNameForCraft(ufo) + 1;	/* +1 = get rid of the '+' */
						else
							asmName = (const char*)LIST_GetByIdx(md->params, 0);


						char* entityString = SV_GetConfigString(CS_ENTITYSTRING);
						int numPlaced = SV_AssembleMap(p, asmName, mapStr, posStr, entityString, i, false);
						ASSERT_TRUE(numPlaced != 0);
						time = (Sys_Milliseconds() - time);
						ASSERT_TRUE(time < 30000);
						if (time > 10000)
							Com_Printf("\nMap: %s Assembly: %s Seed: %i tiles: %i ms: %li\n", p, asmName, i, numPlaced, time);
					}
					didItOnce = true;
					if (!iterUfo)
						break;
				}
				if (!iterDrop)
					break;
			}
		}
	}
}