Skip to content
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions coresdk/src/test/unit_tests/unit_test_bitmap.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

#include "catch.hpp"

#include <string>

#include "types.h"
#include "graphics.h"
#include "resources.h"
Expand Down Expand Up @@ -128,3 +130,39 @@ TEST_CASE("bitmap bounding details can be retrieved", "[bitmap]")
}
free_bitmap(bmp);
}

TEST_CASE("bitmap filename can be retrieved", "[bitmap_filename]")
{
SECTION("returns correct filename for bitmap")
{
std::string expected_filename = "rocket_sprt.png";

// Load a bitmap
bitmap bmp = load_bitmap("rocket", expected_filename);
REQUIRE(bmp != nullptr);
REQUIRE(bitmap_valid(bmp));

// Extract filename
std::string filepath = bitmap_filename(bmp);
size_t idx = filepath.size() - expected_filename.size();
std::string filename = filepath.substr(idx, expected_filename.size());

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unsafe substring extraction

This code has a potential unsigned integer underflow if filepath is shorter than expected_filename:

size_t idx = filepath.size() - expected_filename.size();  // Can underflow!
std::string filename = filepath.substr(idx, expected_filename.size());

I would suggest do it this way:

std::string filepath = bitmap_filename(bmp);
REQUIRE(filepath.size() >= expected_filename.size());
std::string filename = filepath.substr(filepath.size() - expected_filename.size());
REQUIRE(filename == expected_filename);


REQUIRE(filename == expected_filename);
free_bitmap(bmp);
}

SECTION("returns empty string for null bitmap")
{
bitmap null_bmp = nullptr;
std::string filepath = bitmap_filename(null_bmp);
REQUIRE(filepath == "");
}

SECTION("returns empty string for newly created bitmap")
{
bitmap created_bmp = create_bitmap("new bitmap", 100, 100);
std::string filepath = bitmap_filename(created_bmp);
REQUIRE(filepath == "");
free_bitmap(created_bmp);
}
}