<commit_before>#include "catch.hpp"

#include <api_types.hpp>

TEST_CASE("create a type_tag object", "[type_tag]")
{
    shadow::type_info t_info{"double", 8};

    auto t_tag = shadow::type_tag(t_info);

    REQUIRE(t_tag.name() == std::string("double"));
    REQUIRE(t_tag.size() == 8);

    SECTION("create another type_tag object with same type_info")
    {
        auto t_tag2 = shadow::type_tag(t_info);

        REQUIRE(t_tag == t_tag2);
    }

    SECTION("create another type_tag with an equivalent type_info")
    {
        shadow::type_info t_info2{"double", 8};

        auto t_tag2 = shadow::type_tag(t_info2);

        REQUIRE(t_tag == t_tag2);
    }

    SECTION("create another type_tag with another type_info")
    {
        shadow::type_info t_info2{"int", 4};

        auto t_tag2 = shadow::type_tag(t_info2);

        REQUIRE(t_tag != t_tag2);
    }
}
<commit_msg>Add unit test for default constructed shadow::object. 	modified:   tests/test_api_types.cpp<commit_after>#include "catch.hpp"

#include <api_types.hpp>

TEST_CASE("create a type_tag object", "[type_tag]")
{
    shadow::type_info t_info{"double", 8};

    auto t_tag = shadow::type_tag(t_info);

    REQUIRE(t_tag.name() == std::string("double"));
    REQUIRE(t_tag.size() == 8);

    SECTION("create another type_tag object with same type_info")
    {
        auto t_tag2 = shadow::type_tag(t_info);

        REQUIRE(t_tag == t_tag2);
    }

    SECTION("create another type_tag with an equivalent type_info")
    {
        shadow::type_info t_info2{"double", 8};

        auto t_tag2 = shadow::type_tag(t_info2);

        REQUIRE(t_tag == t_tag2);
    }

    SECTION("create another type_tag with another type_info")
    {
        shadow::type_info t_info2{"int", 4};

        auto t_tag2 = shadow::type_tag(t_info2);

        REQUIRE(t_tag != t_tag2);
    }
}

TEST_CASE("default construction of shadow::object", "[shadow::object]")
{
    shadow::object a;

    REQUIRE(a.type().name() == std::string("void"));
}
<|endoftext|>


<commit_before>#include <string.h>
#include <pthread.h>
#include <iostream>
#include <sstream>
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "debug_Simprompt.hpp"
#include "debug_Simhandler.hpp"
#include "serialization.hpp"
#include "types.hpp"
#include "blinkyBlocksVM.h"

using namespace std;
using namespace debugger;

namespace debugger {

#define SIZE (sizeof(message_type))
#define BROADCAST true

    /*****************************************************************/

    /*GLOBAL STORED VARS: debug handling specific*/

    /****************************************************************/

    std::queue<message_type*> *messageQueue;
    /*global variables to controll main thread*/
    static bool isSystemPaused = true;
    static bool isDebug = false;
    static bool isSimDebug = false;
    static bool isPausedAtBreakpoint = false;
	static bool okayToBroadcastPause = true;
    /*number of messages the Master expects to recieve*/
    int numberExpected = 0;

    bool verboseMode = false;
    bool serializationMode = false;

    /**********************************************************************/

    /* I/0 SPECIFICATION PARSING */

    /*********************************************************************/

    /*returns the index of a character in a string,
     *if it is not there it returns -1*/
    int characterInStringIndex(string str, char character){
        for(unsigned int i = 0; i < str.length(); i++){
            if (str[i] == character)
                return (int)i;
        }
        return -1;
    }

    /*extracts the type from the specification from input line
     *returns the type of breakpoint from the specification
     *invariant-- the type is always specified*/
    string getType(string specification){
        string build = "";
        for (unsigned int i = 0; i < specification.length(); i++){
            if(specification[i] == ':' || specification[i] == '@')
                return build;
            else
                build += specification[i];
        }
        return build;
    }

    /*extracts the name from the specification
     *returns the name from the specification
     *returns "" if name is not present*/
    string getName(string specification){
        string build = "";
        //find index of colon
        int index = characterInStringIndex(specification, ':');
        // if colon not there
        if (index == -1)
            return "";
        for (unsigned int i = index +1;
             i < specification.length(); i++){
            if (specification[i] == '@')
                return build;
            else
                build += specification[i];
        }
        return build;
    }

    /*extracts the node from the specification
     *returns the node from the specification
     *returns "" if node is not given*/
    string getNode(string specification){
        string build = "";
        int index = characterInStringIndex(specification, '@');
        if (index == -1)
            return "";
        for (unsigned int i = index+1; i < specification.length(); i++){
            build+=specification[i];
        }
        return build;
    }

    /*given the encoding return the corresponding string for
     *break point types*/
    string typeInt2String(int type){
        switch(type){
            case FACTDER:
                return "factDer";
            case FACTCON:
                return "factCon";
            case FACTRET:
                return "factRet";
            case ACTION:
                return "action";
            case SENSE:
                return "sense";
            case BLOCK:
                return "block";
        }
        return "";
    }

    /**********************************************************************/

    /*SIMULATION DEBUGGING FUNCTIONS*/

    /*********************************************************************/

   void setFlags(string specification){
        ostringstream msg;
        for (int i = 0; i < specification.length(); i++){
            if ((uint)specification[i] == 'V'){
                verboseMode = true;
            } else if ((uint)specification[i] == 'S'){
                serializationMode = true;
            }
        }
    }

    void debugController(int instruction, string specification){

        string type;
        string name;
        string node;

            if (instruction == CONTINUE || instruction == UNPAUSE){
				okayToBroadcastPause = true;
                /*continue a paused system by broadcasting an CONTINUE signal*/
                unPauseSimulation();
                numberExpected = sendMsg(-1,CONTINUE,"",BROADCAST);
            } else if (instruction == RUN){
                okayToBroadcastPause = true;
                /*continue a paused system by broadcasting an CONTINUE signal*/
                unPauseSimulation();
                numberExpected = sendMsg(-1,CONTINUE,"",BROADCAST);
            } else if (instruction == DUMP) {

                /*broadcast the message to all VMs*/
                if (specification == "all"){

                    numberExpected = sendMsg(-1,DUMP,specification,BROADCAST);

                } else {

                    /*send to a specific VM to dump content*/
                    sendMsg(atoi(specification.c_str()),DUMP,specification);
                    numberExpected = 1;
                }

                /*handle the breakpoints in the lists*/
            } else if (instruction == REMOVE||instruction == BREAKPOINT) {

                /*extract the destination*/
                node = getNode(specification);
                if (node == ""){

                    /*broadcast the message if the node is not specified*/
                    numberExpected = sendMsg(-1,instruction,specification,BROADCAST);

                } else {

                    /*send break/remove to a specific node */
                    sendMsg(atoi(node.c_str()),instruction,specification);
                    numberExpected = 1;

                }

            } else if (instruction == PRINTLIST) {

                /*broadcast  a pause message*/
                numberExpected = sendMsg(-1,PRINTLIST,"",BROADCAST);

            } else if (instruction == MODE) {
                setFlags(specification);
                numberExpected = sendMsg(-1,MODE,specification,
                                         BROADCAST);
            }

    }

    /*the controller for the master MPI debugger-called when messages are
    *received*/
    void debugMasterController(int instruction, string specification){

        /*print the output and then tell all other VMs to pause*/
        if (instruction == BREAKFOUND){
            printf("%s",specification.c_str());
			/*print content from a VM*/
            if(okayToBroadcastPause) {
				sendMsg(-1,PAUSE,"",BROADCAST);
				okayToBroadcastPause = false;
                pauseSimulation();
            }
        } else if (instruction == PRINTCONTENT){
            printf("%s",specification.c_str());
        } else if (instruction == TERMINATE){
            printf("PROGRAM FINISHED\n");
            exit(0);
        } else if (instruction == PAUSE){

            /*prints more information*/
            if (verboseMode){
                printf("%s",specification.c_str());
            }

        }
    }

    /***************************************************************************/

    /*DEBUG MESSAGE SENDING*/

    /***************************************************************************/

    /*return the size of a packed array stored with content of an unkown size*/
    inline int getSize(string content){

        /*will always return an integer*/
        return  3 + ((content.size()+1) + (SIZE-(content.size()+1)%SIZE))/SIZE;
    }

    void messageQueueInsert(uint64_t* msg){
        messageQueue->push(msg);
    }

    /*given the type encoding and content, pack the information into
     *a sendable messeage*/
    message_type* pack(int msgEncode, string content){

        utils::byte* msg = (utils::byte*)new message_type[MAXLENGTH];
        int pos = 0;
        message_type debugFlag =  DEBUG;
        size_t size = content.length() +1;
        size_t bufSize = MAXLENGTH*SIZE;
        message_type msgSize = bufSize-SIZE;
        utils::byte anotherIndicator = 0;
        message_type timeStamp = 0;
        message_type nodeId = 0;

        utils::pack<message_type>(&msgSize,1,msg,bufSize,&pos);
        utils::pack<message_type>(&debugFlag,1,msg,bufSize,&pos);
        /*timestamp*/
        utils::pack<message_type>(&timeStamp,1,msg,bufSize,&pos);
        /*VM ID*/
        utils::pack<message_type>(&nodeId,1,msg,bufSize,&pos);
        /*indicate if another message is coming*/
        utils::pack<utils::byte>(&anotherIndicator,1,msg,bufSize,&pos);

        utils::pack<int>(&msgEncode,1,msg,bufSize,&pos);
        utils::pack<size_t>(&size,1,msg,bufSize,&pos);

        /*add the content into the buffer*/
        utils::pack<char>((char*)content.c_str(),content.size()+1,
                                 msg,bufSize,&pos);
        return (message_type*)msg;

    }

    /*the desination specified is the process*/
    /*send a debug message to another process through the MPI layer*/
    /*if send to all, specify BROADCAST (see top)*/
    int sendMsg(int destination, int msgType,
              string content, bool broadcast)  {

        /*pack the message*/
        message_type* msg = pack(msgType,content);

        size_t msgSize = MAXLENGTH*SIZE;

        if (broadcast){

            return debugSendMsg(-1,msg,msgSize);

        } else {

            /*get the process id (getVMId) and send the message*/
            return debugSendMsg(destination,msg,
                              msgSize);
        }

    }

    void receiveMsg(void){

        utils::byte *msg;
        int instruction;
        char specification[MAXLENGTH*SIZE];
        int pos = 0;
        message_type size;
        message_type debugFlag;
        size_t specSize;
         utils::byte anotherIndicator;
        message_type nodeId;
        message_type timeStamp;

		BlinkyBlocks::checkForReceivedVMMessages();

        while(!messageQueue->empty()){
            /*process each message until empty*/
            /*extract the message*/
            msg = (utils::byte*)messageQueue->front();

            /*unpack the message into readable form*/
            utils::unpack<message_type>(msg,MAXLENGTH*SIZE,&pos,&size,1);
            utils::unpack<message_type>(msg,MAXLENGTH*SIZE,&pos,&debugFlag,1);
            utils::unpack<message_type>(msg,MAXLENGTH*SIZE,&pos,&timeStamp,1);
            utils::unpack<message_type>(msg,MAXLENGTH*SIZE,&pos,&nodeId,1);
            utils::unpack<utils::byte>(msg,MAXLENGTH*SIZE,&pos,
                                        &anotherIndicator,1);
            utils::unpack<int>(msg,MAXLENGTH*SIZE,&pos,&instruction,1);
            utils::unpack<size_t>(msg,MAXLENGTH*SIZE,&pos,&specSize,1);
            utils::unpack<char>(msg,MAXLENGTH*SIZE,&pos,
                                &specification,specSize);
            string spec(specification);

            debugMasterController(instruction,spec);
            numberExpected--;

            /*set up the variables and buffers for next message*/
            memset(specification,0,MAXLENGTH*SIZE);
            messageQueue->pop();
            memset(msg,0,MAXLENGTH*SIZE);
            pos = 0;
        }
    }

}
<commit_msg>fixed syc error with set color<commit_after>#include <string.h>
#include <pthread.h>
#include <iostream>
#include <sstream>
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "debug_Simprompt.hpp"
#include "debug_Simhandler.hpp"
#include "serialization.hpp"
#include "types.hpp"
#include "blinkyBlocksVM.h"

using namespace std;
using namespace debugger;

namespace debugger {

#define SIZE (sizeof(message_type))
#define BROADCAST true

    /*****************************************************************/

    /*GLOBAL STORED VARS: debug handling specific*/

    /****************************************************************/

    std::queue<message_type*> *messageQueue;
    /*global variables to controll main thread*/
    static bool isSystemPaused = true;
    static bool isDebug = false;
    static bool isSimDebug = false;
    static bool isPausedAtBreakpoint = false;
	static bool okayToBroadcastPause = true;

    static bool okayToPauseSimulation = false;

    /*number of messages the Master expects to recieve*/
    int numberExpected = 0;

    bool verboseMode = false;
    bool serializationMode = false;

    /**********************************************************************/

    /* I/0 SPECIFICATION PARSING */

    /*********************************************************************/

    /*returns the index of a character in a string,
     *if it is not there it returns -1*/
    int characterInStringIndex(string str, char character){
        for(unsigned int i = 0; i < str.length(); i++){
            if (str[i] == character)
                return (int)i;
        }
        return -1;
    }

    /*extracts the type from the specification from input line
     *returns the type of breakpoint from the specification
     *invariant-- the type is always specified*/
    string getType(string specification){
        string build = "";
        for (unsigned int i = 0; i < specification.length(); i++){
            if(specification[i] == ':' || specification[i] == '@')
                return build;
            else
                build += specification[i];
        }
        return build;
    }

    /*extracts the name from the specification
     *returns the name from the specification
     *returns "" if name is not present*/
    string getName(string specification){
        string build = "";
        //find index of colon
        int index = characterInStringIndex(specification, ':');
        // if colon not there
        if (index == -1)
            return "";
        for (unsigned int i = index +1;
             i < specification.length(); i++){
            if (specification[i] == '@')
                return build;
            else
                build += specification[i];
        }
        return build;
    }

    /*extracts the node from the specification
     *returns the node from the specification
     *returns "" if node is not given*/
    string getNode(string specification){
        string build = "";
        int index = characterInStringIndex(specification, '@');
        if (index == -1)
            return "";
        for (unsigned int i = index+1; i < specification.length(); i++){
            build+=specification[i];
        }
        return build;
    }

    /*given the encoding return the corresponding string for
     *break point types*/
    string typeInt2String(int type){
        switch(type){
            case FACTDER:
                return "factDer";
            case FACTCON:
                return "factCon";
            case FACTRET:
                return "factRet";
            case ACTION:
                return "action";
            case SENSE:
                return "sense";
            case BLOCK:
                return "block";
        }
        return "";
    }

    /**********************************************************************/

    /*SIMULATION DEBUGGING FUNCTIONS*/

    /*********************************************************************/

   void setFlags(string specification){
        ostringstream msg;
        for (int i = 0; i < specification.length(); i++){
            if ((uint)specification[i] == 'V'){
                verboseMode = true;
            } else if ((uint)specification[i] == 'S'){
                serializationMode = true;
            }
        }
    }

    void debugController(int instruction, string specification){

        string type;
        string name;
        string node;

            if (instruction == CONTINUE || instruction == UNPAUSE){
				okayToBroadcastPause = true;
                okayToPauseSimulation = true;
                /*continue a paused system by broadcasting an CONTINUE signal*/
                unPauseSimulation();
                numberExpected = sendMsg(-1,CONTINUE,"",BROADCAST);
            } else if (instruction == RUN){
                okayToBroadcastPause = true;
                okayToPauseSimulation = true;
                /*continue a paused system by broadcasting an CONTINUE signal*/
                unPauseSimulation();
                numberExpected = sendMsg(-1,CONTINUE,"",BROADCAST);
            } else if (instruction == DUMP) {

                /*broadcast the message to all VMs*/
                if (specification == "all"){

                    numberExpected = sendMsg(-1,DUMP,specification,BROADCAST);

                } else {

                    /*send to a specific VM to dump content*/
                    sendMsg(atoi(specification.c_str()),DUMP,specification);
                    numberExpected = 1;
                }

                /*handle the breakpoints in the lists*/
            } else if (instruction == REMOVE||instruction == BREAKPOINT) {

                /*extract the destination*/
                node = getNode(specification);
                if (node == ""){

                    /*broadcast the message if the node is not specified*/
                    numberExpected = sendMsg(-1,instruction,specification,BROADCAST);

                } else {

                    /*send break/remove to a specific node */
                    sendMsg(atoi(node.c_str()),instruction,specification);
                    numberExpected = 1;

                }

            } else if (instruction == PRINTLIST) {

                /*broadcast  a pause message*/
                numberExpected = sendMsg(-1,PRINTLIST,"",BROADCAST);

            } else if (instruction == MODE) {
                setFlags(specification);
                numberExpected = sendMsg(-1,MODE,specification,
                                         BROADCAST);
            }

    }

    /*the controller for the master MPI debugger-called when messages are
    *received*/
    void debugMasterController(int instruction, string specification){

        /*print the output and then tell all other VMs to pause*/
        if (instruction == BREAKFOUND){
            printf("%s",specification.c_str());
			/*print content from a VM*/
            if(okayToBroadcastPause) {
				sendMsg(-1,PAUSE,"",BROADCAST);
				okayToBroadcastPause = false;
            }
        } else if (instruction == PRINTCONTENT){
            printf("%s",specification.c_str());
        } else if (instruction == TERMINATE){
            printf("PROGRAM FINISHED\n");
            exit(0);
        } else if (instruction == PAUSE){

            /*prints more information*/
            if (verboseMode){
                printf("%s",specification.c_str());
            }

        }
    }

    /***************************************************************************/

    /*DEBUG MESSAGE SENDING*/

    /***************************************************************************/

    /*return the size of a packed array stored with content of an unkown size*/
    inline int getSize(string content){

        /*will always return an integer*/
        return  3 + ((content.size()+1) + (SIZE-(content.size()+1)%SIZE))/SIZE;
    }

    void messageQueueInsert(uint64_t* msg){
        messageQueue->push(msg);
    }

    /*given the type encoding and content, pack the information into
     *a sendable messeage*/
    message_type* pack(int msgEncode, string content){

        utils::byte* msg = (utils::byte*)new message_type[MAXLENGTH];
        int pos = 0;
        message_type debugFlag =  DEBUG;
        size_t size = content.length() +1;
        size_t bufSize = MAXLENGTH*SIZE;
        message_type msgSize = bufSize-SIZE;
        utils::byte anotherIndicator = 0;
        message_type timeStamp = 0;
        message_type nodeId = 0;

        utils::pack<message_type>(&msgSize,1,msg,bufSize,&pos);
        utils::pack<message_type>(&debugFlag,1,msg,bufSize,&pos);
        /*timestamp*/
        utils::pack<message_type>(&timeStamp,1,msg,bufSize,&pos);
        /*VM ID*/
        utils::pack<message_type>(&nodeId,1,msg,bufSize,&pos);
        /*indicate if another message is coming*/
        utils::pack<utils::byte>(&anotherIndicator,1,msg,bufSize,&pos);

        utils::pack<int>(&msgEncode,1,msg,bufSize,&pos);
        utils::pack<size_t>(&size,1,msg,bufSize,&pos);

        /*add the content into the buffer*/
        utils::pack<char>((char*)content.c_str(),content.size()+1,
                                 msg,bufSize,&pos);
        return (message_type*)msg;

    }

    /*the desination specified is the process*/
    /*send a debug message to another process through the MPI layer*/
    /*if send to all, specify BROADCAST (see top)*/
    int sendMsg(int destination, int msgType,
              string content, bool broadcast)  {

        /*pack the message*/
        message_type* msg = pack(msgType,content);

        size_t msgSize = MAXLENGTH*SIZE;

        if (broadcast){

            return debugSendMsg(-1,msg,msgSize);

        } else {

            /*get the process id (getVMId) and send the message*/
            return debugSendMsg(destination,msg,
                              msgSize);
        }

    }

    void receiveMsg(void){

        utils::byte *msg;
        int instruction;
        char specification[MAXLENGTH*SIZE];
        int pos = 0;
        message_type size;
        message_type debugFlag;
        size_t specSize;
         utils::byte anotherIndicator;
        message_type nodeId;
        message_type timeStamp;

		BlinkyBlocks::checkForReceivedVMMessages();

        while(!messageQueue->empty()){
            /*process each message until empty*/
            /*extract the message*/
            msg = (utils::byte*)messageQueue->front();

            /*unpack the message into readable form*/
            utils::unpack<message_type>(msg,MAXLENGTH*SIZE,&pos,&size,1);
            utils::unpack<message_type>(msg,MAXLENGTH*SIZE,&pos,&debugFlag,1);
            utils::unpack<message_type>(msg,MAXLENGTH*SIZE,&pos,&timeStamp,1);
            utils::unpack<message_type>(msg,MAXLENGTH*SIZE,&pos,&nodeId,1);
            utils::unpack<utils::byte>(msg,MAXLENGTH*SIZE,&pos,
                                        &anotherIndicator,1);
            utils::unpack<int>(msg,MAXLENGTH*SIZE,&pos,&instruction,1);
            utils::unpack<size_t>(msg,MAXLENGTH*SIZE,&pos,&specSize,1);
            utils::unpack<char>(msg,MAXLENGTH*SIZE,&pos,
                                &specification,specSize);
            string spec(specification);

            debugMasterController(instruction,spec);
            numberExpected--;

            if (numberExpected == 0 && okayToPauseSimulation)
                pauseSimulation();

            /*set up the variables and buffers for next message*/
            memset(specification,0,MAXLENGTH*SIZE);
            messageQueue->pop();
            memset(msg,0,MAXLENGTH*SIZE);
            pos = 0;
        }
    }

}
<|endoftext|>


<commit_before>#include <iostream>
#include <vector>
#include <cmath>
#include <assert.h>
#include <atomic>
#include <algorithm>
#include <gtest/gtest.h>
#include "../algorithm.h"
#include "../parallel.h"
#include "../sequence.h"
#include "../async.h"
#include "../task.h"

class Parallel2Test : testing::Test { };

TEST(Parallel2Test, Test1)
{
	std::future<int> f1 = asyncply::_async([](int data){return data;}, 10);
	ASSERT_EQ(f1.get(), 10);
}

TEST(Parallel2Test, Test2)
{
	auto f1 = asyncply::async([](){return 15;});
	auto f2 = f1->then([](int data) {
		std::cout << "post, received: " << data << std::endl;
		return data + 6;
	});
	ASSERT_EQ(f2->get(), 15 + 6);
}

TEST(Parallel2Test, Test3)
{
	std::vector<int> a;
	for(int i=0; i<100; ++i)
	{
		a.push_back(1);
		a.push_back(4);
		a.push_back(12);
		a.push_back(-3);
		a.push_back(22);
	}
	std::atomic<int> total;
	total = 0;
	asyncply::for_each_sync(a.begin(), a.end(), [&total](int i) {
		total += i;
	});
	ASSERT_EQ(total, 3600);
}

TEST(Parallel2Test, Test3_async)
{
	std::vector<int> a;
	for(int i=0; i<100; ++i)
	{
		a.push_back(1);
		a.push_back(4);
		a.push_back(12);
		a.push_back(-3);
		a.push_back(22);
	}
	std::atomic<int> total;
	total = 0;
	asyncply::for_each(a.begin(), a.end(), [&total](int i) {
		total += i;
	});
	ASSERT_EQ(total, 3600);
}

TEST(Parallel2Test, Test4)
{
	double total_ps = asyncply::parallel_sync(
		[]()
		{
			return asyncply::sequence(1.0,
				[](double data)
				{
					return data + 1.0;
				},
				[](double data)
				{
					return data + 1.0;
				});
		},
		[]()
		{
			return asyncply::sequence(1.0,
				[](double data)
				{
					return data + 1.0;
				},
				[](double data)
				{
					return data + 1.0;
				});
		}
	);
	ASSERT_EQ(total_ps, 6);
}

TEST(Parallel2Test, Test5)
{
	std::atomic<int> total;
	total = 0;
	auto process = asyncply::parallel(
				[&total]()
				{
					std::cout << "hi" << std::endl;
					total += 1;
				},
				[&total]()
				{
					std::cout << "bye" << std::endl;
					total += 1;
				}
			);
	auto process2 = process->then([&total]()
			{
				std::cout << "no accum" << std::endl;
				total += 1;
			});
	process2->get();
	ASSERT_EQ(total, 3);
}

TEST(Parallel2Test, Test6)
{
	std::atomic<int> total;
	total = 0;
	{
		auto process = asyncply::parallel(
					[&total]()
					{
						std::cout << "hi" << std::endl;
						total += 1;
					},
					[&total]()
					{
						std::cout << "bye" << std::endl;
						total += 1;
					}
				);
		process->then([&total]()
				{
					std::cout << "no accum" << std::endl;
					total += 1;
				});
	}
	ASSERT_EQ(total, 3);
}
<commit_msg>Update test_parallel2.cpp<commit_after>#include <iostream>
#include <vector>
#include <cmath>
#include <assert.h>
#include <atomic>
#include <algorithm>
#include <gtest/gtest.h>
#include "../algorithm.h"
#include "../parallel.h"
#include "../sequence.h"
#include "../async.h"
#include "../task.h"

class Parallel2Test : testing::Test { };

TEST(Parallel2Test, Test1)
{
	std::future<int> f1 = asyncply::_async([](int data){return data;}, 10);
	ASSERT_EQ(f1.get(), 10);
}

TEST(Parallel2Test, Test2)
{
	auto f1 = asyncply::async([](){return 15;});
	auto f2 = f1->then([](int data) {
		std::cout << "post, received: " << data << std::endl;
		return data + 6;
	});
	ASSERT_EQ(f2->get(), 15 + 6);
}

TEST(Parallel2Test, Test3)
{
	std::vector<int> a;
	for(int i=0; i<100; ++i)
	{
		a.push_back(1);
		a.push_back(4);
		a.push_back(12);
		a.push_back(-3);
		a.push_back(22);
	}
	std::atomic<int> total;
	total = 0;
	asyncply::for_each_sync(a.begin(), a.end(), [&total](int i) {
		total += i;
	});
	ASSERT_EQ(total, 3600);
}

TEST(Parallel2Test, Test3_async)
{
	std::vector<int> a;
	for(int i=0; i<100; ++i)
	{
		a.push_back(1);
		a.push_back(4);
		a.push_back(12);
		a.push_back(-3);
		a.push_back(22);
	}
	std::atomic<int> total;
	total = 0;
	asyncply::for_each(a.begin(), a.end(), [&total](int i) {
		total += i;
	});
	ASSERT_EQ(total, 3600);
}

TEST(Parallel2Test, Test4)
{
	double total_ps = asyncply::parallel_sync(
		[]()
		{
			return asyncply::sequence(1.0,
				[](double data)
				{
					return data + 1.0;
				},
				[](double data)
				{
					return data + 1.0;
				});
		},
		[]()
		{
			return asyncply::sequence(1.0,
				[](double data)
				{
					return data + 1.0;
				},
				[](double data)
				{
					return data + 1.0;
				});
		}
	);
	ASSERT_EQ(total_ps, 6);
}

TEST(Parallel2Test, Test5)
{
	std::atomic<int> total;
	total = 0;
	auto process = asyncply::parallel(
				[&total]()
				{
					std::cout << "hi" << std::endl;
					total += 1;
				},
				[&total]()
				{
					std::cout << "bye" << std::endl;
					total += 1;
				}
			);
	auto process2 = process->then([&total]()
			{
				std::cout << "no accum" << std::endl;
				total += 1;
			});
	process2->get();
	ASSERT_EQ(total, 3);
}

TEST(Parallel2Test, Test6)
{
	std::atomic<int> total;
	total = 0;
	{
		auto process = asyncply::parallel(
					[&total]()
					{
						std::cout << "hi" << std::endl;
						total += 1;
					},
					[&total]()
					{
						std::cout << "bye" << std::endl;
						total += 1;
					}
				);
		auto process_then = process->then([&total]()
				{
					std::cout << "no accum" << std::endl;
					total += 1;
				});
	}
	ASSERT_EQ(total, 3);
}
<|endoftext|>


<commit_before>#include <iostream>
#include <vector>
#include <cmath>
#include <assert.h>
#include <atomic>
#include <algorithm>
#include "../algorithm.h"
#include "../parallel.h"
#include "../sequence.h"
#include "../async.h"
#include "../task.h"

int main(int, const char**)
{
	std::future<int> f = asyncply::_async([](){return 10;});
	std::cout << "f = " << f.get() << std::endl;

	auto f2 = asyncply::async([](){return 15;});
	f2->then([](int data){ std::cout << "post, received: " << data << std::endl; return 0; });
	std::cout << "f2 = " << f2->get() << std::endl;

	std::vector<int> a;
	for(int i=0; i<100; ++i)
	{
		a.push_back(1);
		a.push_back(4);
		a.push_back(12);
		a.push_back(-3);
		a.push_back(22);
	}
	std::atomic<int> total;
	total = 0;
	asyncply::for_each_sync(a.begin(), a.end(), [&total](int i) {
		total += i;
		// std::cout << "thread " << std::this_thread::get_id() << std::endl;
	});
	std::cout << "total = " << total << std::endl;

	{
		auto total_ps = asyncply::parallel_sync(
					[]()
					{
						return asyncply::sequence(1.0,
							[](double data)
							{
								return data + 1.0;
							},
							[](double data)
							{
								return data + 1.0;
							});
					},
					[]()
					{
						return asyncply::sequence(1.0,
							[](double data)
							{
								return data + 1.0;
							},
							[](double data)
							{
								return data + 1.0;
							});
					}
				);
		std::cout << "process1 = " << total_ps << std::endl;
		if (std::abs(6.0 - total_ps) > 1e-3)
		{
			std::cout << "invalid total " << total_ps << std::endl;
			return 1;
		}
	}

	{
		auto process2 = asyncply::parallel(
					[]()
					{
						std::cout << "hi" << std::endl;
					},
					[]()
					{
						std::cout << "bye" << std::endl;
					}
				);
		process2->then([]()
				{
					std::cout << "no accum" << std::endl;
				});
	}

	return 0;
}

<commit_msg>Update test_parallel2.cpp<commit_after>#include <iostream>
#include <vector>
#include <cmath>
#include <assert.h>
#include <atomic>
#include <algorithm>
#include "../algorithm.h"
#include "../parallel.h"
#include "../sequence.h"
#include "../async.h"
#include "../task.h"
#include <gtest/gtest.h>

class Parallel2Test : testing::Test { };

TEST(Parallel2Test, Test1)
{
	std::future<int> f = asyncply::_async([](){return 10;});
	ASSERT_EQ(f.get(), 10);
}

TEST(Parallel2Test, Test2)
{
	auto f2 = asyncply::async([](){return 15;});
	f2->then([](int data){ std::cout << "post, received: " << data << std::endl; return 6; });
	// 6 or 15 ?
	ASSERT_EQ(f2->get(), 6);
}

TEST(Parallel2Test, Test3)
{
	std::vector<int> a;
	for(int i=0; i<100; ++i)
	{
		a.push_back(1);
		a.push_back(4);
		a.push_back(12);
		a.push_back(-3);
		a.push_back(22);
	}
	std::atomic<int> total;
	total = 0;
	asyncply::for_each_sync(a.begin(), a.end(), [&total](int i) {
		total += i;
		// std::cout << "thread " << std::this_thread::get_id() << std::endl;
	});
	ASSERT_EQ(total, 3600);
}

TEST(Parallel2Test, Test4)
{
	auto total_ps = asyncply::parallel_sync(
				[]()
				{
					return asyncply::sequence(1.0,
						[](double data)
						{
							return data + 1.0;
						},
						[](double data)
						{
							return data + 1.0;
						});
				},
				[]()
				{
					return asyncply::sequence(1.0,
						[](double data)
						{
							return data + 1.0;
						},
						[](double data)
						{
							return data + 1.0;
						});
				}
			);
	ASSERT_EQ(total_ps, 6);
}

TEST(Parallel2Test, Test5)
{
	std::atomic<int> total;
	total = 0;
	auto process2 = asyncply::parallel(
				[]()
				{
					std::cout << "hi" << std::endl;
					total += 1;
				},
				[]()
				{
					std::cout << "bye" << std::endl;
					total += 1;
				}
			);
	process2->then([]()
			{
				std::cout << "no accum" << std::endl;
				total += 1;
			});
	ASSERT_EQ(total, 3);
}
<|endoftext|>


<commit_before>#include <gtest/gtest.h>

#include "Vaca/SharedPtr.h"
#include "Vaca/Referenceable.h"

using namespace Vaca;

class Int : public Referenceable
{
public:
  int value_;
  Int(int value) : value_(value) { }
};

TEST(SharedPtr, Equal)
{
  SharedPtr<Int> a(new Int(5));
  SharedPtr<Int> b;
  EXPECT_EQ(5, a->value_);
  EXPECT_TRUE(a != b);
  b = a;
  EXPECT_TRUE(a == b);
  EXPECT_TRUE(&a->value_ == &b->value_); // Same address
}
<commit_msg>Minor modifications in test for SharedPtr class.<commit_after>#include <gtest/gtest.h>

#include "Vaca/SharedPtr.h"
#include "Vaca/Referenceable.h"

using namespace Vaca;

class Int : public Referenceable
{
public:
  int value_;
  Int(int value) : value_(value) { }
};

TEST(SharedPtr, Equal)
{
  SharedPtr<Int> a(new Int(5));
  SharedPtr<Int> b(new Int(0));
  SharedPtr<Int> c;

  EXPECT_EQ(5, a->value_);
  EXPECT_EQ(0, b->value_);

  b->value_ = a->value_;	// Same values

  EXPECT_TRUE(a != b);		// References are different
  EXPECT_TRUE(b != c);

  b = a;			// Same reference

  EXPECT_TRUE(a == b);
  EXPECT_TRUE(b != c);
  EXPECT_TRUE(&a->value_ == &b->value_); // Same address
}
<|endoftext|>


<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "ppapi/tests/test_url_loader.h"

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

#include "ppapi/c/pp_errors.h"
#include "ppapi/c/ppb_testing.h"
#include "ppapi/c/ppb_url_loader.h"
#include "ppapi/cpp/completion_callback.h"
#include "ppapi/cpp/url_loader.h"
#include "ppapi/cpp/url_request_info.h"
#include "ppapi/cpp/instance.h"
#include "ppapi/cpp/module.h"
#include "ppapi/tests/test_instance.h"

REGISTER_TEST_CASE(URLLoader);

namespace {

const PPB_Testing* g_testing_interface;

class TestCompletionCallback {
 public:
  TestCompletionCallback() : result_(PP_ERROR_WOULDBLOCK) {
  }

  operator pp::CompletionCallback() const {
    return pp::CompletionCallback(&TestCompletionCallback::Handler,
                                  const_cast<TestCompletionCallback*>(this));
  }

  int32_t WaitForResult() {
    result_ = PP_ERROR_WOULDBLOCK;  // Reset
    g_testing_interface->RunMessageLoop();
    return result_;
  }

 private:
  static void Handler(void* user_data, int32_t result) {
    static_cast<TestCompletionCallback*>(user_data)->result_ = result;
    g_testing_interface->QuitMessageLoop();
  }

  int32_t result_;
};

std::string ReportError(const char* method, int32_t error) {
  char error_as_string[12];
  sprintf(error_as_string, "%d", error);
  return method + std::string(" failed with error: ") + error_as_string;
}

}  // namespace

bool TestURLLoader::Init() {
  g_testing_interface = reinterpret_cast<PPB_Testing const*>(
      pp::Module::Get()->GetBrowserInterface(PPB_TESTING_INTERFACE));
  if (!g_testing_interface) {
    // Give a more helpful error message for the testing interface being gone
    // since that needs special enabling in Chrome.
    instance_->AppendError("This test needs the testing interface, which is "
        "not currently available. In Chrome, use --enable-pepper-testing when "
        "launching.");
  }
  return !!g_testing_interface;
}

void TestURLLoader::RunTest() {
  RUN_TEST(BasicGET);
  RUN_TEST(BasicPOST);
  RUN_TEST(CompoundBodyPOST);
  RUN_TEST(CustomRequestHeader);
  RUN_TEST(IgnoresBogusContentLength);
}

std::string TestURLLoader::ReadEntireResponseBody(pp::URLLoader* loader,
                                                  std::string* body) {
  TestCompletionCallback callback;
  char buf[256];

  for (;;) {
    int32_t rv = loader->ReadResponseBody(buf, sizeof(buf), callback);
    if (rv == PP_ERROR_WOULDBLOCK)
      rv = callback.WaitForResult();
    if (rv < 0)
      return ReportError("URLLoader::ReadResponseBody", rv);
    if (rv == 0)
      break;
    body->append(buf, rv);
  }

  return "";
}

std::string TestURLLoader::LoadAndCompareBody(
    const pp::URLRequestInfo& request,
    const std::string& expected_body) {
  TestCompletionCallback callback;

  pp::URLLoader loader(*instance_);
  int32_t rv = loader.Open(request, callback);
  if (rv == PP_ERROR_WOULDBLOCK)
    rv = callback.WaitForResult();
  if (rv != PP_OK)
    return ReportError("URLLoader::Open", rv);

  std::string body;
  std::string error = ReadEntireResponseBody(&loader, &body);
  if (!error.empty())
    return error;

  if (body.size() != expected_body.size())
    return "URLLoader::ReadResponseBody returned unexpected content length";
  if (body != expected_body)
    return "URLLoader::ReadResponseBody returned unexpected content";

  return "";
}

std::string TestURLLoader::TestBasicGET() {
  pp::URLRequestInfo request;
  request.SetURL("test_url_loader_data/hello.txt");
  return LoadAndCompareBody(request, "hello\n");
}

std::string TestURLLoader::TestBasicPOST() {
  pp::URLRequestInfo request;
  request.SetURL("/echo");
  request.SetMethod("POST");
  request.AppendDataToBody("postdata");
  return LoadAndCompareBody(request, "postdata");
}

std::string TestURLLoader::TestCompoundBodyPOST() {
  pp::URLRequestInfo request;
  request.SetURL("/echo");
  request.SetMethod("POST");
  request.AppendDataToBody("post");
  request.AppendDataToBody("data");
  return LoadAndCompareBody(request, "postdata");
}

std::string TestURLLoader::TestCustomRequestHeader() {
  pp::URLRequestInfo request;
  request.SetURL("/echoheader?Foo");
  request.SetHeaders("Foo: 1");
  return LoadAndCompareBody(request, "1");
}

std::string TestURLLoader::TestIgnoresBogusContentLength() {
  pp::URLRequestInfo request;
  request.SetURL("/echo");
  request.SetMethod("POST");
  request.SetHeaders("Content-Length: 400");
  request.AppendDataToBody("postdata");
  return LoadAndCompareBody(request, "postdata");
}
<commit_msg>Verify that the URLLoader tests are run over HTTP, and check that we get a 200 response.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "ppapi/tests/test_url_loader.h"

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

#include "ppapi/c/pp_errors.h"
#include "ppapi/c/ppb_testing.h"
#include "ppapi/c/ppb_url_loader.h"
#include "ppapi/cpp/completion_callback.h"
#include "ppapi/cpp/url_loader.h"
#include "ppapi/cpp/url_request_info.h"
#include "ppapi/cpp/url_response_info.h"
#include "ppapi/cpp/instance.h"
#include "ppapi/cpp/module.h"
#include "ppapi/tests/test_instance.h"

REGISTER_TEST_CASE(URLLoader);

namespace {

const PPB_Testing* g_testing_interface;

class TestCompletionCallback {
 public:
  TestCompletionCallback() : result_(PP_ERROR_WOULDBLOCK) {
  }

  operator pp::CompletionCallback() const {
    return pp::CompletionCallback(&TestCompletionCallback::Handler,
                                  const_cast<TestCompletionCallback*>(this));
  }

  int32_t WaitForResult() {
    result_ = PP_ERROR_WOULDBLOCK;  // Reset
    g_testing_interface->RunMessageLoop();
    return result_;
  }

 private:
  static void Handler(void* user_data, int32_t result) {
    static_cast<TestCompletionCallback*>(user_data)->result_ = result;
    g_testing_interface->QuitMessageLoop();
  }

  int32_t result_;
};

std::string ReportError(const char* method, int32_t error) {
  char error_as_string[12];
  sprintf(error_as_string, "%d", error);
  return method + std::string(" failed with error: ") + error_as_string;
}

}  // namespace

bool TestURLLoader::Init() {
  g_testing_interface = reinterpret_cast<PPB_Testing const*>(
      pp::Module::Get()->GetBrowserInterface(PPB_TESTING_INTERFACE));
  if (!g_testing_interface) {
    // Give a more helpful error message for the testing interface being gone
    // since that needs special enabling in Chrome.
    instance_->AppendError("This test needs the testing interface, which is "
        "not currently available. In Chrome, use --enable-pepper-testing when "
        "launching.");
    return false;
  }

  // Make sure we're running over HTTP.
  pp::Var window = instance_->GetWindowObject();
  pp::Var location = window.GetProperty("location");
  pp::Var protocol = location.GetProperty("protocol");
  if (!protocol.is_string() || protocol.AsString() != "http:") {
    instance_->AppendError("This test needs to be run over HTTP.");
    return false;
  }

  return true;
}

void TestURLLoader::RunTest() {

  RUN_TEST(BasicGET);
  RUN_TEST(BasicPOST);
  RUN_TEST(CompoundBodyPOST);
  RUN_TEST(CustomRequestHeader);
  RUN_TEST(IgnoresBogusContentLength);
}

std::string TestURLLoader::ReadEntireResponseBody(pp::URLLoader* loader,
                                                  std::string* body) {
  TestCompletionCallback callback;
  char buf[256];

  for (;;) {
    int32_t rv = loader->ReadResponseBody(buf, sizeof(buf), callback);
    if (rv == PP_ERROR_WOULDBLOCK)
      rv = callback.WaitForResult();
    if (rv < 0)
      return ReportError("URLLoader::ReadResponseBody", rv);
    if (rv == 0)
      break;
    body->append(buf, rv);
  }

  return "";
}

std::string TestURLLoader::LoadAndCompareBody(
    const pp::URLRequestInfo& request,
    const std::string& expected_body) {
  TestCompletionCallback callback;

  pp::URLLoader loader(*instance_);
  int32_t rv = loader.Open(request, callback);
  if (rv == PP_ERROR_WOULDBLOCK)
    rv = callback.WaitForResult();
  if (rv != PP_OK)
    return ReportError("URLLoader::Open", rv);

  pp::URLResponseInfo response_info(loader.GetResponseInfo());
  if (response_info.is_null())
    return "URLLoader::GetResponseInfo returned null";
  int32_t status_code = response_info.GetStatusCode();
  if (status_code != 200)
    return "Unexpected HTTP status code";

  std::string body;
  std::string error = ReadEntireResponseBody(&loader, &body);
  if (!error.empty())
    return error;

  if (body.size() != expected_body.size())
    return "URLLoader::ReadResponseBody returned unexpected content length";
  if (body != expected_body)
    return "URLLoader::ReadResponseBody returned unexpected content";

  return "";
}

std::string TestURLLoader::TestBasicGET() {
  pp::URLRequestInfo request;
  request.SetURL("test_url_loader_data/hello.txt");
  return LoadAndCompareBody(request, "hello\n");
}

std::string TestURLLoader::TestBasicPOST() {
  pp::URLRequestInfo request;
  request.SetURL("/echo");
  request.SetMethod("POST");
  request.AppendDataToBody("postdata");
  return LoadAndCompareBody(request, "postdata");
}

std::string TestURLLoader::TestCompoundBodyPOST() {
  pp::URLRequestInfo request;
  request.SetURL("/echo");
  request.SetMethod("POST");
  request.AppendDataToBody("post");
  request.AppendDataToBody("data");
  return LoadAndCompareBody(request, "postdata");
}

std::string TestURLLoader::TestCustomRequestHeader() {
  pp::URLRequestInfo request;
  request.SetURL("/echoheader?Foo");
  request.SetHeaders("Foo: 1");
  return LoadAndCompareBody(request, "1");
}

std::string TestURLLoader::TestIgnoresBogusContentLength() {
  pp::URLRequestInfo request;
  request.SetURL("/echo");
  request.SetMethod("POST");
  request.SetHeaders("Content-Length: 400");
  request.AppendDataToBody("postdata");
  return LoadAndCompareBody(request, "postdata");
}
<|endoftext|>


<commit_before>(| 4 typed integer |)
#FIXME example is too simple
<commit_msg>improved the test;<commit_after>fun F : () -> ()
  4 typed integer
  [] typed list string
  [] typed [integer]
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2011 Collabora Ltd. <http://www.collabora.co.uk/>
 *   @author Andre Moreira Magalhaes <andre.magalhaes@collabora.co.uk>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "tls-cert-verifier-op.h"

#include <TelepathyQt4/PendingVariantMap>

#include <KDebug>

TlsCertVerifierOp::TlsCertVerifierOp(const Tp::AccountPtr &account,
        const Tp::ConnectionPtr &connection,
        const Tp::ChannelPtr &channel)
    : Tp::PendingOperation(channel),
      m_account(account),
      m_connection(connection),
      m_channel(channel)
{
    QString certificatePath = qdbus_cast<QString>(channel->immutableProperties().value(
                TP_QT4_IFACE_CHANNEL_TYPE_SERVER_TLS_CONNECTION + ".ServerCertificate"));
    m_hostname = qdbus_cast<QString>(channel->immutableProperties().value(
                TP_QT4_IFACE_CHANNEL_TYPE_SERVER_TLS_CONNECTION + ".Hostname"));
    m_referenceIdentities = qdbus_cast<QStringList>(channel->immutableProperties().value(
                TP_QT4_IFACE_CHANNEL_TYPE_SERVER_TLS_CONNECTION + ".ReferenceIdentities"));

    m_authTLSCertificateIface = new Tp::Client::AuthenticationTLSCertificateInterface(
            channel->dbusConnection(), channel->busName(), certificatePath);
    connect(m_authTLSCertificateIface->requestAllProperties(),
            SIGNAL(finished(Tp::PendingOperation*)),
            SLOT(gotProperties(Tp::PendingOperation*)));
}

TlsCertVerifierOp::~TlsCertVerifierOp()
{
}

void TlsCertVerifierOp::gotProperties(Tp::PendingOperation *op)
{
    if (op->isError()) {
        kWarning() << "Unable to retrieve properties from AuthenticationTLSCertificate object at" <<
            m_authTLSCertificateIface->path();
        setFinishedWithError(op->errorName(), op->errorMessage());
        return;
    }

    // everything ok, we can return from handleChannels now
    emit ready(this);

    Tp::PendingVariantMap *pvm = qobject_cast<Tp::PendingVariantMap*>(op);
    QVariantMap props = qdbus_cast<QVariantMap>(pvm->result());
    m_certType = qdbus_cast<QString>(props.value("CertificateType"));
    m_certData = qdbus_cast<CertificateDataList>(props.value("certificateChainData"));

    // FIXME: verify cert
    setFinished();
}

#include "tls-cert-verifier-op.moc"
<commit_msg>Close TLS channel on error<commit_after>/*
 * Copyright (C) 2011 Collabora Ltd. <http://www.collabora.co.uk/>
 *   @author Andre Moreira Magalhaes <andre.magalhaes@collabora.co.uk>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "tls-cert-verifier-op.h"

#include <TelepathyQt4/PendingVariantMap>

#include <KDebug>

TlsCertVerifierOp::TlsCertVerifierOp(const Tp::AccountPtr &account,
        const Tp::ConnectionPtr &connection,
        const Tp::ChannelPtr &channel)
    : Tp::PendingOperation(channel),
      m_account(account),
      m_connection(connection),
      m_channel(channel)
{
    QString certificatePath = qdbus_cast<QString>(channel->immutableProperties().value(
                TP_QT4_IFACE_CHANNEL_TYPE_SERVER_TLS_CONNECTION + ".ServerCertificate"));
    m_hostname = qdbus_cast<QString>(channel->immutableProperties().value(
                TP_QT4_IFACE_CHANNEL_TYPE_SERVER_TLS_CONNECTION + ".Hostname"));
    m_referenceIdentities = qdbus_cast<QStringList>(channel->immutableProperties().value(
                TP_QT4_IFACE_CHANNEL_TYPE_SERVER_TLS_CONNECTION + ".ReferenceIdentities"));

    m_authTLSCertificateIface = new Tp::Client::AuthenticationTLSCertificateInterface(
            channel->dbusConnection(), channel->busName(), certificatePath);
    connect(m_authTLSCertificateIface->requestAllProperties(),
            SIGNAL(finished(Tp::PendingOperation*)),
            SLOT(gotProperties(Tp::PendingOperation*)));
}

TlsCertVerifierOp::~TlsCertVerifierOp()
{
}

void TlsCertVerifierOp::gotProperties(Tp::PendingOperation *op)
{
    if (op->isError()) {
        kWarning() << "Unable to retrieve properties from AuthenticationTLSCertificate object at" <<
            m_authTLSCertificateIface->path();
        m_channel->requestClose();
        setFinishedWithError(op->errorName(), op->errorMessage());
        return;
    }

    // everything ok, we can return from handleChannels now
    emit ready(this);

    Tp::PendingVariantMap *pvm = qobject_cast<Tp::PendingVariantMap*>(op);
    QVariantMap props = qdbus_cast<QVariantMap>(pvm->result());
    m_certType = qdbus_cast<QString>(props.value("CertificateType"));
    m_certData = qdbus_cast<CertificateDataList>(props.value("certificateChainData"));

    // FIXME: verify cert
    setFinished();
}

#include "tls-cert-verifier-op.moc"
<|endoftext|>


<commit_before>/******************************************************************************
  This source file is part of the tomviz project.

  Copyright Kitware, Inc.

  This source code is released under the New BSD License, (the "License").

  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.

******************************************************************************/
#include "ModuleOutline.h"

#include "DataSource.h"
#include "Utilities.h"
#include "pqProxiesWidget.h"
#include "vtkNew.h"
#include "vtkSMParaViewPipelineControllerWithRendering.h"
#include "vtkSMProperty.h"
#include "vtkSMPropertyHelper.h"
#include "vtkSMSessionProxyManager.h"
#include "vtkSMSourceProxy.h"
#include "vtkSMViewProxy.h"
#include "vtkSmartPointer.h"
#include <pqColorChooserButton.h>
#include <vtkGridAxes3DActor.h>
#include <vtkPVRenderView.h>
#include <vtkRenderer.h>

#include <QCheckBox>
#include <QHBoxLayout>
#include <QLabel>
#include <QVBoxLayout>

namespace tomviz {

using pugi::xml_attribute;
using pugi::xml_node;

ModuleOutline::ModuleOutline(QObject* parentObject) : Superclass(parentObject)
{
}

ModuleOutline::~ModuleOutline()
{
  this->finalize();
}

QIcon ModuleOutline::icon() const
{
  return QIcon(":/icons/pqProbeLocation.png");
}

bool ModuleOutline::initialize(DataSource* data, vtkSMViewProxy* vtkView)
{
  if (!this->Superclass::initialize(data, vtkView)) {
    return false;
  }

  vtkNew<vtkSMParaViewPipelineControllerWithRendering> controller;

  vtkSMSessionProxyManager* pxm = data->producer()->GetSessionProxyManager();

  // Create the outline filter.
  vtkSmartPointer<vtkSMProxy> proxy;
  proxy.TakeReference(pxm->NewProxy("filters", "OutlineFilter"));

  this->OutlineFilter = vtkSMSourceProxy::SafeDownCast(proxy);
  Q_ASSERT(this->OutlineFilter);
  controller->PreInitializeProxy(this->OutlineFilter);
  vtkSMPropertyHelper(this->OutlineFilter, "Input").Set(data->producer());
  controller->PostInitializeProxy(this->OutlineFilter);
  controller->RegisterPipelineProxy(this->OutlineFilter);

  // Create the representation for it.
  this->OutlineRepresentation =
    controller->Show(this->OutlineFilter, 0, vtkView);
  vtkSMPropertyHelper(this->OutlineRepresentation, "Position")
    .Set(data->displayPosition(), 3);
  vtkSMPropertyHelper(this->OutlineRepresentation, "DiffuseColor")
    .Set(offWhite, 3);
  Q_ASSERT(this->OutlineRepresentation);
  // vtkSMPropertyHelper(this->OutlineRepresentation,
  //                    "Representation").Set("Outline");
  this->OutlineRepresentation->UpdateVTKObjects();

  // Give the proxy a friendly name for the GUI/Python world.
  if (auto p = convert<pqProxy*>(proxy)) {
    p->rename(label());
  }

  // Init the grid axes
  initializeGridAxes(data, vtkView);

  return true;
}

bool ModuleOutline::finalize()
{
  vtkNew<vtkSMParaViewPipelineControllerWithRendering> controller;
  controller->UnRegisterProxy(this->OutlineRepresentation);
  controller->UnRegisterProxy(this->OutlineFilter);

  if (m_view) {
    m_view->GetRenderer()->RemoveActor(m_gridAxes.Get());
  }

  this->OutlineFilter = nullptr;
  this->OutlineRepresentation = nullptr;
  return true;
}

bool ModuleOutline::serialize(pugi::xml_node& ns) const
{
  xml_node rootNode = ns.append_child("properties");

  xml_node visibilityNode = rootNode.append_child("visibility");
  visibilityNode.append_attribute("enabled") = visibility();

  xml_node gridAxesNode = rootNode.append_child("grid_axes");
  gridAxesNode.append_attribute("enabled") = m_gridAxes->GetVisibility() > 0;

  return true;
}

bool ModuleOutline::deserialize(const pugi::xml_node& ns)
{
  xml_node rootNode = ns.child("properties");
  if (!rootNode) {
    return false;
  }

  xml_node node = rootNode.child("visibility");
  if (node) {
    xml_attribute att = node.attribute("enabled");
    if (att) {
      setVisibility(att.as_bool());
    }
  }

  node = rootNode.child("grid_axes");
  if (node) {
    xml_attribute att = node.attribute("enabled");
    if (att) {
      m_gridAxes->SetVisibility(att.as_bool() ? 1 : 0);
    }
  }

  return Module::deserialize(ns);
}

bool ModuleOutline::setVisibility(bool val)
{
  Q_ASSERT(this->OutlineRepresentation);
  vtkSMPropertyHelper(this->OutlineRepresentation, "Visibility")
    .Set(val ? 1 : 0);
  this->OutlineRepresentation->UpdateVTKObjects();
  m_gridAxes->SetVisibility(val ? 1 : 0);
  return true;
}

bool ModuleOutline::visibility() const
{
  if (this->OutlineRepresentation) {
    return vtkSMPropertyHelper(this->OutlineRepresentation, "Visibility")
             .GetAsInt() != 0;
  } else {
    return false;
  }
}

void ModuleOutline::addToPanel(QWidget* panel)
{
  Q_ASSERT(panel && this->OutlineRepresentation);

  if (panel->layout()) {
    delete panel->layout();
  }

  QHBoxLayout* layout = new QHBoxLayout;
  QLabel* label = new QLabel("Color");
  layout->addWidget(label);
  layout->addStretch();
  pqColorChooserButton* colorSelector = new pqColorChooserButton(panel);
  colorSelector->setShowAlphaChannel(false);
  layout->addWidget(colorSelector);

  QHBoxLayout* gridAxesLayout = new QHBoxLayout;
  QCheckBox* showAxesGrid = new QCheckBox(QString("Show Axes Grid"));
  showAxesGrid->setChecked(m_gridAxes->GetVisibility() == 1);

  connect(showAxesGrid, &QCheckBox::stateChanged, this, [this](int state) {
    this->m_gridAxes->SetVisibility(state == Qt::Checked);
    emit this->renderNeeded();
  });

  gridAxesLayout->addWidget(showAxesGrid);

  QVBoxLayout* panelLayout = new QVBoxLayout;
  panelLayout->addItem(layout);
  panelLayout->addItem(gridAxesLayout);
  panelLayout->addStretch();
  panel->setLayout(panelLayout);

  m_links.addPropertyLink(
    colorSelector, "chosenColorRgbF", SIGNAL(chosenColorChanged(const QColor&)),
    this->OutlineRepresentation,
    this->OutlineRepresentation->GetProperty("DiffuseColor"));

  this->connect(colorSelector, &pqColorChooserButton::chosenColorChanged, this,
                &ModuleOutline::dataUpdated);
}

void ModuleOutline::dataUpdated()
{
  m_links.accept();
  emit this->renderNeeded();
}

void ModuleOutline::dataSourceMoved(double newX, double newY, double newZ)
{
  double pos[3] = { newX, newY, newZ };
  vtkSMPropertyHelper(this->OutlineRepresentation, "Position").Set(pos, 3);
  this->OutlineRepresentation->UpdateVTKObjects();
}

//-----------------------------------------------------------------------------
bool ModuleOutline::isProxyPartOfModule(vtkSMProxy* proxy)
{
  return (proxy == this->OutlineFilter.Get()) ||
         (proxy == this->OutlineRepresentation.Get());
}

std::string ModuleOutline::getStringForProxy(vtkSMProxy* proxy)
{
  if (proxy == this->OutlineFilter.Get()) {
    return "Outline";
  } else if (proxy == this->OutlineRepresentation.Get()) {
    return "Representation";
  } else {
    qWarning("Unknown proxy passed to module outline in save animation");
    return "";
  }
}

vtkSMProxy* ModuleOutline::getProxyForString(const std::string& str)
{
  if (str == "Outline") {
    return this->OutlineFilter.Get();
  } else if (str == "Representation") {
    return this->OutlineRepresentation.Get();
  } else {
    return nullptr;
  }
}

void ModuleOutline::updateGridAxesBounds(DataSource* dataSource)
{
  Q_ASSERT(dataSource);
  double bounds[6];
  dataSource->getBounds(bounds);
  m_gridAxes->SetGridBounds(bounds);
}
void ModuleOutline::initializeGridAxes(DataSource* data,
                                       vtkSMViewProxy* vtkView)
{

  updateGridAxesBounds(data);
  m_gridAxes->SetVisibility(0);

  // Set the titles
  QString xTitle = QString("X (%1)").arg(data->getUnits(0));
  QString yTitle = QString("Y (%1)").arg(data->getUnits(1));
  QString zTitle = QString("Z (%1)").arg(data->getUnits(2));
  m_gridAxes->SetXTitle(xTitle.toUtf8().data());
  m_gridAxes->SetYTitle(yTitle.toUtf8().data());
  m_gridAxes->SetZTitle(zTitle.toUtf8().data());

  m_view = vtkPVRenderView::SafeDownCast(vtkView->GetClientSideView());
  m_view->GetRenderer()->AddActor(m_gridAxes.Get());

  connect(data, &DataSource::dataPropertiesChanged, this, [this]() {
    auto dataSource = qobject_cast<DataSource*>(sender());
    this->updateGridAxesBounds(dataSource);
    dataSource->producer()->MarkModified(nullptr);
    dataSource->producer()->UpdatePipeline();
    emit this->renderNeeded();

  });
}

} // end of namespace tomviz
<commit_msg>Update grid color when its changed<commit_after>/******************************************************************************
  This source file is part of the tomviz project.

  Copyright Kitware, Inc.

  This source code is released under the New BSD License, (the "License").

  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.

******************************************************************************/
#include "ModuleOutline.h"

#include "DataSource.h"
#include "Utilities.h"
#include "pqProxiesWidget.h"
#include "vtkNew.h"
#include "vtkSMParaViewPipelineControllerWithRendering.h"
#include "vtkSMProperty.h"
#include "vtkSMPropertyHelper.h"
#include "vtkSMSessionProxyManager.h"
#include "vtkSMSourceProxy.h"
#include "vtkSMViewProxy.h"
#include "vtkSmartPointer.h"
#include <pqColorChooserButton.h>
#include <vtkGridAxes3DActor.h>
#include <vtkPVRenderView.h>
#include <vtkRenderer.h>
#include <vtkProperty.h>

#include <QCheckBox>
#include <QHBoxLayout>
#include <QLabel>
#include <QVBoxLayout>

namespace tomviz {

using pugi::xml_attribute;
using pugi::xml_node;

ModuleOutline::ModuleOutline(QObject* parentObject) : Superclass(parentObject)
{
}

ModuleOutline::~ModuleOutline()
{
  this->finalize();
}

QIcon ModuleOutline::icon() const
{
  return QIcon(":/icons/pqProbeLocation.png");
}

bool ModuleOutline::initialize(DataSource* data, vtkSMViewProxy* vtkView)
{
  if (!this->Superclass::initialize(data, vtkView)) {
    return false;
  }

  vtkNew<vtkSMParaViewPipelineControllerWithRendering> controller;

  vtkSMSessionProxyManager* pxm = data->producer()->GetSessionProxyManager();

  // Create the outline filter.
  vtkSmartPointer<vtkSMProxy> proxy;
  proxy.TakeReference(pxm->NewProxy("filters", "OutlineFilter"));

  this->OutlineFilter = vtkSMSourceProxy::SafeDownCast(proxy);
  Q_ASSERT(this->OutlineFilter);
  controller->PreInitializeProxy(this->OutlineFilter);
  vtkSMPropertyHelper(this->OutlineFilter, "Input").Set(data->producer());
  controller->PostInitializeProxy(this->OutlineFilter);
  controller->RegisterPipelineProxy(this->OutlineFilter);

  // Create the representation for it.
  this->OutlineRepresentation =
    controller->Show(this->OutlineFilter, 0, vtkView);
  vtkSMPropertyHelper(this->OutlineRepresentation, "Position")
    .Set(data->displayPosition(), 3);
  vtkSMPropertyHelper(this->OutlineRepresentation, "DiffuseColor")
    .Set(offWhite, 3);
  Q_ASSERT(this->OutlineRepresentation);
  // vtkSMPropertyHelper(this->OutlineRepresentation,
  //                    "Representation").Set("Outline");
  this->OutlineRepresentation->UpdateVTKObjects();

  // Give the proxy a friendly name for the GUI/Python world.
  if (auto p = convert<pqProxy*>(proxy)) {
    p->rename(label());
  }

  // Init the grid axes
  initializeGridAxes(data, vtkView);

  return true;
}

bool ModuleOutline::finalize()
{
  vtkNew<vtkSMParaViewPipelineControllerWithRendering> controller;
  controller->UnRegisterProxy(this->OutlineRepresentation);
  controller->UnRegisterProxy(this->OutlineFilter);

  if (m_view) {
    m_view->GetRenderer()->RemoveActor(m_gridAxes.Get());
  }

  this->OutlineFilter = nullptr;
  this->OutlineRepresentation = nullptr;
  return true;
}

bool ModuleOutline::serialize(pugi::xml_node& ns) const
{
  xml_node rootNode = ns.append_child("properties");

  xml_node visibilityNode = rootNode.append_child("visibility");
  visibilityNode.append_attribute("enabled") = visibility();

  xml_node gridAxesNode = rootNode.append_child("grid_axes");
  gridAxesNode.append_attribute("enabled") = m_gridAxes->GetVisibility() > 0;

  return true;
}

bool ModuleOutline::deserialize(const pugi::xml_node& ns)
{
  xml_node rootNode = ns.child("properties");
  if (!rootNode) {
    return false;
  }

  xml_node node = rootNode.child("visibility");
  if (node) {
    xml_attribute att = node.attribute("enabled");
    if (att) {
      setVisibility(att.as_bool());
    }
  }

  node = rootNode.child("grid_axes");
  if (node) {
    xml_attribute att = node.attribute("enabled");
    if (att) {
      m_gridAxes->SetVisibility(att.as_bool() ? 1 : 0);
    }
  }

  return Module::deserialize(ns);
}

bool ModuleOutline::setVisibility(bool val)
{
  Q_ASSERT(this->OutlineRepresentation);
  vtkSMPropertyHelper(this->OutlineRepresentation, "Visibility")
    .Set(val ? 1 : 0);
  this->OutlineRepresentation->UpdateVTKObjects();
  m_gridAxes->SetVisibility(val ? 1 : 0);
  return true;
}

bool ModuleOutline::visibility() const
{
  if (this->OutlineRepresentation) {
    return vtkSMPropertyHelper(this->OutlineRepresentation, "Visibility")
             .GetAsInt() != 0;
  } else {
    return false;
  }
}

void ModuleOutline::addToPanel(QWidget* panel)
{
  Q_ASSERT(panel && this->OutlineRepresentation);

  if (panel->layout()) {
    delete panel->layout();
  }

  QHBoxLayout* layout = new QHBoxLayout;
  QLabel* label = new QLabel("Color");
  layout->addWidget(label);
  layout->addStretch();
  pqColorChooserButton* colorSelector = new pqColorChooserButton(panel);
  colorSelector->setShowAlphaChannel(false);
  layout->addWidget(colorSelector);

  QHBoxLayout* gridAxesLayout = new QHBoxLayout;
  QCheckBox* showAxesGrid = new QCheckBox(QString("Show Axes Grid"));
  showAxesGrid->setChecked(m_gridAxes->GetVisibility() == 1);

  connect(showAxesGrid, &QCheckBox::stateChanged, this, [this](int state) {
    this->m_gridAxes->SetVisibility(state == Qt::Checked);
    emit this->renderNeeded();
  });

  gridAxesLayout->addWidget(showAxesGrid);

  QVBoxLayout* panelLayout = new QVBoxLayout;
  panelLayout->addItem(layout);
  panelLayout->addItem(gridAxesLayout);
  panelLayout->addStretch();
  panel->setLayout(panelLayout);

  m_links.addPropertyLink(
    colorSelector, "chosenColorRgbF", SIGNAL(chosenColorChanged(const QColor&)),
    this->OutlineRepresentation,
    this->OutlineRepresentation->GetProperty("DiffuseColor"));

  this->connect(colorSelector, &pqColorChooserButton::chosenColorChanged, [this](const QColor& color) {
    m_gridAxes->GetProperty()->SetDiffuseColor(color.redF(), color.greenF(), color.blueF());
  });
  this->connect(colorSelector, &pqColorChooserButton::chosenColorChanged, this,
                &ModuleOutline::dataUpdated);
}

void ModuleOutline::dataUpdated()
{
  m_links.accept();
  emit this->renderNeeded();
}

void ModuleOutline::dataSourceMoved(double newX, double newY, double newZ)
{
  double pos[3] = { newX, newY, newZ };
  vtkSMPropertyHelper(this->OutlineRepresentation, "Position").Set(pos, 3);
  this->OutlineRepresentation->UpdateVTKObjects();
}

//-----------------------------------------------------------------------------
bool ModuleOutline::isProxyPartOfModule(vtkSMProxy* proxy)
{
  return (proxy == this->OutlineFilter.Get()) ||
         (proxy == this->OutlineRepresentation.Get());
}

std::string ModuleOutline::getStringForProxy(vtkSMProxy* proxy)
{
  if (proxy == this->OutlineFilter.Get()) {
    return "Outline";
  } else if (proxy == this->OutlineRepresentation.Get()) {
    return "Representation";
  } else {
    qWarning("Unknown proxy passed to module outline in save animation");
    return "";
  }
}

vtkSMProxy* ModuleOutline::getProxyForString(const std::string& str)
{
  if (str == "Outline") {
    return this->OutlineFilter.Get();
  } else if (str == "Representation") {
    return this->OutlineRepresentation.Get();
  } else {
    return nullptr;
  }
}

void ModuleOutline::updateGridAxesBounds(DataSource* dataSource)
{
  Q_ASSERT(dataSource);
  double bounds[6];
  dataSource->getBounds(bounds);
  m_gridAxes->SetGridBounds(bounds);
}
void ModuleOutline::initializeGridAxes(DataSource* data,
                                       vtkSMViewProxy* vtkView)
{

  updateGridAxesBounds(data);
  m_gridAxes->SetVisibility(0);

  // Work around a bug in vtkGridAxes3DActor. GetProperty() returns the
  // vtkProperty associated with a single face, so to get a property associated
  // with all the faces, we need to create a new one and set it.
  vtkNew<vtkProperty> prop;
  prop->DeepCopy(m_gridAxes->GetProperty());
  this->m_gridAxes->SetProperty(prop.Get());

  // Set the titles
  QString xTitle = QString("X (%1)").arg(data->getUnits(0));
  QString yTitle = QString("Y (%1)").arg(data->getUnits(1));
  QString zTitle = QString("Z (%1)").arg(data->getUnits(2));
  m_gridAxes->SetXTitle(xTitle.toUtf8().data());
  m_gridAxes->SetYTitle(yTitle.toUtf8().data());
  m_gridAxes->SetZTitle(zTitle.toUtf8().data());

  m_view = vtkPVRenderView::SafeDownCast(vtkView->GetClientSideView());
  m_view->GetRenderer()->AddActor(m_gridAxes.Get());

  connect(data, &DataSource::dataPropertiesChanged, this, [this]() {
    auto dataSource = qobject_cast<DataSource*>(sender());
    this->updateGridAxesBounds(dataSource);
    dataSource->producer()->MarkModified(nullptr);
    dataSource->producer()->UpdatePipeline();
    emit this->renderNeeded();

  });
}

} // end of namespace tomviz
<|endoftext|>


<commit_before>#ifndef __CONSTS_HH__
#define __CONSTS_HH__

#include <snowball.h>

constexpr uint32_t sz_magic = SZ_MAGIC;
constexpr

#endif /* end __CONSTS_HH__ include guard */
<commit_msg>Remove unused consts.hh<commit_after><|endoftext|>


<commit_before>/*
 * Copyright (c) 2005, Peter Sommerlad and IFS Institute for Software at HSR Rapperswil, Switzerland
 * All rights reserved.
 *
 * This library/application is free software; you can redistribute and/or modify it under the terms of
 * the license that is included with this library/application in the file license.txt.
 */

//--- interface include --------------------------------------------------------
#include "ResultMapperTest.h"

//--- test modules used --------------------------------------------------------
#include "TestSuite.h"

//--- module under test --------------------------------------------------------
#include "Mapper.h"

//--- standard modules used ----------------------------------------------------
#include "Dbg.h"
#include "StringStream.h"
#include "CacheHandler.h"

//--- c-modules used -----------------------------------------------------------

//---- ResultMapperTest ----------------------------------------------------------------
ResultMapperTest::ResultMapperTest(TString tstrName) : TestCase(tstrName)
{
	StartTrace(ResultMapperTest.Ctor);
}

ResultMapperTest::~ResultMapperTest()
{
	StartTrace(ResultMapperTest.Dtor);
}

// setup for this TestCase
void ResultMapperTest::setUp ()
{
	StartTrace(ResultMapperTest.setUp);
}

void ResultMapperTest::tearDown ()
{
	StartTrace(ResultMapperTest.tearDown);
}

void ResultMapperTest::testDoSelectScript()
{
	StartTrace(ResultMapperTest.testDoSelectScript);

	Anything script, empty;
	script["Sub"] = "a";
	ResultMapper rm("");
	Context ctx;
	assertAnyEqual(rm.DoSelectScript("Sub", script, ctx), script["Sub"]);
	assertAnyEqual(rm.DoSelectScript("Nonex", script, ctx), empty);
}

void ResultMapperTest::testDoLoadConfig()
{
	StartTrace(ResultMapperTest.testDoLoadConfig);

	ResultMapper rm("ResultMapperTest");

	t_assertm(rm.DoLoadConfig("ResultMapper"), "Couldn't load config");
	t_assertm(!rm.DoLoadConfig("NonExistingMapper"), "Found a config, but shouldn't!");
}

void ResultMapperTest::testDoGetConfigName()
{
	StartTrace(ResultMapperTest.testDoGetConfigName);

	String configName;
	ResultMapper rm("");

	rm.DoGetConfigName("ResultMapper", "", configName);
	assertEqual("OutputMapperMeta", configName);
	rm.DoGetConfigName("SomeOtherMapper", "", configName);
	assertEqual("SomeOtherMapperMeta", configName);
}

void ResultMapperTest::testDoFinalPutAny()
{
	StartTrace(ResultMapperTest.testDoFinalPutAny);

	ResultMapper rm("");
	Context ctx;
	Anything a = "first", b = "second", res;

	// 1. Empty key not allowed
	t_assert(!rm.DoFinalPutAny("", a, ctx));
	ctx.GetTmpStore().LookupPath(res, "Mapper");
	t_assert(res.IsNull());

	// 2. Use key
	rm.DoFinalPutAny("rmt", a, ctx);
	ctx.GetTmpStore().LookupPath(res, "Mapper.rmt");
	assertAnyEqual(a, res);

	rm.DoFinalPutAny("rmt", b, ctx);
	ctx.GetTmpStore().LookupPath(res, "Mapper.rmt");
	t_assert(res.GetSize() == 2);
	t_assert(res.Contains(a.AsString()));
	t_assert(res.Contains(b.AsString()));
}

void ResultMapperTest::testDoFinalPutStream()
{
	// uses DoFinalPutAny in the end, so just do a sanity check
	String msg = "MessageToStore";
	IStringStream is(msg);
	ResultMapper rm("");
	Context ctx;
	Anything res;

	rm.DoFinalPutStream("rmt", is, ctx);
	ctx.GetTmpStore().LookupPath(res, "Mapper.rmt");
	assertEqual(msg, res.AsString());
}

void ResultMapperTest::testDoPutAny()
{
	StartTrace(ResultMapperTest.testDoPutAny);

	SimpleAnyLoader sal;
	Anything scripts = sal.Load("MapperTestScripts");
	ROAnything script;
	Anything any = "value";
	Context ctx;
	ResultMapper rm("");

	// --- 1. Mapper without script (i.e. script == empty)

	rm.DoPutAny("rmt", any, ctx, script);
	assertAnyEqual(any, ctx.GetTmpStore()["Mapper"]["rmt"]);

	// --- 2. Mapper with simple valued script (key/context do not matter)

	script = rm.DoSelectScript("SingleScript1", scripts, ctx);
	rm.DoPutAny("-", any, ctx, script);
	assertAnyEqual(any, ctx.GetTmpStore()["Mapper"]["ding"]);

	// --- 3. Mapper with a full script (interpreatation, init key doesn't matter)

	// 3.1 DistributorScript
	Context ctx2;
	script = rm.DoSelectScript("DistributorScript", scripts, ctx);
	rm.DoPutAny("-", any, ctx2, script);
	OStringStream os;
	os << ctx2.GetTmpStore()["Mapper"];
	assertEqual("{\n  /a "_QUOTE_("value")"\n  /b "_QUOTE_("value")"\n  /c "_QUOTE_("value")"\n  /d "_QUOTE_("value")"\n}", os.str());

	// 3.2 DelegationScript
	script = rm.DoSelectScript("AnyPlacerScript", scripts, ctx);
	rm.DoPutAny("Inside", any, ctx, script);
	assertAnyEqualm(any, ctx.GetTmpStore()["SomeSlot"]["Inside"], "Was NameUsingOutputMapper called?");
	assertAnyEqualm(any, ctx.GetTmpStore()["SomeOtherSlot"]["Deep"]["Inside"], "Was NameUsingOutputMapper called?");

	TraceAny(ctx.GetTmpStore(), "tmp");
}

void ResultMapperTest::testDoPutStream()
{
	StartTrace(ResultMapperTest.testDoFinalPutStream);

	// cannot "distribute" a stream like in example above, since
	// stream will be consumed when accessed - no renewal

	SimpleAnyLoader sal;
	Anything scripts = sal.Load("MapperTestScripts");
	ROAnything script;
	Context ctx;
	ResultMapper rm("");
	String msg = "myMsgStream";

	// --- 1. Mapper without script (i.e. script == empty)

	IStringStream is(msg);
	rm.DoPutStream("rmt", is, ctx, script);
	assertEqual(msg, ctx.GetTmpStore()["Mapper"]["rmt"].AsString());

	// --- 2. Mapper with simple valued script (key/context do not matter)

	IStringStream is2(msg);
	script = rm.DoSelectScript("SingleScript1", scripts, ctx);
	rm.DoPutStream("-", is2, ctx, script);
	assertEqual(msg, ctx.GetTmpStore()["Mapper"]["ding"].AsString());

	// --- 3. Mapper with a full script (interpreatation)

	IStringStream is3(msg);
	Anything res;
	script = rm.DoSelectScript("StreamPlacerScript", scripts, ctx);
	rm.DoPutStream("StreamSlot", is3, ctx, script);
	assertEqualm(msg, ctx.GetTmpStore()["SomeSlot"]["StreamSlot"].AsString(), "Was NameUsingOutputMapper called?");
	t_assert(ctx.GetTmpStore().LookupPath(res, "EmptyStuff.StreamSlot"));
	assertEqualm("", res.AsString(), "Should be empty, because stream was consumed!");
}

void ResultMapperTest::testPut()
{
	StartTrace(ResultMapperTest.testPut);

	ResultMapper rm("ResultMapperTest");
	rm.CheckConfig("ResultMapper");
	Context ctx;
	String s("hello"), msg("message");
	long l = 1234L;
	double d = 3.1415;
	bool b = true;
	Anything any;
	any["a"] = "foo";
	any["b"] = "bar";
	IStringStream is(msg);
	Anything tmp = ctx.GetTmpStore();

	// put simple values
	rm.Put("string", s, ctx);
	assertEqual(s, tmp["Mapper"]["sKey"].AsString());

	rm.Put("bool", b, ctx);
	assertEqual(b, tmp["Mapper"]["bKey"].AsBool());

	rm.Put("long", l, ctx);
	assertEqual(l, tmp["Mapper"]["lKey"].AsLong());

	rm.Put("double", d, ctx);
	assertDoublesEqual(d, tmp["Mapper"]["dKey"].AsDouble(), 1);

	// put any
	rm.Put("any", any, ctx);
	assertAnyEqual(any, tmp["Mapper"]["aKey"]);

	// put stream
	rm.Put("stream", is, ctx);
	assertEqual(msg, tmp["Mapper"]["strmKey"].AsString());

	// unknown key in script is put under Mapper.key
	rm.Put("unknownKey", msg, ctx);
	assertEqual(msg, tmp["Mapper"]["unknownKey"].AsString());

	// another put will append the new result
	Anything anyExp = any;
	anyExp.Append(any);
	rm.Put("any", any, ctx);
	assertAnyEqual(anyExp, tmp["Mapper"]["aKey"]);

	// test with special always appending mapper
	ResultMapper arm("AppendingResultMapper");
	arm.CheckConfig("ResultMapper");

	// put any
	anyExp = Anything();
	anyExp.Append(any);
	arm.Put("any", any, ctx);
	assertAnyEqual(anyExp, tmp["AppendAnyMapper"]["aKey"]);
	// another put will append the new result
	anyExp.Append(any);
	arm.Put("any", any, ctx);
	assertAnyEqual(anyExp, tmp["AppendAnyMapper"]["aKey"]);

	anyExp = Anything();
	anyExp.Append(l);
	arm.Put("long", l, ctx);
	assertAnyEqual(anyExp, tmp["AppendAnyMapper"]["lKey"]);
	anyExp.Append(l);
	arm.Put("long", l, ctx);
	assertAnyEqual(anyExp, tmp["AppendAnyMapper"]["lKey"]);
}

void ResultMapperTest::testEagerDoSelectScript()
{
	StartTrace(ParameterMapperTest.testEagerDoSelectScript);

	Anything script;
	script["Sub"] = "a";
	EagerResultMapper erm("");
	Context ctx;
	assertAnyEqual(erm.DoSelectScript("Sub", script, ctx), script["Sub"]);
	assertAnyEqual(erm.DoSelectScript("Nonex", script, ctx), script);
}

void ResultMapperTest::testEagerPut()
{
	StartTrace(ResultMapperTest.testEagerPut);

	// eager mapper gets a script in any case, even if key is not found
	// which leads to a distribution of the information
	EagerResultMapper erm("ResultMapperTest");
	erm.CheckConfig("ResultMapper");
	Context ctx;
	String msg("foo");

	erm.Put("unknownKey", msg, ctx);

	OStringStream os;
	os << ctx.GetTmpStore()["Mapper"];
	IStringStream is("{ /sKey foo /dKey foo /lKey foo /bKey foo /aKey foo /strmKey foo }");
	Anything a;
	is >> a;
	OStringStream os2;
	os2 << a;
	assertEqual(os2.str(), os.str());
}

void ResultMapperTest::testDoSetDestinationSlotDynamically()
{
	StartTrace(ResultMapperTest.testSetDestinationSlot);

	Context ctx;
	ResultMapper rm("DynamicStorer");

	// without config
	assertEquals("Mapper", rm.DoGetDestinationSlot(ctx));

	// set in tmp-store
	ctx.GetTmpStore()["DynamicStorer"]["DestinationSlot"] = "Mapper.a.b.c";
	assertEquals("Mapper.a.b.c", rm.DoGetDestinationSlot(ctx));

	// with config (overrides dest in tmp store)
	rm.CheckConfig("ResultMapper");
	assertEquals("Mapper.foo.bar", rm.DoGetDestinationSlot(ctx));
}

void ResultMapperTest::testDoGetDestinationSlotWithPath()
{
	StartTrace(ResultMapperTest.testDoGetDestinationSlotWithPath);

	Context ctx;
	PathTestMapper ptm("");
	assertEquals("Mapper.x.y.z", ptm.DoGetDestinationSlot(ctx));

	// assign first
	ptm.Put("msg", String("foo"), ctx);
	TraceAny(ctx.GetTmpStore(), "tmp");
	Anything res;
	ctx.GetTmpStore().LookupPath(res, "Mapper.x.y.z.msg");
	assertEquals("foo", res.AsString());

	// assign second
	ptm.Put("msg", String("bar"), ctx);
	ctx.GetTmpStore().LookupPath(res, "Mapper.x.y.z.msg");
	assertEquals(2, res.GetSize());
	t_assert(res.Contains("foo"));
	t_assert(res.Contains("bar"));
}

// builds up a suite of testcases, add a line for each testmethod
Test *ResultMapperTest::suite ()
{
	StartTrace(ResultMapperTest.suite);
	TestSuite *testSuite = new TestSuite;

	ADD_CASE(testSuite, ResultMapperTest, testDoLoadConfig);
	ADD_CASE(testSuite, ResultMapperTest, testDoSelectScript);
	ADD_CASE(testSuite, ResultMapperTest, testDoGetConfigName);
	ADD_CASE(testSuite, ResultMapperTest, testDoFinalPutAny);
	ADD_CASE(testSuite, ResultMapperTest, testDoFinalPutStream);
	ADD_CASE(testSuite, ResultMapperTest, testDoPutAny);
	ADD_CASE(testSuite, ResultMapperTest, testDoPutStream);
	ADD_CASE(testSuite, ResultMapperTest, testPut);
	ADD_CASE(testSuite, ResultMapperTest, testDoSetDestinationSlotDynamically);
	ADD_CASE(testSuite, ResultMapperTest, testDoGetDestinationSlotWithPath);

	ADD_CASE(testSuite, ResultMapperTest, testEagerDoSelectScript);
	ADD_CASE(testSuite, ResultMapperTest, testEagerPut);
	return testSuite;
}
<commit_msg>changed to new interface<commit_after>/*
 * Copyright (c) 2005, Peter Sommerlad and IFS Institute for Software at HSR Rapperswil, Switzerland
 * All rights reserved.
 *
 * This library/application is free software; you can redistribute and/or modify it under the terms of
 * the license that is included with this library/application in the file license.txt.
 */

//--- interface include --------------------------------------------------------
#include "ResultMapperTest.h"

//--- test modules used --------------------------------------------------------
#include "TestSuite.h"

//--- module under test --------------------------------------------------------
#include "Mapper.h"

//--- standard modules used ----------------------------------------------------
#include "Dbg.h"
#include "StringStream.h"
#include "CacheHandler.h"

//--- c-modules used -----------------------------------------------------------

//---- ResultMapperTest ----------------------------------------------------------------
ResultMapperTest::ResultMapperTest(TString tstrName) : TestCase(tstrName)
{
	StartTrace(ResultMapperTest.Ctor);
}

ResultMapperTest::~ResultMapperTest()
{
	StartTrace(ResultMapperTest.Dtor);
}

// setup for this TestCase
void ResultMapperTest::setUp ()
{
	StartTrace(ResultMapperTest.setUp);
}

void ResultMapperTest::tearDown ()
{
	StartTrace(ResultMapperTest.tearDown);
}

void ResultMapperTest::testDoSelectScript()
{
	StartTrace(ResultMapperTest.testDoSelectScript);

	Anything script, empty;
	script["Sub"] = "a";
	ResultMapper rm("");
	Context ctx;
	assertAnyEqual(rm.DoSelectScript("Sub", script, ctx), script["Sub"]);
	assertAnyEqual(rm.DoSelectScript("Nonex", script, ctx), empty);
}

void ResultMapperTest::testDoLoadConfig()
{
	StartTrace(ResultMapperTest.testDoLoadConfig);

	ResultMapper rm("ResultMapperTest");

	t_assertm(rm.DoLoadConfig("ResultMapper"), "Couldn't load config");
	t_assertm(!rm.DoLoadConfig("NonExistingMapper"), "Found a config, but shouldn't!");
}

void ResultMapperTest::testDoGetConfigName()
{
	StartTrace(ResultMapperTest.testDoGetConfigName);

	String configName;
	ResultMapper rm("");

	rm.DoGetConfigName("ResultMapper", "", configName);
	assertEqual("OutputMapperMeta", configName);
	rm.DoGetConfigName("SomeOtherMapper", "", configName);
	assertEqual("SomeOtherMapperMeta", configName);
}

void ResultMapperTest::testDoFinalPutAny()
{
	StartTrace(ResultMapperTest.testDoFinalPutAny);

	ResultMapper rm("");
	Context ctx;
	Anything a = "first", b = "second", res;

	// 1. Empty key not allowed
	t_assert(!rm.DoFinalPutAny("", a, ctx));
	ctx.GetTmpStore().LookupPath(res, "Mapper");
	t_assert(res.IsNull());

	// 2. Use key
	rm.DoFinalPutAny("rmt", a, ctx);
	ctx.GetTmpStore().LookupPath(res, "Mapper.rmt");
	assertAnyEqual(a, res);

	rm.DoFinalPutAny("rmt", b, ctx);
	ctx.GetTmpStore().LookupPath(res, "Mapper.rmt");
	t_assert(res.GetSize() == 2);
	t_assert(res.Contains(a.AsString()));
	t_assert(res.Contains(b.AsString()));
}

void ResultMapperTest::testDoFinalPutStream()
{
	// uses DoFinalPutAny in the end, so just do a sanity check
	String msg = "MessageToStore";
	IStringStream is(msg);
	ResultMapper rm("");
	Context ctx;
	Anything res;

	rm.DoFinalPutStream("rmt", is, ctx);
	ctx.GetTmpStore().LookupPath(res, "Mapper.rmt");
	assertEqual(msg, res.AsString());
}

void ResultMapperTest::testDoPutAny()
{
	StartTrace(ResultMapperTest.testDoPutAny);

	SimpleAnyLoader sal;
	Anything scripts = sal.Load("MapperTestScripts");
	ROAnything script;
	Anything any = "value";
	Context ctx;
	ResultMapper rm("");

	// --- 1. Mapper without script (i.e. script == empty)

	rm.DoPutAny("rmt", any, ctx, script);
	assertAnyEqual(any, ctx.GetTmpStore()["Mapper"]["rmt"]);

	// --- 2. Mapper with simple valued script (key/context do not matter)

	script = rm.DoSelectScript("SingleScript1", scripts, ctx);
	rm.DoPutAny("-", any, ctx, script);
	assertAnyEqual(any, ctx.GetTmpStore()["Mapper"]["ding"]);

	// --- 3. Mapper with a full script (interpreatation, init key doesn't matter)

	// 3.1 DistributorScript
	Context ctx2;
	script = rm.DoSelectScript("DistributorScript", scripts, ctx);
	rm.DoPutAny("-", any, ctx2, script);
	OStringStream os;
	os << ctx2.GetTmpStore()["Mapper"];
	assertEqual("{\n  /a "_QUOTE_("value")"\n  /b "_QUOTE_("value")"\n  /c "_QUOTE_("value")"\n  /d "_QUOTE_("value")"\n}", os.str());

	// 3.2 DelegationScript
	script = rm.DoSelectScript("AnyPlacerScript", scripts, ctx);
	rm.DoPutAny("Inside", any, ctx, script);
	assertAnyEqualm(any, ctx.GetTmpStore()["SomeSlot"]["Inside"], "Was NameUsingOutputMapper called?");
	assertAnyEqualm(any, ctx.GetTmpStore()["SomeOtherSlot"]["Deep"]["Inside"], "Was NameUsingOutputMapper called?");

	TraceAny(ctx.GetTmpStore(), "tmp");
}

void ResultMapperTest::testDoPutStream()
{
	StartTrace(ResultMapperTest.testDoFinalPutStream);

	// cannot "distribute" a stream like in example above, since
	// stream will be consumed when accessed - no renewal

	SimpleAnyLoader sal;
	Anything scripts = sal.Load("MapperTestScripts");
	ROAnything script;
	Context ctx;
	ResultMapper rm("");
	String msg = "myMsgStream";

	// --- 1. Mapper without script (i.e. script == empty)

	IStringStream is(msg);
	rm.DoPutStream("rmt", is, ctx, script);
	assertEqual(msg, ctx.GetTmpStore()["Mapper"]["rmt"].AsString());

	// --- 2. Mapper with simple valued script (key/context do not matter)

	IStringStream is2(msg);
	script = rm.DoSelectScript("SingleScript1", scripts, ctx);
	rm.DoPutStream("-", is2, ctx, script);
	assertEqual(msg, ctx.GetTmpStore()["Mapper"]["ding"].AsString());

	// --- 3. Mapper with a full script (interpreatation)

	IStringStream is3(msg);
	Anything res;
	script = rm.DoSelectScript("StreamPlacerScript", scripts, ctx);
	rm.DoPutStream("StreamSlot", is3, ctx, script);
	assertEqualm(msg, ctx.GetTmpStore()["SomeSlot"]["StreamSlot"].AsString(), "Was NameUsingOutputMapper called?");
	t_assert(ctx.GetTmpStore().LookupPath(res, "EmptyStuff.StreamSlot"));
	assertEqualm("", res.AsString(), "Should be empty, because stream was consumed!");
}

void ResultMapperTest::testPut()
{
	StartTrace(ResultMapperTest.testPut);

	ResultMapper rm("ResultMapperTest");
	rm.CheckConfig("ResultMapper");
	Context ctx;
	String s("hello"), msg("message");
	long l = 1234L;
	double d = 3.1415;
	bool b = true;
	Anything any;
	any["a"] = "foo";
	any["b"] = "bar";
	IStringStream is(msg);
	Anything tmp = ctx.GetTmpStore();

	// put simple values
	rm.Put("string", s, ctx);
	assertEqual(s, tmp["Mapper"]["sKey"].AsString());

	rm.Put("bool", b, ctx);
	assertEqual(b, tmp["Mapper"]["bKey"].AsBool());

	rm.Put("long", l, ctx);
	assertEqual(l, tmp["Mapper"]["lKey"].AsLong());

	rm.Put("double", d, ctx);
	assertDoublesEqual(d, tmp["Mapper"]["dKey"].AsDouble(), 1);

	// put any
	rm.Put("any", any, ctx);
	assertAnyEqual(any, tmp["Mapper"]["aKey"]);

	// put stream
	rm.Put("stream", is, ctx);
	assertEqual(msg, tmp["Mapper"]["strmKey"].AsString());

	// unknown key in script is put under Mapper.key
	rm.Put("unknownKey", msg, ctx);
	assertEqual(msg, tmp["Mapper"]["unknownKey"].AsString());

	// another put will append the new result
	Anything anyExp = any;
	anyExp.Append(any);
	rm.Put("any", any, ctx);
	assertAnyEqual(anyExp, tmp["Mapper"]["aKey"]);

	// test with special always appending mapper
	ResultMapper arm("AppendingResultMapper");
	arm.CheckConfig("ResultMapper");

	// put any
	anyExp = Anything();
	anyExp.Append(any);
	arm.Put("any", any, ctx);
	assertAnyEqual(anyExp, tmp["AppendAnyMapper"]["aKey"]);
	// another put will append the new result
	anyExp.Append(any);
	arm.Put("any", any, ctx);
	assertAnyEqual(anyExp, tmp["AppendAnyMapper"]["aKey"]);

	anyExp = Anything();
	anyExp.Append(l);
	arm.Put("long", l, ctx);
	assertAnyEqual(anyExp, tmp["AppendAnyMapper"]["lKey"]);
	anyExp.Append(l);
	arm.Put("long", l, ctx);
	assertAnyEqual(anyExp, tmp["AppendAnyMapper"]["lKey"]);
}

void ResultMapperTest::testEagerDoSelectScript()
{
	StartTrace(ParameterMapperTest.testEagerDoSelectScript);

	Anything script;
	script["Sub"] = "a";
	EagerResultMapper erm("");
	Context ctx;
	assertAnyEqual(erm.DoSelectScript("Sub", script, ctx), script["Sub"]);
	assertAnyEqual(erm.DoSelectScript("Nonex", script, ctx), script);
}

void ResultMapperTest::testEagerPut()
{
	StartTrace(ResultMapperTest.testEagerPut);

	// eager mapper gets a script in any case, even if key is not found
	// which leads to a distribution of the information
	EagerResultMapper erm("ResultMapperTest");
	erm.CheckConfig("ResultMapper");
	Context ctx;
	String msg("foo");

	erm.Put("unknownKey", msg, ctx);

	OStringStream os;
	os << ctx.GetTmpStore()["Mapper"];
	IStringStream is("{ /sKey foo /dKey foo /lKey foo /bKey foo /aKey foo /strmKey foo }");
	Anything a;
	is >> a;
	OStringStream os2;
	os2 << a;
	assertEqual(os2.str(), os.str());
}

void ResultMapperTest::testDoSetDestinationSlotDynamically()
{
	StartTrace(ResultMapperTest.testSetDestinationSlot);

	Context ctx;
	ResultMapper rm("DynamicStorer");

	// without config
	assertEquals("Mapper", rm.GetDestinationSlot(ctx));

	// set in tmp-store
	ctx.GetTmpStore()["DynamicStorer"]["DestinationSlot"] = "Mapper.a.b.c";
	assertEquals("Mapper.a.b.c", rm.GetDestinationSlot(ctx));

	// with config (overrides dest in tmp store)
	rm.CheckConfig("ResultMapper");
	assertEquals("Mapper.foo.bar", rm.GetDestinationSlot(ctx));
}

void ResultMapperTest::testDoGetDestinationSlotWithPath()
{
	StartTrace(ResultMapperTest.testDoGetDestinationSlotWithPath);

	Context ctx;
	PathTestMapper ptm("");
	assertEquals("Mapper.x.y.z", ptm.GetDestinationSlot(ctx));

	// assign first
	ptm.Put("msg", String("foo"), ctx);
	TraceAny(ctx.GetTmpStore(), "tmp");
	Anything res;
	ctx.GetTmpStore().LookupPath(res, "Mapper.x.y.z.msg");
	assertEquals("foo", res.AsString());

	// assign second
	ptm.Put("msg", String("bar"), ctx);
	ctx.GetTmpStore().LookupPath(res, "Mapper.x.y.z.msg");
	assertEquals(2, res.GetSize());
	t_assert(res.Contains("foo"));
	t_assert(res.Contains("bar"));
}

// builds up a suite of testcases, add a line for each testmethod
Test *ResultMapperTest::suite ()
{
	StartTrace(ResultMapperTest.suite);
	TestSuite *testSuite = new TestSuite;

	ADD_CASE(testSuite, ResultMapperTest, testDoLoadConfig);
	ADD_CASE(testSuite, ResultMapperTest, testDoSelectScript);
	ADD_CASE(testSuite, ResultMapperTest, testDoGetConfigName);
	ADD_CASE(testSuite, ResultMapperTest, testDoFinalPutAny);
	ADD_CASE(testSuite, ResultMapperTest, testDoFinalPutStream);
	ADD_CASE(testSuite, ResultMapperTest, testDoPutAny);
	ADD_CASE(testSuite, ResultMapperTest, testDoPutStream);
	ADD_CASE(testSuite, ResultMapperTest, testPut);
	ADD_CASE(testSuite, ResultMapperTest, testDoSetDestinationSlotDynamically);
	ADD_CASE(testSuite, ResultMapperTest, testDoGetDestinationSlotWithPath);

	ADD_CASE(testSuite, ResultMapperTest, testEagerDoSelectScript);
	ADD_CASE(testSuite, ResultMapperTest, testEagerPut);
	return testSuite;
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2012 Aldebaran Robotics. All rights reserved.
 * Use of this source code is governed by a BSD-style license that can be
 * found in the COPYING file.
 */

#include <qi/log.hpp>
#include <qi/os.hpp>

#include <boost/filesystem.hpp>

#include <iostream>
#include <cstring>

# ifdef _WIN32
#  include <windows.h>
# else
#  include <dlfcn.h>
# endif

#include <qi/qi.hpp>
#include <qi/path.hpp>

#include "filesystem.hpp"

namespace qi {
  namespace os {

    void *dlopen(const char *filename, int flag) {
      std::string fullName = path::findLib(filename);
      if (fullName.empty())
      {
        qiLogError("qi.dlopen") << "Could not locate library " << filename;
        fullName = filename; // Do not return here, let sys call fails and set errno.
      }
      void *handle = NULL;
      boost::filesystem::path fname(fullName, qi::unicodeFacet());
      qiLogDebug("qi.dlopen") << "opening " << fname;
     #ifdef _WIN32
      handle = LoadLibraryW(fname.wstring(qi::unicodeFacet()).c_str());
     #else
      if (flag == -1)
        flag = RTLD_NOW;
      handle = ::dlopen(fname.string(qi::unicodeFacet()).c_str(), flag);
     #endif
      return handle;
    }

    int   dlclose(void *handle) {
      if (!handle)
        return 0;
     #ifdef _WIN32
      // Mimic unix dlclose (0 on sucess)
      return FreeLibrary((HINSTANCE) handle) != 0 ? 0 : -1;
     #else
      return ::dlclose(handle);
     #endif
    }

    void *dlsym(void *handle, const char *symbol) {
      void* function = NULL;

      if(!handle)
        return 0;
     #ifdef _WIN32
      function = (void *)GetProcAddress((HINSTANCE) handle, symbol);
     #else
      function = ::dlsym(handle, symbol);
     #endif
      return function;
    }

    const char *dlerror(void) {
     #ifdef _WIN32
      static char err[255];
      DWORD lastError = GetLastError();
      // Unix dlerror() return null if error code is 0
      if (lastError == 0)
        return NULL;

      DWORD result = FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM, 0, lastError, 0, err, sizeof(err), 0);
      // Unix dlerror() resets its value after a call, ensure same behavior
      SetLastError(0);
      return err;
     #else
      return ::dlerror();
     #endif
    }

  }
}
<commit_msg>make dlerror threadsafe on windows<commit_after>/*
 * Copyright (c) 2012 Aldebaran Robotics. All rights reserved.
 * Use of this source code is governed by a BSD-style license that can be
 * found in the COPYING file.
 */

#include <qi/log.hpp>
#include <qi/os.hpp>

#include <boost/filesystem.hpp>
#include <boost/thread/tss.hpp>

#include <iostream>
#include <cstring>

# ifdef _WIN32
#  include <windows.h>
# else
#  include <dlfcn.h>
# endif

#include <qi/qi.hpp>
#include <qi/path.hpp>

#include "filesystem.hpp"

namespace qi {
  namespace os {

    void *dlopen(const char *filename, int flag) {
      std::string fullName = path::findLib(filename);
      if (fullName.empty())
      {
        qiLogError("qi.dlopen") << "Could not locate library " << filename;
        fullName = filename; // Do not return here, let sys call fails and set errno.
      }
      void *handle = NULL;
      boost::filesystem::path fname(fullName, qi::unicodeFacet());
      qiLogDebug("qi.dlopen") << "opening " << fname;
     #ifdef _WIN32
      handle = LoadLibraryW(fname.wstring(qi::unicodeFacet()).c_str());
     #else
      if (flag == -1)
        flag = RTLD_NOW;
      handle = ::dlopen(fname.string(qi::unicodeFacet()).c_str(), flag);
     #endif
      return handle;
    }

    int   dlclose(void *handle) {
      if (!handle)
        return 0;
     #ifdef _WIN32
      // Mimic unix dlclose (0 on sucess)
      return FreeLibrary((HINSTANCE) handle) != 0 ? 0 : -1;
     #else
      return ::dlclose(handle);
     #endif
    }

    void *dlsym(void *handle, const char *symbol) {
      void* function = NULL;

      if(!handle)
        return 0;
     #ifdef _WIN32
      function = (void *)GetProcAddress((HINSTANCE) handle, symbol);
     #else
      function = ::dlsym(handle, symbol);
     #endif
      return function;
    }

#ifdef _WIN32

    void cleanup(char* ptr)
    {
      delete[] ptr;
    }

#endif // !_WIN32

    const char *dlerror(void) {
     #ifdef _WIN32
      DWORD lastError = GetLastError();
      // Unix dlerror() return null if error code is 0
      if (lastError == 0)
        return NULL;

      static boost::thread_specific_ptr<char> err(cleanup);
      if (!err.get())
        err.reset(static_cast<char*>(new char[255]));

      DWORD result = FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM, 0, lastError, 0, err.get(), sizeof(char) * 255, 0);

      // Unix dlerror() resets its value after a call, ensure same behavior
      SetLastError(0);
      return err.get();
     #else
      return ::dlerror();
     #endif
    }

  }
}
<|endoftext|>