Untitled

mail@pastecode.io avatar
unknown
golang
a month ago
2.9 kB
2
Indexable
Never
func TestSendStoreMessage(t *testing.T) {
	// Set up the receiver node and its network
	receiverPort, err := tests.GetFreePort()
	assert.NoError(t, err, "Failed to get a free port")

	receiverDht := dht.NewDHT(24*time.Hour, []byte("1234567890abcdef"), "2", "127.0.0.1", receiverPort)
	receiverStore := storage.NewStorage(24*time.Hour, []byte("1234567890abcdef"))
	receiverNode := &node.Node{
		IP:      "127.0.0.1",
		Port:    receiverPort,
		Storage: receiverStore,
		DHT:     receiverDht,
	}

	// Set up the sender node and its network
	senderPort, err := tests.GetFreePort()
	assert.NoError(t, err, "Failed to get a free port")
	senderDht := dht.NewDHT(24*time.Hour, []byte("1234567890abcdef"), "2", "127.0.0.2", senderPort)
	senderStore := storage.NewStorage(24*time.Hour, []byte("1234567890abcdef"))
	senderNode := &node.Node{
		IP:      "127.0.0.2",
		Port:    senderPort,
		Storage: senderStore,
		DHT:     senderDht,
	}

	network_sender := message.NewNetwork(receiverNode.IP, receiverNode.ID, receiverNode.Port)
	log.Print("Receiver port:", receiverPort)

	// Start the receiver node's network listening for messages
	go func() {
		err := network_sender.StartListening()
		assert.NoError(t, err)
		log.Print("Receiver is listening")
	}()
	time.Sleep(2 * time.Second)

	network_receiver := message.NewNetwork(senderNode.IP, senderNode.ID, senderNode.Port)
	log.Print("Sender port:", senderPort)

	go func() {
		err := network_receiver.StartListening()
		assert.NoError(t, err)
		log.Print("Sender is listening")
	}()

	time.Sleep(2 * time.Second)

	senderDht.Network = network_receiver
	receiverDht.Network = network_sender

	go func() {
		err := api.StartServer(receiverNode.IP+":"+fmt.Sprint(receiverPort), receiverNode)
		assert.NoError(t, err, "Failed to start API server")
	}()

	time.Sleep(2 * time.Second)

	go func() {
		err := api.StartServer(senderNode.IP+":"+fmt.Sprint(senderPort), senderNode)
		assert.NoError(t, err, "Failed to start API server")
	}()

	time.Sleep(2 * time.Second)

	key := "testkey"
	value := "testvalue"

	receiverKNode := dht.KNode{
		ID:   receiverNode.ID,
		IP:   receiverNode.IP,
		Port: receiverPort,
	}

	storeMessageResponse, err := senderDht.SendStoreMessage(key, value, receiverKNode)
	if err != nil {
		log.Print("Send store message error")
	}

	//cast storeMessageResponse to DHTSuccessMessage
	log.Print("Store message response msg typeXXXXXX:", storeMessageResponse.GetType())
	assert.Equal(t, message.DHT_SUCCESS, storeMessageResponse.GetType(), "The response message should be a success message")

	// Check if the value exists in the storage
	retrievedValue, _, err := receiverNode.DHT.GET(key)
	log.Print("Retrieved value:", retrievedValue)
	assert.NoError(t, err, "GET should not return an error")
	assert.Equal(t, value, retrievedValue, "The value retrieved should match the value stored")
}
Leave a Comment