Uploaded image for project: 'Qt'
  1. Qt
  2. QTBUG-82309

Add QDebug::toString()

    XMLWordPrintable

Details

    • Suggestion
    • Resolution: Done
    • Not Evaluated
    • None
    • None
    • Core: Other
    • None
    • 658b9697f9d85d4ed294810b4f60bafdbdd8e247 (qt/qtbase/dev)

    Description

      Often I want to construct a useful message for test failures by including a textual representation of an object involved with the failure. Creating such a message is easy when using QDebug, because I can just use my existing operator<< for that object's type, but the QTest framework requires a string. This results in code like the following:

          if (!list.isEmpty()) {
              QString message;
              QDebug debug(&message);
              debug << "Expected list to be empty, but it still contains the following items:" << list;
              QFAIL(qPrintable(message));
          }
      

      This is even worse for checks that must be repeated over time, as there is no simple way to do the above test without the QTRY_* macros.

      What I recently did was define a toString() template function that simply stores the result of calling operator<< with the object and returns it:

          template <typename T>
          QString toString(const T &object) {
              QString buffer;
              QDebug stream(&buffer);
              stream << object;
              return buffer;
          }
      

      It can then be used like this:

      QTRY_VERIFY2(list.isEmpty(), qPrintable(QString::fromLatin1(
              "Expected list to be empty, but it still contains the following items: %1").arg(QtUtils::toString(list))));
      

      I think that this would be a really convenient addition for debug output in tests, and possibly other places where strings are required.

      QTest already has a toString API that is only used for printing types in failures in its macros, otherwise that could have also been a good place to add the proposed function.

      Attachments

        No reviews matched the request. Check your Options in the drop-down menu of this sections header.

        Activity

          People

            mitch_curtis Mitch Curtis
            mitch_curtis Mitch Curtis
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

            Dates

              Created:
              Updated:
              Resolved:

              Gerrit Reviews

                There are no open Gerrit changes