Boost test expected throw - c++

I have a test on a code part that needs to throw an exception, but using BOOST_CHECK_THROW still crashes the test. Here is the test:
#include <boost/test/unit_test.hpp>
#include "tools/CQueueMessage.hpp"
class TestMessage
{
public:
std::string m_message1;
std::string m_message2;
std::string m_messageEmpty;
std::string m_messageEmptyJson;
TestMessage()
: m_message1("{\"photo\":{\"name\":\"pic\",\"extension\":\"jpg\"}}"),
m_message2("{\"photo\":{\"name\":\"pic\",\"extension\":\"png\"}}"),
m_messageEmpty(""), m_messageEmptyJson("{}") {}
~TestMessage() {}
};
BOOST_FIXTURE_TEST_CASE(message2send, TestMessage)
{
QueueMessage qmsg1(m_message1);
BOOST_CHECK_EQUAL(qmsg1.messageToBeSent(), "{\"photo\":{\"name\":\"pic\",\"extension\":\"jpg\"}}");
QueueMessage qmsg2(m_message2);
BOOST_CHECK_EQUAL(qmsg2.messageToBeSent(), "{\"photo\":{\"name\":\"pic\",\"extension\":\"png\"}}");
BOOST_CHECK_THROW(QueueMessage qmsg3(m_messageEmpty), QueueMessageException)
// QueueMessage qmsg4(m_messageEmptyJson);
}
The QueueMessage class constructor is throwing a QueueMessageException if the message is empty or if it is an empty json. My problem is that this test is printing:
Running 1 test case...
unknown location(0): fatal error in "message2send": std::exception: Bad message format
*** 1 failure detected in test suite "main"
*** Exited with return code: 201 ***
How can I verify that the exception is thrown?
This is the constructor:
QueueMessage(CString& messageIn)
{
std::stringstream ss;
ss << messageIn;
PTree pt;
json::read_json(ss, pt);
std::string photo = pt.get< std::string >("photo");
if (photo.empty())
{
throw QueueMessageException("Bad message format"); // in debugging it arrives here
}
}

My psychic debugging powers tell me that your constructor is NOT in fact throwing QueueMessageException. It looks like it (through the function message2send) is throwing std::exception or a different child of it.

Related

C++ bit7z : Exception thrown at ... in ... Microsoft C++ exception: bit7z::BitException at memory location 0x001AF440 & paths of directory and files

I'm trying to create a program that, on execution, zips a given directory. Most of my errors have been resolved and I am hopefully getting to the end of this, but I still have the issue of an exception being thrown and a question regarding the program. I code in C++20 and on Visual Studio 2019.
I've come across this exact error when debugging the program:
Exception thrown at 0x76820B42 in aixLogger.exe: Microsoft C++ exception: bit7z::BitException at memory location 0x001AF440.
I already checked with a breakpoint what code is giving me this error:
catch (const BitException& ex) {
ex.what(); //<-
}
The code runs otherwise and isn't giving me any error messages, the breakpoint activates on the line I marked with an arrow (not actually part of my code).
To eliminate further possible edits I will add the rest of my code as well:
main.cpp
#include <QCoreApplication>
#include <string>
#include <iostream>
#include <filesystem>
#include <bit7z.hpp>
#include "main.h"
#include <bitcompressor.hpp>
namespace fs = std::filesystem;
using namespace bit7z;
using namespace std;
int main(int argc, char* argv[])
{
QCoreApplication a(argc, argv);
try {
Bit7zLibrary lib{ L"7z.dll" };
BitCompressor compressor{ lib, BitFormat::Zip };
//vector< wstring > files = { L"aretz/Downloads/test" };
wstring dir = { L"D: / local / aretz / Programmierung / git - workplace / aixLogger / test /" } ;
wstring zip = { L"zippedtest.zip" };
compressor.compressDirectory(dir, zip);
}
catch (const BitException& ex) {
ex.what();
}
return a.exec();
}
void AIXLogger::CompressDir() {
/*try {
Bit7zLibrary lib{ L"7z.dll" };
BitCompressor compressor{ lib, BitFormat::Zip };
vector< wstring > files = { L"C:/Users/aretz/Downloads/test" };
wstring zip = { L"zippedtest.zip" };
compressor.compressFiles(files, zip);
}
catch (const BitException& ex) {
ex;
}*/
}
main.h
#pragma once
#include <qwidget.h>
#include <qobject.h>
#include <bit7z.hpp>
class AIXLogger : public QWidget
{
Q_OBJECT
public slots:
public:
void CompressDir();
};
I've currently commented out the function CompressDir() as I can't call it in my main since it gives me either a syntax error or tells me the identifier is undefined.
Syntax Error:
AIXLogger.CompressDir(); the dot is marked as the error
identifier is undefined:
CompressDir();
I don't know what exactly is causing the catch to thrown an exception. From other posts I suspected that my paths for the files and directories are at fault, but changing them or moving my test directory didn't help at all. Removing the try and catch lines from my codeblock only adds the same error message where Exception Thrown is being replaced by Unhandled Exception. Thanks to anyone who can help.
I already checked with a breakpoint what code is giving me this error:
catch (const BitException& ex) {
ex.what(); //<-
}
The code runs otherwise and isn't giving me any error messages
The code isn't giving you any error message since you're not doing anything with the information provided by the thrown exception.
You're simply calling ex.what() without, for example, printing the error message string it returns, e.g., via std::cout.
the breakpoint activates on the line I marked with an arrow (not actually
part of my code).
I don't know what exactly is causing the catch to thrown an exception. From other posts I suspected that my paths for the files and directories are at fault, but changing them or moving my test directory didn't help at all.
The ex.what() error message should give you more details about the actual issue you're having.
By the way, I'm the author of the bit7z library, and from my experience and looking at the code you posted, I can think of some possible causes (the most common ones):
The program could not find the 7z.dll library.
Please ensure that the DLL is in the same directory as the executable or in one of the default DLL search paths of Windows.
The program could not find the directory path to be compressed.
As before, make sure that the path exists.

Error: can't allocate region after creating an object

I'm learning various details of OOP in C++ and wrote that code. The purpose of that code is to toy with ctor-initializers and learn how to inirialize a reference that is a class attribute.
#include <string>
#include <iostream>
using namespace std;
class Corgi {
private:
const string nickname;
const string& rNickname;
public:
Corgi(const string& _nickname): nickname(nickname), rNickname(nickname) {}
};
int main() {
Corgi buddy("buddy");
return 0;
}
This code compiles, however, I get this error message when it runs:
Project(1343,0x7fff7b2f2000) malloc: *** mach_vm_map(size=140734714511360) failed (error code=3)
*** error: can't allocate region
*** set a breakpoint in malloc_error_break to debug
terminate called after throwing an instance of 'std::bad_alloc'
what(): std::bad_alloc
I don't understand why I get this error message and how I can fix that. So, why do I get it and how to fix that?
I appreciate any help.
Corgi(const string& _nickname): nickname(nickname), rNickname(nickname) {}
initializes member nickname with itself which is a problem as member nickname is at this point uninitialized.
A fix:
Corgi(const string& _nickname): nickname(_nickname), rNickname(nickname) {}
Live Demo on coliru
I considered also this:
Corgi(const string& nickname): nickname(nickname), rNickname(nickname) {}
which will work for proper initialization of Corgi::nickname (due to the scope rules) but it introduces a new issue for Corgi::rNickname (which is now initialized with a reference to the constructor argument).
For this case, correct would be:
Corgi(const string& nickname): nickname(nickname), rNickname(this->nickname) {}
Live Demo on coliru

Invalid Deployment Exception

When creating new class instance I get "A first chance exception of type 'System.Deployment.Application.InvalidDeploymentException' occurred in System.Deployment.dll".
It happens at:
PrinterSettings^ MyPS = gcnew PrinterSettings();
Everything works fine and I get a value I want.
Form1.cpp:
#include "stdafx.h"
#include "Form1.h"
#include "Print.h"
#include <iostream>
System::Void DPrint::Form1::Form1_Load(System::Object^ sender, System::EventArgs^ e)
{
PrinterSettings^ MyPS = gcnew PrinterSettings();
System::Windows::Forms::MessageBox::Show("From Class PrinterSettings: " + MyPS->IniFilePath());
}
Print.h:
#ifndef PRINT_H
#define PRINT_H
public ref class PrinterSettings
{
private:
System::String^ m_strPath;
public:
PrinterSettings()
{
m_strPath = System::Windows::Forms::Application::UserAppDataPath;
}
System::String^ IniFilePath() { return m_strPath; };
};
#endif
Any ideas what is going on? Thank you.
This is a "first chance" exception, meaning the debugger observes an exception is thrown that may be handled. In this case, it is likely the application is trying to determine how the app is installed, such as via ClickOnce, to determine what your User app path is.
See What causes an InvalidDeploymentException in a WPF application? for a good explanation.

Stack unwind procedure failing when throwing exception after calling a function that returns a structure.

I have posted two other questions earlier this week, about exceptions and why my program does not handle exceptions. I have 'undressed' my program from unnecesarry code, and here it is:
#include <string>
#include <stdexcept>
#include <iostream>
class some_class
{
public:
some_class(const some_class &);
some_class(const char *);
std::string m_id;
};
some_class::some_class(const char *p_id) :
m_id(p_id)
{
}
some_class::some_class(const some_class &p_that) :
m_id(p_that.m_id)
{
}
extern some_class return_a_struct(const char *p_id);
int run()
{
some_class l = return_a_struct("john");
throw std::runtime_error("something bad happened");
return 0;
}
extern "C" int main(int, char **)
{
try
{
run();
}
catch(const std::exception &p)
{
std::cout << p.what() << std::endl;
}
return 0;
}
some_class return_a_struct(const char *p_id)
{
return some_class(p_id);
}
The output should be:
somethingbad happened
According to the exception (std::runtime_error) I throw.
In run(), I call a function that returns some_class. The object returned is then copy-constructed into the object I assign it to. So far, so good. But then I throw the exception, and the program never reaches the catch handler in function main. It crashes with the following message:
This application has requested the Runtime to terminate it in an unusual way
Please contact the application's support team for more information.
If I ommit the call to return_a_struct() this doesn't happen.
Question is: Is this a bug in gcc (part of MinGW latest release running on Windows 7), or am I doing something wrong. Any work arounds?
GCC-options:
gcc -fexceptions -g3 test_case.cpp -l libstdc++ -o test_case.exe
g++ test_case.cpp -o test_case.exe

Testing exceptions with BOOST

I'm using boost test framework 1.47 and I'm having difficulties testing my exceptions
Here is my exception class
class VideoCaptureException : public std::exception
{
std::string m_Description;
public:
VideoCaptureException(const char* description)
{
m_Description = std::string(description);
}
VideoCaptureException(const std::string& description)
{
m_Description = description;
}
virtual ~VideoCaptureException() throw() {}
virtual const char* what() const throw()
{
return m_Description.c_str();
}
}
I'm trying to test code that simply throws this exception
BOOST_CHECK_THROW( source.StopCapture(), VideoCaptureException )
For some reason it doesn't work.
unknown location(0): fatal error in "testVideoCaptureSource": unknown type
testVideoCaptureSource.cpp(28): last checkpoint
What is it that I'm doing wrong?
After encountering this error myself, I have tracked it down to a silly, but easy-to-make mistake:
throw new VideoCaptureException( "uh-oh" );
will fail with that error message, while:
throw VideoCaptureException( "uh-oh" );
will succeed.
The new variant causes a pointer to an exception to be caught, rather than the exception itself. The boost library doesn't know what to do with this, so it just says "unknown type".
It would be nice if the library explained the situation properly, but hopefully anybody else hitting "fatal error: unknown type" will find this page and see how to fix it!