From 7c1d97a6ab4e5f487920a0d93c1276c0daefd083 Mon Sep 17 00:00:00 2001 From: Joshua Goins Date: Tue, 15 Apr 2025 15:05:14 -0400 Subject: [PATCH] Add new obscure qt blog post --- content/blog/obscure-qt5.md | 40 +++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 content/blog/obscure-qt5.md diff --git a/content/blog/obscure-qt5.md b/content/blog/obscure-qt5.md new file mode 100644 index 0000000..5f4283e --- /dev/null +++ b/content/blog/obscure-qt5.md @@ -0,0 +1,40 @@ +--- +title: "Obscure Qt: Testing log messages" +date: 2025-04-15 +draft: false +tags: +- Qt +series: +- Obscure Qt +summary: "I noticed that I kept searching for \"how do I check for log messages in Qt tests?\" online. I figure that is a good enough indicator for \"obscure\" and now deserves to be saved on my blog" +--- + +I noticed that I kept searching for "how do I check for log messages in Qt tests?" online. I figure that is a good enough indicator for obscurity[^1] and now deserves to be saved on my blog! + +The case that spurred this is me writing a bunch of fallible code recently, and I wanted to check if the log message is emitted. Since the message also dynamic, making sure it has the correct line number too. For reference, here is some sample code: + +```cpp +const auto node = childNode.firstChildElement(QStringLiteral("SomeNode")); +if (node.isNull()) { + qWarning() << "Missing for node at line" << childNode.lineNumber(); + return std::nullopt; +} +... +``` + +Checking if this returns `std::nullopt` is easy enough, but what about the log output? It turns out QTest has us covered here with [QTest::ignoreMessage](https://doc.qt.io/qt-6/qtest.html#ignoreMessage). Add it to your test case, and it will panic if the message is not emitted: + +```cpp +QTest::ignoreMessage(QtWarningMsg, "Missing for node at line 14"); +``` + +And if the message isn't emitted, it will complain in your test output: + +```shell +INFO : ConfigFileTest::scaleUpData() Did not receive message: "Missing for node at line 14" +FAIL! : ConfigFileTest::scaleUpData() Not all expected messages were received +``` + +However if the message is found, it _hides said message from the test output_ which is extremely useful too. Also useful to know is that there's [a RegExp overload](https://doc.qt.io/qt-6/qtest.html#ignoreMessage-1) if you don't want it to be as specific. + +[^1]: Out of pure curiosity, I checked the KDE repositories and there's only ~60 usages of this function. I hope to see more of this the next time I check!