Fix wrong cast in sf::Packet

Add unit tests
This commit is contained in:
Pawel Paruzel 2021-12-05 23:27:48 +01:00 committed by Lukas Dürrenberger
parent 6cf124db66
commit 11020363b1
3 changed files with 63 additions and 3 deletions

View File

@ -178,7 +178,7 @@ Packet& Packet::operator >>(Int32& data)
if (checkSize(sizeof(data)))
{
std::memcpy(&data, &m_data[m_readPos], sizeof(data));
data = static_cast<Int16>(ntohl(static_cast<uint32_t>(data)));
data = static_cast<Int32>(ntohl(static_cast<uint32_t>(data)));
m_readPos += sizeof(data);
}
@ -430,7 +430,7 @@ Packet& Packet::operator <<(Uint16 data)
////////////////////////////////////////////////////////////
Packet& Packet::operator <<(Int32 data)
{
Int32 toWrite = static_cast<Int16>(htonl(static_cast<uint32_t>(data)));
Int32 toWrite = static_cast<Int32>(htonl(static_cast<uint32_t>(data)));
append(&toWrite, sizeof(toWrite));
return *this;
}

View File

@ -33,9 +33,17 @@ if(SFML_BUILD_GRAPHICS)
sfml_add_test(test-sfml-graphics "${GRAPHICS_SRC}" sfml-graphics)
endif()
if(SFML_BUILD_NETWORK)
SET(NETWORK_SRC
"${SRCROOT}/CatchMain.cpp"
"${SRCROOT}/Network/Packet.cpp"
)
sfml_add_test(test-sfml-network "${NETWORK_SRC}" sfml-network)
endif()
# Automatically run the tests at the end of the build
add_custom_target(runtests ALL
DEPENDS test-sfml-system test-sfml-window test-sfml-graphics
DEPENDS test-sfml-system test-sfml-window test-sfml-graphics test-sfml-network
)
add_custom_command(TARGET runtests

View File

@ -0,0 +1,52 @@
#include <SFML/Network.hpp>
#include <catch.hpp>
#include <limits>
template <typename IntegerType>
static void testPacketStreamOperators(IntegerType expected)
{
sf::Packet packet;
packet << expected;
IntegerType received;
packet >> received;
CHECK(expected == received);
}
TEST_CASE("sf::Packet class", "[network]")
{
SECTION("Stream operators")
{
SECTION("Int8")
{
testPacketStreamOperators(sf::Int8(0));
testPacketStreamOperators(sf::Int8(1));
testPacketStreamOperators(std::numeric_limits<sf::Int8>::min());
testPacketStreamOperators(std::numeric_limits<sf::Int8>::max());
}
SECTION("Int16")
{
testPacketStreamOperators(sf::Int16(0));
testPacketStreamOperators(sf::Int16(1));
testPacketStreamOperators(std::numeric_limits<sf::Int16>::min());
testPacketStreamOperators(std::numeric_limits<sf::Int16>::max());
}
SECTION("Int32")
{
testPacketStreamOperators(sf::Int32(0));
testPacketStreamOperators(sf::Int32(1));
testPacketStreamOperators(std::numeric_limits<sf::Int32>::min());
testPacketStreamOperators(std::numeric_limits<sf::Int32>::max());
}
SECTION("Int64")
{
testPacketStreamOperators(sf::Int64(0));
testPacketStreamOperators(sf::Int64(1));
testPacketStreamOperators(std::numeric_limits<sf::Int64>::min());
testPacketStreamOperators(std::numeric_limits<sf::Int64>::max());
}
}
}