<commit_before>package relay

import (
	"bytes"
	"encoding/binary"
	"errors"
	"github.com/lbarman/prifi/prifi-lib/client"
	"github.com/lbarman/prifi/prifi-lib/config"
	"github.com/lbarman/prifi/prifi-lib/crypto"
	"github.com/lbarman/prifi/prifi-lib/net"
	"gopkg.in/dedis/crypto.v0/random"
	"gopkg.in/dedis/onet.v1/log"
	"strconv"
	"sync"
	"testing"
	"time"
)

/**
 * Message Sender
 */
type TestMessageSender struct {
}

var clientLock sync.Mutex
var trusteeLock sync.Mutex

func (t *TestMessageSender) SendToClient(i int, msg interface{}) error {
	clientLock.Lock()
	defer clientLock.Unlock()
	sentToClient = append(sentToClient, msg)
	return nil
}
func (t *TestMessageSender) SendToTrustee(i int, msg interface{}) error {
	trusteeLock.Lock()
	defer trusteeLock.Unlock()
	sentToTrustee = append(sentToTrustee, msg)
	return nil
}

var sentToClient []interface{}
var sentToTrustee []interface{}

func (t *TestMessageSender) SendToRelay(msg interface{}) error {
	return errors.New("Relay sending to relay !?")
}
func (t *TestMessageSender) BroadcastToAllClients(msg interface{}) error {
	return t.SendToClient(0, msg)
}
func (t *TestMessageSender) ClientSubscribeToBroadcast(clientID int, messageReceived func(interface{}) error, startStopChan chan bool) error {
	return errors.New("Not for relay")
}

/**
 * Message Sender Wrapper
 */

func newTestMessageSenderWrapper(msgSender net.MessageSender) *net.MessageSenderWrapper {

	errHandling := func(e error) {}
	loggingSuccessFunction := func(e interface{}) { log.Lvl3(e) }
	loggingErrorFunction := func(e interface{}) { log.Error(e) }

	msw, err := net.NewMessageSenderWrapper(true, loggingSuccessFunction, loggingErrorFunction, errHandling, msgSender)
	if err != nil {
		log.Fatal("Could not create a MessageSenderWrapper, error is", err)
	}
	return msw
}

func getClientMessage(wantedMessage string) (interface{}, error) {
	clientLock.Lock()
	defer clientLock.Unlock()
	return getMessage(&sentToClient, wantedMessage)
}
func getTrusteeMessage(wantedMessage string) (interface{}, error) {
	trusteeLock.Lock()
	defer trusteeLock.Unlock()
	return getMessage(&sentToTrustee, wantedMessage)
}

func getMessage(bufferPtr *[]interface{}, wantedMessage string) (interface{}, error) {
	buffer := *bufferPtr
	if buffer == nil {
		panic("Buffer nil")
	}
	if len(buffer) == 0 {
		return nil, errors.New("Tried to fetch a " + wantedMessage + "but buffer is empty.")
	}
	msg := buffer[0]
	*bufferPtr = buffer[1:]
	return msg, nil
}

func TestRelayRun1(t *testing.T) {

	timeoutHandler := func(clients, trustees []int) { log.Error(clients, trustees) }
	resultChan := make(chan interface{}, 1)

	msgSender := new(TestMessageSender)
	msw := newTestMessageSenderWrapper(msgSender)
	sentToClient = make([]interface{}, 0)
	sentToTrustee = make([]interface{}, 0)
	dataForClients := make(chan []byte, 6)
	dataFromDCNet := make(chan []byte, 3)

	relay := NewRelay(true, dataForClients, dataFromDCNet, resultChan, timeoutHandler, msw)

	//when receiving no message, client should have some parameters ready
	rs := relay.relayState
	if rs.DataOutputEnabled != true {
		t.Error("DataOutputEnabled was not set correctly")
	}
	if rs.DataFromDCNet == nil {
		t.Error("DataFromDCNet was not set correctly")
	}
	if rs.DataForClients == nil {
		t.Error("DataForClients was not set correctly")
	}
	if rs.timeoutHandler == nil {
		t.Error("timeoutHandler was not set correctly")
	}
	if rs.ExperimentResultChannel == nil {
		t.Error("ExperimentResultChannel was not set correctly")
	}
	if rs.PriorityDataForClients == nil {
		t.Error("PriorityDataForClients was not set correctly")
	}
	if relay.stateMachine.State() != "BEFORE_INIT" {
		t.Error("State was not set correctly")
	}
	if rs.privateKey == nil || rs.PublicKey == nil {
		t.Error("Private/Public key not set")
	}
	if rs.bitrateStatistics == nil {
		t.Error("Statistics should have been set")
	}

	//we start by receiving a ALL_ALL_PARAMETERS from relay
	msg := new(net.ALL_ALL_PARAMETERS)
	msg.ForceParams = true
	nClients := 1
	nTrustees := 1
	upCellSize := 1500
	dcNetType := "Simple"
	msg.Add("StartNow", true)
	msg.Add("NClients", nClients)
	msg.Add("NTrustees", nTrustees)
	msg.Add("UpstreamCellSize", upCellSize)
	msg.Add("DownstreamCellSize", 10*upCellSize)
	msg.Add("WindowSize", 1)
	msg.Add("UseUDP", true)
	msg.Add("UseDummyDataDown", true)
	msg.Add("ExperimentRoundLimit", 2)
	msg.Add("DCNetType", dcNetType)
	msg.Add("UseOpenClosedSlots", true)
	msg.Add("UseDummyDataDown", true)
	msg.Add("DisruptionProtectionEnabled", true)
	msg.Add("OpenClosedSlotsMinDelayBetweenRequests", 101)
	msg.Add("RelayMaxNumberOfConsecutiveFailedRounds", 3)
	msg.Add("RelayProcessingLoopSleepTime", 102)
	msg.Add("RelayRoundTimeOut", 1003)
	msg.Add("RelayTrusteeCacheLowBound", 10)
	msg.Add("RelayTrusteeCacheHighBound", 15)

	if err := relay.ReceivedMessage(*msg); err != nil {
		t.Error("Relay should be able to receive this message, but", err)
	}
	if rs.nClients != nClients {
		t.Error("nClients was not set correctly")<commit_msg>Fixes relay test (statistics created on ALL_ALL_PARAM message)<commit_after>package relay

import (
	"bytes"
	"encoding/binary"
	"errors"
	"github.com/lbarman/prifi/prifi-lib/client"
	"github.com/lbarman/prifi/prifi-lib/config"
	"github.com/lbarman/prifi/prifi-lib/crypto"
	"github.com/lbarman/prifi/prifi-lib/net"
	"gopkg.in/dedis/crypto.v0/random"
	"gopkg.in/dedis/onet.v1/log"
	"strconv"
	"sync"
	"testing"
	"time"
)

/**
 * Message Sender
 */
type TestMessageSender struct {
}

var clientLock sync.Mutex
var trusteeLock sync.Mutex

func (t *TestMessageSender) SendToClient(i int, msg interface{}) error {
	clientLock.Lock()
	defer clientLock.Unlock()
	sentToClient = append(sentToClient, msg)
	return nil
}
func (t *TestMessageSender) SendToTrustee(i int, msg interface{}) error {
	trusteeLock.Lock()
	defer trusteeLock.Unlock()
	sentToTrustee = append(sentToTrustee, msg)
	return nil
}

var sentToClient []interface{}
var sentToTrustee []interface{}

func (t *TestMessageSender) SendToRelay(msg interface{}) error {
	return errors.New("Relay sending to relay !?")
}
func (t *TestMessageSender) BroadcastToAllClients(msg interface{}) error {
	return t.SendToClient(0, msg)
}
func (t *TestMessageSender) ClientSubscribeToBroadcast(clientID int, messageReceived func(interface{}) error, startStopChan chan bool) error {
	return errors.New("Not for relay")
}

/**
 * Message Sender Wrapper
 */

func newTestMessageSenderWrapper(msgSender net.MessageSender) *net.MessageSenderWrapper {

	errHandling := func(e error) {}
	loggingSuccessFunction := func(e interface{}) { log.Lvl3(e) }
	loggingErrorFunction := func(e interface{}) { log.Error(e) }

	msw, err := net.NewMessageSenderWrapper(true, loggingSuccessFunction, loggingErrorFunction, errHandling, msgSender)
	if err != nil {
		log.Fatal("Could not create a MessageSenderWrapper, error is", err)
	}
	return msw
}

func getClientMessage(wantedMessage string) (interface{}, error) {
	clientLock.Lock()
	defer clientLock.Unlock()
	return getMessage(&sentToClient, wantedMessage)
}
func getTrusteeMessage(wantedMessage string) (interface{}, error) {
	trusteeLock.Lock()
	defer trusteeLock.Unlock()
	return getMessage(&sentToTrustee, wantedMessage)
}

func getMessage(bufferPtr *[]interface{}, wantedMessage string) (interface{}, error) {
	buffer := *bufferPtr
	if buffer == nil {
		panic("Buffer nil")
	}
	if len(buffer) == 0 {
		return nil, errors.New("Tried to fetch a " + wantedMessage + "but buffer is empty.")
	}
	msg := buffer[0]
	*bufferPtr = buffer[1:]
	return msg, nil
}

func TestRelayRun1(t *testing.T) {

	timeoutHandler := func(clients, trustees []int) { log.Error(clients, trustees) }
	resultChan := make(chan interface{}, 1)

	msgSender := new(TestMessageSender)
	msw := newTestMessageSenderWrapper(msgSender)
	sentToClient = make([]interface{}, 0)
	sentToTrustee = make([]interface{}, 0)
	dataForClients := make(chan []byte, 6)
	dataFromDCNet := make(chan []byte, 3)

	relay := NewRelay(true, dataForClients, dataFromDCNet, resultChan, timeoutHandler, msw)

	//when receiving no message, client should have some parameters ready
	rs := relay.relayState
	if rs.DataOutputEnabled != true {
		t.Error("DataOutputEnabled was not set correctly")
	}
	if rs.DataFromDCNet == nil {
		t.Error("DataFromDCNet was not set correctly")
	}
	if rs.DataForClients == nil {
		t.Error("DataForClients was not set correctly")
	}
	if rs.timeoutHandler == nil {
		t.Error("timeoutHandler was not set correctly")
	}
	if rs.ExperimentResultChannel == nil {
		t.Error("ExperimentResultChannel was not set correctly")
	}
	if rs.PriorityDataForClients == nil {
		t.Error("PriorityDataForClients was not set correctly")
	}
	if relay.stateMachine.State() != "BEFORE_INIT" {
		t.Error("State was not set correctly")
	}
	if rs.privateKey == nil || rs.PublicKey == nil {
		t.Error("Private/Public key not set")
	}

	//we start by receiving a ALL_ALL_PARAMETERS from relay
	msg := new(net.ALL_ALL_PARAMETERS)
	msg.ForceParams = true
	nClients := 1
	nTrustees := 1
	upCellSize := 1500
	dcNetType := "Simple"
	msg.Add("StartNow", true)
	msg.Add("NClients", nClients)
	msg.Add("NTrustees", nTrustees)
	msg.Add("UpstreamCellSize", upCellSize)
	msg.Add("DownstreamCellSize", 10*upCellSize)
	msg.Add("WindowSize", 1)
	msg.Add("UseUDP", true)
	msg.Add("UseDummyDataDown", true)
	msg.Add("ExperimentRoundLimit", 2)
	msg.Add("DCNetType", dcNetType)
	msg.Add("UseOpenClosedSlots", true)
	msg.Add("UseDummyDataDown", true)
	msg.Add("DisruptionProtectionEnabled", true)
	msg.Add("OpenClosedSlotsMinDelayBetweenRequests", 101)
	msg.Add("RelayMaxNumberOfConsecutiveFailedRounds", 3)
	msg.Add("RelayProcessingLoopSleepTime", 102)
	msg.Add("RelayRoundTimeOut", 1003)
	msg.Add("RelayTrusteeCacheLowBound", 10)
	msg.Add("RelayTrusteeCacheHighBound", 15)

	if err := relay.ReceivedMessage(*msg); err != nil {
		t.Error("Relay should be able to receive this message, but", err)
	}
	if rs.bitrateStatistics == nil {
		t.Error("Statistics should have been set")
	}
	if rs.nClients != nClients {
		t.Error("nClients was not set correctly")
{'fraction_non_alphanumeric': 0.1323251417769376, 'fraction_numerical': 0.007561436672967864, 'mean_word_length': 5.45186136071887, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1658650', 'n_tokens_mistral': 3568, 'n_tokens_neox': 3406, 'n_words': 806}