Add OOM unit test for QVarLengthArray
authorPeter Kümmel <syntheticpp@gmx.net>
Wed, 10 Oct 2012 18:08:10 +0000 (20:08 +0200)
committerThe Qt Project <gerrit-noreply@qt-project.org>
Tue, 6 Nov 2012 04:33:28 +0000 (05:33 +0100)
Change-Id: Idf22ee6747aca8f0322e68b71f2c32e9ea562d4c
Reviewed-by: Thiago Macieira <thiago.macieira@intel.com>
Reviewed-by: Jason McDonald <macadder1@gmail.com>
tests/auto/other/exceptionsafety/tst_exceptionsafety.cpp

index 979a0db..98f1e98 100644 (file)
 **
 ****************************************************************************/
 
+#include "qplatformdefs.h"
+#include <stdlib.h>
+
+void* internalMalloc(size_t bytes);
+#define malloc internalMalloc
+#include <QVarLengthArray>
+#undef malloc
 
 #include <QtTest/QtTest>
 
@@ -59,6 +66,7 @@ private slots:
     void exceptionLinkedList();
 //    void exceptionEventLoop();
 //    void exceptionSignalSlot();
+    void exceptionOOMQVarLengthArray();
 #endif
 };
 
@@ -788,6 +796,50 @@ void tst_ExceptionSafety::exceptionSignalSlot()
 }
 #endif
 
+
+static bool outOfMemory = false;
+void* internalMalloc(size_t bytes) { return outOfMemory ? 0 : malloc(bytes); }
+
+struct OutOfMemory
+{
+    OutOfMemory() { outOfMemory = true; }
+    ~OutOfMemory() { outOfMemory = false; }
+};
+
+void tst_ExceptionSafety::exceptionOOMQVarLengthArray()
+{
+#ifdef QT_NO_EXCEPTIONS
+    // it will crash by design
+    Q_STATIC_ASSERT(false);
+#else
+     QVarLengthArray<char> arr0;
+    int minSize = arr0.capacity();
+
+    // constructor throws
+    bool success = false;
+    try {
+        OutOfMemory oom;
+        QVarLengthArray<char> arr(minSize * 2);
+    } catch (const std::bad_alloc&) {
+        success = true;
+    }
+    QVERIFY(success);
+
+    QVarLengthArray<char> arr;
+
+    // resize throws
+    success = false;
+    try {
+        OutOfMemory oom;
+        arr.resize(minSize * 2);
+    } catch(const std::bad_alloc&) {
+        arr.resize(1);
+        success = true;
+    }
+    QVERIFY(success);
+#endif
+}
+
 #endif
 
 QTEST_MAIN(tst_ExceptionSafety)