add:添加使用catch2测试用例。

This commit is contained in:
taynpg 2025-04-12 21:58:53 +08:00
parent 49d6ad1974
commit 2793dab420
11 changed files with 26251 additions and 204 deletions

View File

@ -21,7 +21,7 @@
],
"visualizerFile": "${workspaceRoot}/.vscode/qt5.natvis",
"args": [
"-u", "0"
//"-u", "0"
]
},
"cmake.environment": {
@ -35,6 +35,7 @@
],
"cmake.options.statusBarVisibility": "visible",
"cmake.generator": "Ninja",
"cmake.ctestArgs": ["-V"],
"C_Cpp.default.compileCommands": "${workspaceRoot}/build/compile_commands.json",
"C_Cpp.default.cppStandard": "c++17",
"editor.inlayHints.enabled": "off",
@ -156,7 +157,8 @@
"cfenv": "cpp",
"cassert": "cpp",
"version": "cpp",
"resumable": "cpp"
"resumable": "cpp",
"stack": "cpp"
},
"makefile.configureOnOpen": false,
"C_Cpp.default.configurationProvider": "ms-vscode.cmake-tools"

11817
3rd/catch_amalgamated.cpp Normal file

File diff suppressed because it is too large Load Diff

14135
3rd/catch_amalgamated.hpp Normal file

File diff suppressed because it is too large Load Diff

View File

@ -59,6 +59,7 @@ add_subdirectory(tinyaes)
if (DEFINED USE_TRANSM_TEST)
message(STATUS "USE USE_TRANSM_TEST ${USE_TRANSM_TEST}")
include(CTest)
add_subdirectory(test)
endif()

View File

@ -1,7 +1,19 @@
cmake_minimum_required(VERSION 3.16)
project(test LANGUAGES CXX)
project(transm_test LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 17)
add_executable(test main.cxx)
target_link_libraries(test PRIVATE tinyaes trans_util)
set(TEST_SOURCES
../3rd/catch_amalgamated.cpp
assistant.h
assistant.cxx
)
add_executable(encry_correct_test EncryptCorrect.cxx ${TEST_SOURCES})
add_executable(encry_speed_test EncryptSpeed.cxx ${TEST_SOURCES})
target_link_libraries(encry_correct_test PRIVATE tinyaes trans_util)
target_link_libraries(encry_speed_test PRIVATE tinyaes trans_util)
enable_testing()
add_test(NAME EncryCorrectTest COMMAND encry_correct_test)
add_test(NAME EncrySpeedTest COMMAND encry_speed_test -s)

41
test/EncryptCorrect.cxx Normal file
View File

@ -0,0 +1,41 @@
#include <aes.hpp>
#include <catch_amalgamated.hpp>
#include <fstream>
#include <string>
#include <util.h>
bool correctness_test()
{
std::string key = "demokey";
uint8_t ik[32]{};
hash(key.c_str(), ik);
int offset = 16;
char* msg = new char[256]{};
std::shared_ptr<int> deleter(new int(), [msg](int* p) {
delete p;
delete[] msg;
});
char source[] = "hello world";
memset(msg, 0, 256);
auto len = std::snprintf(msg + offset, 256 - offset, "%s", source);
if (!encrypt(ik, (uint8_t*)msg, len + offset)) {
return false;
}
uint8_t ik2[32]{};
hash(key.c_str(), ik2);
if (!decrypt(ik2, (uint8_t*)msg, len + offset)) {
return false;
}
return std::memcmp(source, msg + offset, len) == 0;
}
TEST_CASE("transm encry part", "[encry]")
{
SECTION("correctness of encryption")
{
REQUIRE(correctness_test() == true);
}
}

185
test/EncryptSpeed.cxx Normal file
View File

@ -0,0 +1,185 @@
#include <aes.hpp>
#include <catch_amalgamated.hpp>
#include <fstream>
#include <string>
#include <util.h>
#include "assistant.h"
const size_t BLOCK_SIZE = 102400; // 100KB块大小
const size_t IV_SIZE = 16; // 随机值大小
struct SpeedRet {
std::string mode;
long long file_size;
long long encry_speed;
long long decry_speed;
bool verify;
};
bool test_speed(SpeedRet& ret)
{
std::string test_file("1.dat");
if (!random_file(test_file, 1024 * 1024 * 10)) {
std::cerr << "Failed to create test file" << std::endl;
return false;
}
ret.decry_speed = 0;
ret.encry_speed = 0;
ret.mode = "";
ret.verify = false;
std::shared_ptr<int> deleter(new int(1), [test_file](int* p) {
delete p;
if (fs::exists(test_file)) {
fs::remove(test_file);
}
});
if (!fs::exists(test_file)) {
std::cerr << "Input file not found: " << test_file << std::endl;
return false;
}
size_t file_size = fs::file_size(test_file);
ret.file_size = file_size / (1024 * 1024);
if (file_size == 0) {
std::cerr << "Input file is empty" << std::endl;
return false;
}
std::string key = "test_speed_key";
uint8_t ik[32]{};
hash(key.c_str(), ik);
fs::path decrypted_path = fs::path(test_file).replace_filename(
fs::path(test_file).stem().string() + "_decrypted" + fs::path(test_file).extension().string());
std::ofstream decrypted_file(decrypted_path, std::ios::binary);
if (!decrypted_file) {
std::cerr << "Failed to create decrypted file" << std::endl;
return false;
}
std::ifstream in_file(test_file, std::ios::binary);
if (!in_file) {
std::cerr << "Failed to open input file" << std::endl;
return false;
}
// 测试数据缓冲区(额外预留16字节空间)
std::vector<uint8_t> original_block(BLOCK_SIZE);
std::vector<uint8_t> processing_block(BLOCK_SIZE + IV_SIZE); // 加密/解密处理缓冲区
size_t total_bytes = 0;
size_t blocks_processed = 0;
bool verification_passed = true;
auto total_encrypt_time = std::chrono::microseconds(0);
auto total_decrypt_time = std::chrono::microseconds(0);
while (in_file) {
in_file.read(reinterpret_cast<char*>(original_block.data()), BLOCK_SIZE - IV_SIZE);
size_t bytes_read = in_file.gcount();
if (bytes_read == 0)
break;
memcpy(processing_block.data() + IV_SIZE, original_block.data(), bytes_read);
auto start_encrypt = std::chrono::high_resolution_clock::now();
if (!encrypt(ik, processing_block.data(), bytes_read + IV_SIZE)) {
std::cerr << "Encryption failed at block " << blocks_processed << std::endl;
verification_passed = false;
break;
}
auto end_encrypt = std::chrono::high_resolution_clock::now();
total_encrypt_time +=
std::chrono::duration_cast<std::chrono::microseconds>(end_encrypt - start_encrypt);
auto start_decrypt = std::chrono::high_resolution_clock::now();
if (!decrypt(ik, processing_block.data(), bytes_read + IV_SIZE)) {
std::cerr << "Decryption failed at block " << blocks_processed << std::endl;
verification_passed = false;
break;
}
auto end_decrypt = std::chrono::high_resolution_clock::now();
total_decrypt_time +=
std::chrono::duration_cast<std::chrono::microseconds>(end_decrypt - start_decrypt);
if (memcmp(original_block.data(), processing_block.data() + IV_SIZE, bytes_read) != 0) {
std::cerr << "Data mismatch at block " << blocks_processed << std::endl;
verification_passed = false;
break;
}
decrypted_file.write(reinterpret_cast<const char*>(processing_block.data() + IV_SIZE), bytes_read);
total_bytes += bytes_read;
blocks_processed++;
}
in_file.close();
decrypted_file.close();
#if !defined(NDEBUG) || defined(_DEBUG) || defined(DEBUG)
// Debug 模式
ret.mode = "Debug";
#else
// Release 模式
ret.mode = "Release";
#endif
// 计算吞吐量(只计算有效数据部分)
double encrypt_throughput =
(double)total_bytes / (1024 * 1024) / (total_encrypt_time.count() / 1000000.0);
double decrypt_throughput =
(double)total_bytes / (1024 * 1024) / (total_decrypt_time.count() / 1000000.0);
ret.encry_speed = encrypt_throughput;
ret.decry_speed = decrypt_throughput;
ret.verify = verification_passed;
fs::remove(decrypted_path);
return verification_passed;
}
bool correctness_test()
{
std::string key = "demokey";
uint8_t ik[32]{};
hash(key.c_str(), ik);
int offset = 16;
char* msg = new char[256]{};
std::shared_ptr<int> deleter(new int(), [msg](int* p) {
delete p;
delete[] msg;
});
char source[] = "hello world";
memset(msg, 0, 256);
auto len = std::snprintf(msg + offset, 256 - offset, "%s", source);
if (!encrypt(ik, (uint8_t*)msg, len + offset)) {
return false;
}
uint8_t ik2[32]{};
hash(key.c_str(), ik2);
if (!decrypt(ik2, (uint8_t*)msg, len + offset)) {
return false;
}
return std::memcmp(source, msg + offset, len) == 0;
}
TEST_CASE("transm encry part", "[encry]")
{
SECTION("speed of encryption")
{
SpeedRet ret{};
auto r = test_speed(ret);
UNSCOPED_INFO("Encryption mode: " << ret.mode << "");
UNSCOPED_INFO("FileSize: " << ret.file_size << " MB");
UNSCOPED_INFO("Encryption speed: " << ret.encry_speed << " MB/s");
UNSCOPED_INFO("Decryption speed: " << ret.decry_speed << " MB/s");
REQUIRE(r == true);
}
}

33
test/assistant.cxx Normal file
View File

@ -0,0 +1,33 @@
#include "assistant.h"
bool random_file(const std::string& file, size_t size)
{
if (file.empty() || size == 0) {
return false;
}
std::ofstream ofs(file, std::ios::binary | std::ios::trunc);
if (!ofs) {
return false;
}
std::random_device rd;
std::mt19937_64 gen(rd());
std::uniform_int_distribution<int> dis(0, 255);
const size_t buffer_size = 4096;
std::vector<unsigned char> buffer(buffer_size);
for (size_t remaining = size; remaining > 0;) {
size_t chunk = std::min(remaining, buffer_size);
for (size_t i = 0; i < chunk; ++i) {
buffer[i] = static_cast<unsigned char>(dis(gen));
}
if (!ofs.write(reinterpret_cast<const char*>(buffer.data()), chunk)) {
return false;
}
remaining -= chunk;
}
return true;
}

18
test/assistant.h Normal file
View File

@ -0,0 +1,18 @@
#ifndef ASSISTANT_H
#define ASSISTANT_H
#include <fstream>
#include <string>
#include <random>
#ifdef USE_BOOST
#include <boost/filesystem.hpp>
namespace fs = boost::filesystem;
#else
#include <filesystem>
namespace fs = std::filesystem;
#endif
bool random_file(const std::string& file, size_t size);
#endif // ASSISTANT_H

View File

@ -1,198 +0,0 @@
#include <aes.hpp>
#include <fstream>
#include <string>
#include <util.h>
#ifdef USE_BOOST
#include <boost/filesystem.hpp>
namespace fs = boost::filesystem;
#else
#include <filesystem>
namespace fs = std::filesystem;
#endif
const size_t BLOCK_SIZE = 102400; // 100KB块大小
const size_t IV_SIZE = 16; // 随机值大小
/*
Microsoft Windows 10 Professional (x64) Build 19045.5608 (22H2)
13th Gen Intel(R) Core(TM) i5-13500H 3200.0 MHz
Debug模式 tinyaes
=========================================
File size: 630239232 bytes (601.043 MB)
Effective block size: 102384 bytes
IV size: 16 bytes
Blocks processed: 6156
Total encryption time: 41887336 μs (14.349 MB/s)
Total decryption time: 41822620 μs (14.3712 MB/s)
Decrypted file: "D:\\1_decrypted.iso"
Data verification: PASSED
=========================================
Release模式 tinyaes
=========================================
File size: 630239232 bytes (601.043 MB)
Effective block size: 102384 bytes
IV size: 16 bytes
Blocks processed: 6156
Total encryption time: 8367460 μs (71.831 MB/s)
Total decryption time: 8150036 μs (73.7473 MB/s)
Decrypted file: "D:\\1_decrypted.iso"
Data verification: PASSED
=========================================
*/
void test_speed(const char* input_file)
{
// 检查输入文件
if (!fs::exists(input_file)) {
std::cerr << "Input file not found: " << input_file << std::endl;
return;
}
size_t file_size = fs::file_size(input_file);
if (file_size == 0) {
std::cerr << "Input file is empty" << std::endl;
return;
}
// 准备密钥
std::string key = "test_speed_key";
uint8_t ik[32]{};
hash(key.c_str(), ik);
// 准备解密后的输出文件
fs::path decrypted_path = fs::path(input_file)
.replace_filename(fs::path(input_file).stem().string() + "_decrypted" +
fs::path(input_file).extension().string());
std::ofstream decrypted_file(decrypted_path, std::ios::binary);
if (!decrypted_file) {
std::cerr << "Failed to create decrypted file" << std::endl;
return;
}
// 打开输入文件
std::ifstream in_file(input_file, std::ios::binary);
if (!in_file) {
std::cerr << "Failed to open input file" << std::endl;
return;
}
// 测试数据缓冲区(额外预留16字节空间)
std::vector<uint8_t> original_block(BLOCK_SIZE);
std::vector<uint8_t> processing_block(BLOCK_SIZE + IV_SIZE); // 加密/解密处理缓冲区
size_t total_bytes = 0;
size_t blocks_processed = 0;
bool verification_passed = true;
// 计时变量
auto total_encrypt_time = std::chrono::microseconds(0);
auto total_decrypt_time = std::chrono::microseconds(0);
while (in_file) {
// 读取原始数据块(注意实际读取量比BLOCK_SIZE少16字节)
in_file.read(reinterpret_cast<char*>(original_block.data()), BLOCK_SIZE - IV_SIZE);
size_t bytes_read = in_file.gcount();
if (bytes_read == 0)
break;
// 准备加密缓冲区(前16字节留给随机值)
memcpy(processing_block.data() + IV_SIZE, original_block.data(), bytes_read);
// 加密计时
auto start_encrypt = std::chrono::high_resolution_clock::now();
if (!encrypt(ik, processing_block.data(), bytes_read + IV_SIZE)) {
std::cerr << "Encryption failed at block " << blocks_processed << std::endl;
verification_passed = false;
break;
}
auto end_encrypt = std::chrono::high_resolution_clock::now();
total_encrypt_time +=
std::chrono::duration_cast<std::chrono::microseconds>(end_encrypt - start_encrypt);
// 解密计时(使用加密后的数据)
auto start_decrypt = std::chrono::high_resolution_clock::now();
if (!decrypt(ik, processing_block.data(), bytes_read + IV_SIZE)) {
std::cerr << "Decryption failed at block " << blocks_processed << std::endl;
verification_passed = false;
break;
}
auto end_decrypt = std::chrono::high_resolution_clock::now();
total_decrypt_time +=
std::chrono::duration_cast<std::chrono::microseconds>(end_decrypt - start_decrypt);
// 验证解密结果(比较解密后的数据部分)
if (memcmp(original_block.data(), processing_block.data() + IV_SIZE, bytes_read) != 0) {
std::cerr << "Data mismatch at block " << blocks_processed << std::endl;
verification_passed = false;
break;
}
// 写入解密后的数据(只写入有效数据部分)
decrypted_file.write(reinterpret_cast<const char*>(processing_block.data() + IV_SIZE), bytes_read);
total_bytes += bytes_read;
blocks_processed++;
}
// 关闭文件
in_file.close();
decrypted_file.close();
// 计算吞吐量(只计算有效数据部分)
double encrypt_throughput =
(double)total_bytes / (1024 * 1024) / (total_encrypt_time.count() / 1000000.0);
double decrypt_throughput =
(double)total_bytes / (1024 * 1024) / (total_decrypt_time.count() / 1000000.0);
// 输出结果
std::cout << "\nOptimized Block Encryption/Decryption Test\n";
std::cout << "=========================================\n";
std::cout << "File size: " << file_size << " bytes (" << (double)file_size / (1024 * 1024) << " MB)\n";
std::cout << "Effective block size: " << (BLOCK_SIZE - IV_SIZE) << " bytes\n";
std::cout << "IV size: " << IV_SIZE << " bytes\n";
std::cout << "Blocks processed: " << blocks_processed << "\n";
std::cout << "Total encryption time: " << total_encrypt_time.count() << " μs (" << encrypt_throughput
<< " MB/s)\n";
std::cout << "Total decryption time: " << total_decrypt_time.count() << " μs (" << decrypt_throughput
<< " MB/s)\n";
std::cout << "Decrypted file: " << decrypted_path << "\n";
std::cout << "Data verification: " << (verification_passed ? "PASSED" : "FAILED") << "\n";
std::cout << "=========================================\n";
// 如果验证失败,删除可能不正确的解密文件
if (!verification_passed) {
fs::remove(decrypted_path);
}
}
void base_test()
{
std::string key = "sss";
uint8_t ik[32]{};
hash(key.c_str(), ik);
int offset = 16;
char* msg = new char[256]{};
memset(msg, 0, 256);
auto len = std::snprintf(msg + offset, 256 - offset, "%s", "hello world");
std::cout << encrypt(ik, (uint8_t*)msg, len + offset) << std::endl;
std::cout << msg + offset << std::endl;
uint8_t ik2[32]{};
hash(key.c_str(), ik2);
std::cout << decrypt(ik2, (uint8_t*)msg, len + offset) << std::endl;
std::cout << msg + offset << std::endl;
delete[] msg;
}
int main()
{
test_speed("D:\\1.iso");
return 0;
}

View File

@ -324,7 +324,8 @@ void rdm(uint8_t* o, size_t size)
mt19937 + uniform_int_distribution
*/
std::random_device rd;
std::mt19937 gen(rd());
// std::mt19937 gen(rd());
std::mt19937_64 gen(rd());
std::uniform_int_distribution<int> dist(0, 255);
std::generate(o, o + size, [&]() { return static_cast<uint8_t>(dist(gen)); });
}