Короче, в чем дело: есть прога на C++, в которой реализовано шифрование и дешифрование русского текста шифром Виженера. Модуля всего три - заголовочник класса modAlphaCipher, его реализация и собственно main. Скорее всего говнокода в них немерено, так что не судите строго. Код прикреплю ниже, в т.ч юнит-тесты и Makefile. Теперь к сути: 1) Желтое - валится с ошибкой (на скрине), красное проходится _________________________________________________________________________________________________ 2) Красное - валится с ошибкой на скрине, желтое - ошибка компиляции, если компилировать в IDE, то открывается файл из либы UnitTest++ с кучей ошибок там Код: modAlphaCipher.h: #pragma once #include <vector> #include <string> #include <map> #include <locale> #include <iostream> #include <codecvt> class modAlphaCipher { private: std::wstring_convert<std::codecvt_utf8<wchar_t>, wchar_t> codec; std::wstring numAlpha = L"АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЬЫЪЭЮЯ"; std::map <char,int> alphaNum; //ассоциативный массив "номер по символу" std::vector <int> key; //ключ std::vector<int> convert(const std::wstring& s); //преобразование строка-вектор std::wstring convert(const std::vector<int>& v); //преобразование вектор-строка std::wstring getValidKey(const std::wstring & s); public: modAlphaCipher()=delete; modAlphaCipher(const std::wstring& skey); //конструктор для установки ключа std::wstring encrypt(const std::wstring& open_text); //зашифрование std::wstring decrypt(const std::wstring& cipher_text);//расшифрование std::wstring toValid(std::wstring& s); }; class cipher_error: public std::invalid_argument { public: explicit cipher_error (const std::string& what_arg): std::invalid_argument(what_arg) {} explicit cipher_error (const char* what_arg): std::invalid_argument(what_arg) {} }; C #pragma once #include <vector> #include <string> #include <map> #include <locale> #include <iostream> #include <codecvt> class modAlphaCipher { private: std::wstring_convert<std::codecvt_utf8<wchar_t>, wchar_t> codec; std::wstring numAlpha = L"АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЬЫЪЭЮЯ"; std::map <char,int> alphaNum; //ассоциативный массив "номер по символу" std::vector <int> key; //ключ std::vector<int> convert(const std::wstring& s); //преобразование строка-вектор std::wstring convert(const std::vector<int>& v); //преобразование вектор-строка std::wstring getValidKey(const std::wstring & s); public: modAlphaCipher()=delete; modAlphaCipher(const std::wstring& skey); //конструктор для установки ключа std::wstring encrypt(const std::wstring& open_text); //зашифрование std::wstring decrypt(const std::wstring& cipher_text);//расшифрование std::wstring toValid(std::wstring& s); }; class cipher_error: public std::invalid_argument { public: explicit cipher_error (const std::string& what_arg): std::invalid_argument(what_arg) {} explicit cipher_error (const char* what_arg): std::invalid_argument(what_arg) {} }; modAlphaCipher.cpp: #include "headers/modAlphaCipher.h" #include <vector> #include <locale> modAlphaCipher::modAlphaCipher(const std::wstring& skey) { for (unsigned i=0; i<numAlpha.size(); i++) { alphaNum[numAlpha[i]]=i; } key = convert(getValidKey(skey)); } std::wstring modAlphaCipher::encrypt(const std::wstring& open_text) { std::vector<int> work = convert(open_text); for(unsigned i=0; i < work.size(); i++) { work[i] = (work[i] + key[i % key.size()]) % alphaNum.size(); } return convert(work); } std::wstring modAlphaCipher::decrypt(const std::wstring& cipher_text) { std::vector<int> work = convert(cipher_text); for(unsigned i=0; i < work.size(); i++) { work[i] = (work[i] + alphaNum.size() - key[i % key.size()]) % alphaNum.size(); } return convert(work); } inline std::vector<int> modAlphaCipher::convert(const std::wstring& s) { std::vector<int> result; for(auto c:s) { result.push_back(alphaNum[c]); } return result; } inline std::wstring modAlphaCipher::convert(const std::vector<int>& v) { std::wstring result; for(auto i:v) { result.push_back(numAlpha[i]); } return result; } inline std::wstring modAlphaCipher::getValidKey(const std::wstring & s) { if (s.empty()) throw cipher_error("Empty key"); //std::wstring tmp = codec.to_bytes(s); std::wstring tmp(s); for (auto & c:tmp) { if (!iswalpha(c)) throw cipher_error("Invalid key"); if (iswlower(c)) c = toupper(c); } return tmp; } std::wstring modAlphaCipher::toValid(std::wstring& s) { //setup converter using convert_type = std::codecvt_utf8<wchar_t>; std::wstring_convert<convert_type, wchar_t> converter; if (s.empty()) throw cipher_error("Empty text"); //use converter (.to_bytes: wstr->str, .from_bytes: str->wstr) std::wstring tmp(s); std::string st = converter.to_bytes(s); for (auto & c:tmp) { if (!iswalpha(c)) throw cipher_error(("Text has invalid symbols: ") +st); if (iswlower(c)) c = towupper(c); } return tmp; } C #include "headers/modAlphaCipher.h" #include <vector> #include <locale> modAlphaCipher::modAlphaCipher(const std::wstring& skey) { for (unsigned i=0; i<numAlpha.size(); i++) { alphaNum[numAlpha[i]]=i; } key = convert(getValidKey(skey)); } std::wstring modAlphaCipher::encrypt(const std::wstring& open_text) { std::vector<int> work = convert(open_text); for(unsigned i=0; i < work.size(); i++) { work[i] = (work[i] + key[i % key.size()]) % alphaNum.size(); } return convert(work); } std::wstring modAlphaCipher::decrypt(const std::wstring& cipher_text) { std::vector<int> work = convert(cipher_text); for(unsigned i=0; i < work.size(); i++) { work[i] = (work[i] + alphaNum.size() - key[i % key.size()]) % alphaNum.size(); } return convert(work); } inline std::vector<int> modAlphaCipher::convert(const std::wstring& s) { std::vector<int> result; for(auto c:s) { result.push_back(alphaNum[c]); } return result; } inline std::wstring modAlphaCipher::convert(const std::vector<int>& v) { std::wstring result; for(auto i:v) { result.push_back(numAlpha[i]); } return result; } inline std::wstring modAlphaCipher::getValidKey(const std::wstring & s) { if (s.empty()) throw cipher_error("Empty key"); //std::wstring tmp = codec.to_bytes(s); std::wstring tmp(s); for (auto & c:tmp) { if (!iswalpha(c)) throw cipher_error("Invalid key"); if (iswlower(c)) c = toupper(c); } return tmp; } std::wstring modAlphaCipher::toValid(std::wstring& s) { //setup converter using convert_type = std::codecvt_utf8<wchar_t>; std::wstring_convert<convert_type, wchar_t> converter; if (s.empty()) throw cipher_error("Empty text"); //use converter (.to_bytes: wstr->str, .from_bytes: str->wstr) std::wstring tmp(s); std::string st = converter.to_bytes(s); for (auto & c:tmp) { if (!iswalpha(c)) throw cipher_error(("Text has invalid symbols: ") +st); if (iswlower(c)) c = towupper(c); } return tmp; } main.cpp: #include <iostream> #include <cctype> #include "headers/modAlphaCipher.h" #include <locale> using namespace std; std::wstring toValid(std::wstring& s) { //setup converter using convert_type = std::codecvt_utf8<wchar_t>; std::wstring_convert<convert_type, wchar_t> converter; if (s.empty()) throw cipher_error("Empty text"); //use converter (.to_bytes: wstr->str, .from_bytes: str->wstr) std::wstring tmp(s); std::string st = converter.to_bytes(s); for (auto & c:tmp) { if (!iswalpha(c)) throw cipher_error(("Text has invalid symbols: ") +st); if (iswlower(c)) c = towupper(c); } return tmp; } int main(int argc, char **argv) { locale loc("ru_RU.UTF-8"); locale::global(loc); wstring key; wstring text; unsigned op; try { wcout<<"Cipher ready. Input key: "; wcin>>key; //std::wstring vkey=toValid(key); wcout<<"Key loaded\n"; modAlphaCipher cipher(key); do { wcout<<"Cipher ready. Input operation (0-exit, 1-encrypt, 2-decrypt): "; wcin>>op; if (op > 2) { throw cipher_error("Illegal operation\n"); } else if (op >0) { wcout<<"Cipher ready. Input text: "; wcin>>text; std::wstring vtext=cipher.toValid(text); if (op==1) { wcout<<"Encrypted text: "<<cipher.encrypt(vtext)<<endl; } else { wcout<<"Decrypted text: "<<cipher.decrypt(vtext)<<endl; } } } while (op!=0); } catch (const cipher_error& e) { cerr << "Error: " << e.what() << endl; return 1; } catch (const exception& e) { cerr << "Exception: " << e.what() << endl; return 1; } //return 0; } C #include <iostream> #include <cctype> #include "headers/modAlphaCipher.h" #include <locale> using namespace std; std::wstring toValid(std::wstring& s) { //setup converter using convert_type = std::codecvt_utf8<wchar_t>; std::wstring_convert<convert_type, wchar_t> converter; if (s.empty()) throw cipher_error("Empty text"); //use converter (.to_bytes: wstr->str, .from_bytes: str->wstr) std::wstring tmp(s); std::string st = converter.to_bytes(s); for (auto & c:tmp) { if (!iswalpha(c)) throw cipher_error(("Text has invalid symbols: ") +st); if (iswlower(c)) c = towupper(c); } return tmp; } int main(int argc, char **argv) { locale loc("ru_RU.UTF-8"); locale::global(loc); wstring key; wstring text; unsigned op; try { wcout<<"Cipher ready. Input key: "; wcin>>key; //std::wstring vkey=toValid(key); wcout<<"Key loaded\n"; modAlphaCipher cipher(key); do { wcout<<"Cipher ready. Input operation (0-exit, 1-encrypt, 2-decrypt): "; wcin>>op; if (op > 2) { throw cipher_error("Illegal operation\n"); } else if (op >0) { wcout<<"Cipher ready. Input text: "; wcin>>text; std::wstring vtext=cipher.toValid(text); if (op==1) { wcout<<"Encrypted text: "<<cipher.encrypt(vtext)<<endl; } else { wcout<<"Decrypted text: "<<cipher.decrypt(vtext)<<endl; } } } while (op!=0); } catch (const cipher_error& e) { cerr << "Error: " << e.what() << endl; return 1; } catch (const exception& e) { cerr << "Exception: " << e.what() << endl; return 1; } //return 0; } unittest.cpp: #include <UnitTest++/UnitTest++.h> #include "headers/modAlphaCipher.h" #include <iostream> #include <locale> #include <codecvt> using namespace std; struct KeyAB_fixture { modAlphaCipher * pointer; KeyAB_fixture() { pointer = new modAlphaCipher(L"АБ"); } ~KeyAB_fixture() { delete pointer; } }; SUITE(KeyTest) { /*TEST(LargeLetters) { modAlphaCipher test(L"КОТЕЛ"); CHECK(true); } TEST(LargeAndSmallLetters) { modAlphaCipher test(L"КОТопес"); CHECK(true); }*/ TEST(EmptyKey) { CHECK_THROW(modAlphaCipher test(L""), cipher_error); } TEST(Key_with_a_space) { CHECK_THROW(modAlphaCipher test(L"кото пес"), cipher_error); } TEST(Key_with_invalid_characters_number) { CHECK_THROW(modAlphaCipher test(L"кото2пес"), cipher_error); } TEST(Key_with_invalid_characters_special_character) { CHECK_THROW(modAlphaCipher test(L"кото.пес"), cipher_error); } } /*SUITE(EncryptTest) { TEST_FIXTURE(KeyAB_fixture, LargeLetters) { CHECK_EQUAL(L"АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ", pointer->encrypt(L"АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ")); } TEST_FIXTURE(KeyAB_fixture, SmallLetters) { CHECK_EQUAL(L"АГВЕДЖЁИЗКЙМЛОНРПТСФУЦХШЧЪЩЬЫЮЭАЯ", pointer->encrypt(L"абвгдеёжзийклмнопрстуфхцчшщъыьэюя")); } TEST_FIXTURE(KeyAB_fixture,NumberInText) { wstring open_text = L"кора324мох"; CHECK_THROW(pointer->encrypt(open_text),cipher_error); } TEST_FIXTURE(KeyAB_fixture,TextWithSpecialSymbol) { wstring open_text = L"кора/мох"; CHECK_THROW(pointer->encrypt(open_text),cipher_error); } TEST_FIXTURE(KeyAB_fixture,TextWithASpace) { wstring open_text = L"кора мох"; CHECK_THROW(pointer->encrypt(open_text),cipher_error); } }*/ SUITE(DecryptTest) { TEST_FIXTURE(KeyAB_fixture, LargeLetters) { wstring cipher_text = L"АГВЕДЖЁИЗКЙМЛОНРПТСФУЦХШЧЪЩЬЫЮЭАЯ"; wstring result_correct = L"АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ"; CHECK_EQUAL(true, result_correct == pointer->decrypt(cipher_text)); } TEST_FIXTURE(KeyAB_fixture, Smallletters) { wstring cipher_text = L"агведжёизкймлонрптсфуцхшчъщьыюэая"; wstring result_correct = L"АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ"; CHECK_EQUAL(true, result_correct == pointer->decrypt(cipher_text)); } TEST_FIXTURE(KeyAB_fixture,LargeAndSmallLetters) { wstring cipher_text = L"ЗДраВстуЙТЕ"; wstring result_correct = L"ЗВРЮВПТСЙРЕ"; CHECK_EQUAL(true, result_correct == pointer->decrypt(cipher_text)); } } /*TEST_FIXTURE(KeyAB_fixture, EmptyText) { wstring cipher_text = L""; CHECK_THROW(pointer->decrypt(cipher_text),cipher_error); } TEST_FIXTURE(KeyAB_fixture,TextWithNumber) { wstring cipher_text = L"кора324мох"; CHECK_THROW(pointer->decrypt(cipher_text),cipher_error); } TEST_FIXTURE(KeyAB_fixture,TextWithSymbol) { wstring cipher_text = L"кора/мох"; CHECK_THROW(pointer->decrypt(cipher_text),cipher_error); } TEST_FIXTURE(KeyAB_fixture,TextWithASpace) { wstring cipher_text = L"Зкора мох"; CHECK_THROW(pointer->decrypt(cipher_text),cipher_error); } }*/ int main(int argc, char **argv) { return UnitTest::RunAllTests(); } C #include <UnitTest++/UnitTest++.h> #include "headers/modAlphaCipher.h" #include <iostream> #include <locale> #include <codecvt> using namespace std; struct KeyAB_fixture { modAlphaCipher * pointer; KeyAB_fixture() { pointer = new modAlphaCipher(L"АБ"); } ~KeyAB_fixture() { delete pointer; } }; SUITE(KeyTest) { /*TEST(LargeLetters) { modAlphaCipher test(L"КОТЕЛ"); CHECK(true); } TEST(LargeAndSmallLetters) { modAlphaCipher test(L"КОТопес"); CHECK(true); }*/ TEST(EmptyKey) { CHECK_THROW(modAlphaCipher test(L""), cipher_error); } TEST(Key_with_a_space) { CHECK_THROW(modAlphaCipher test(L"кото пес"), cipher_error); } TEST(Key_with_invalid_characters_number) { CHECK_THROW(modAlphaCipher test(L"кото2пес"), cipher_error); } TEST(Key_with_invalid_characters_special_character) { CHECK_THROW(modAlphaCipher test(L"кото.пес"), cipher_error); } } /*SUITE(EncryptTest) { TEST_FIXTURE(KeyAB_fixture, LargeLetters) { CHECK_EQUAL(L"АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ", pointer->encrypt(L"АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ")); } TEST_FIXTURE(KeyAB_fixture, SmallLetters) { CHECK_EQUAL(L"АГВЕДЖЁИЗКЙМЛОНРПТСФУЦХШЧЪЩЬЫЮЭАЯ", pointer->encrypt(L"абвгдеёжзийклмнопрстуфхцчшщъыьэюя")); } TEST_FIXTURE(KeyAB_fixture,NumberInText) { wstring open_text = L"кора324мох"; CHECK_THROW(pointer->encrypt(open_text),cipher_error); } TEST_FIXTURE(KeyAB_fixture,TextWithSpecialSymbol) { wstring open_text = L"кора/мох"; CHECK_THROW(pointer->encrypt(open_text),cipher_error); } TEST_FIXTURE(KeyAB_fixture,TextWithASpace) { wstring open_text = L"кора мох"; CHECK_THROW(pointer->encrypt(open_text),cipher_error); } }*/ SUITE(DecryptTest) { TEST_FIXTURE(KeyAB_fixture, LargeLetters) { wstring cipher_text = L"АГВЕДЖЁИЗКЙМЛОНРПТСФУЦХШЧЪЩЬЫЮЭАЯ"; wstring result_correct = L"АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ"; CHECK_EQUAL(true, result_correct == pointer->decrypt(cipher_text)); } TEST_FIXTURE(KeyAB_fixture, Smallletters) { wstring cipher_text = L"агведжёизкймлонрптсфуцхшчъщьыюэая"; wstring result_correct = L"АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ"; CHECK_EQUAL(true, result_correct == pointer->decrypt(cipher_text)); } TEST_FIXTURE(KeyAB_fixture,LargeAndSmallLetters) { wstring cipher_text = L"ЗДраВстуЙТЕ"; wstring result_correct = L"ЗВРЮВПТСЙРЕ"; CHECK_EQUAL(true, result_correct == pointer->decrypt(cipher_text)); } } /*TEST_FIXTURE(KeyAB_fixture, EmptyText) { wstring cipher_text = L""; CHECK_THROW(pointer->decrypt(cipher_text),cipher_error); } TEST_FIXTURE(KeyAB_fixture,TextWithNumber) { wstring cipher_text = L"кора324мох"; CHECK_THROW(pointer->decrypt(cipher_text),cipher_error); } TEST_FIXTURE(KeyAB_fixture,TextWithSymbol) { wstring cipher_text = L"кора/мох"; CHECK_THROW(pointer->decrypt(cipher_text),cipher_error); } TEST_FIXTURE(KeyAB_fixture,TextWithASpace) { wstring cipher_text = L"Зкора мох"; CHECK_THROW(pointer->decrypt(cipher_text),cipher_error); } }*/ int main(int argc, char **argv) { return UnitTest::RunAllTests(); } Почему не работают тесты - так и не смог понять, надеюсь на помощь
Tntnikitik, привет! Я посмотрел на твой код и тесты. У меня есть несколько предложений, которые могут помочь исправить проблемы. 1) Ошибка компиляции в тесте "Key_with_a_space": Проблема возникает из-за использования пробела в ключе. В классе modAlphaCipher вы используете ассоциативный массив alphaNum, который не содержит пробел в качестве ключа. Поэтому при попытке создать объект modAlphaCipher с ключом, содержащим пробел, возникает ошибка. Я рекомендую добавить проверку на наличие пробела в ключе и выбрасывать исключение, если он присутствует. 2) Ошибка компиляции в тесте "Key_with_invalid_characters_number": Проблема возникает из-за использования цифры в ключе. Аналогично предыдущей проблеме, ассоциативный массив alphaNum не содержит цифры в качестве ключа. Рекомендую добавить проверку на наличие цифр в ключе и выбрасывать исключение, если они присутствуют. 3) Ошибка компиляции в тесте "Key_with_invalid_characters_special_character": Проблема возникает из-за использования специального символа в ключе. Ассоциативный массив alphaNum также не содержит специальных символов в качестве ключа. Рекомендую добавить проверку на наличие специальных символов в ключе и выбрасывать исключение, если они присутствуют. 4) Ошибка компиляции в тесте "DecryptTest": Проблема возникает из-за неправильного использования функции toValid в методе decrypt класса modAlphaCipher. Вместо передачи строки в функцию toValid, вы передаете объект wstring. Из-за этого возникает ошибка компиляции. Рекомендую передавать строку в функцию toValid, а не объект wstring. Попробуйте внести эти изменения и запустить тесты снова. Если у вас возникнут еще какие-либо проблемы, дайте мне знать, и я постараюсь помочь.