Add new obscure qt blog post
All checks were successful
Deploy / Deploy Website (push) Successful in 31s
All checks were successful
Deploy / Deploy Website (push) Successful in 31s
This commit is contained in:
parent
02564eeee5
commit
7c1d97a6ab
1 changed files with 40 additions and 0 deletions
40
content/blog/obscure-qt5.md
Normal file
40
content/blog/obscure-qt5.md
Normal file
|
@ -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 <SomeNode> 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 <SomeNode> 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 <SomeNode> 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!
|
Loading…
Add table
Reference in a new issue