File: testing.h

package info (click to toggle)
wxpython4.0 4.2.3%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 221,752 kB
  • sloc: cpp: 962,555; python: 230,573; ansic: 170,731; makefile: 51,756; sh: 9,342; perl: 1,564; javascript: 584; php: 326; xml: 200
file content (531 lines) | stat: -rw-r--r-- 16,624 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
/////////////////////////////////////////////////////////////////////////////
// Name:        wx/testing.h
// Purpose:     helpers for GUI testing
// Author:      Vaclav Slavik
// Created:     2012-08-28
// Copyright:   (c) 2012 Vaclav Slavik
// Licence:     wxWindows Licence
/////////////////////////////////////////////////////////////////////////////

#ifndef _WX_TESTING_H_
#define _WX_TESTING_H_

#include "wx/debug.h"
#include "wx/string.h"
#include "wx/modalhook.h"

class WXDLLIMPEXP_FWD_CORE wxMessageDialogBase;
class WXDLLIMPEXP_FWD_CORE wxFileDialogBase;

// ----------------------------------------------------------------------------
// testing API
// ----------------------------------------------------------------------------

// Don't include this code when building the library itself
#ifndef WXBUILDING

#include "wx/beforestd.h"
#include <algorithm>
#include <iterator>
#include <queue>
#include "wx/afterstd.h"
#include "wx/cpp.h"
#include "wx/dialog.h"
#include "wx/msgdlg.h"
#include "wx/filedlg.h"

#ifndef __WXDEBUG__
    #include "wx/crt.h"
#endif // !__WXDEBUG__

#include <typeinfo>

class wxTestingModalHook;

// This helper is used to construct the best possible name for the dialog of
// the given type using either wxRTTI or C++ RTTI.
inline
wxString
wxGetDialogClassDescription(const wxClassInfo *ci, const std::type_info& ti)
{
    // We prefer to use the name from wxRTTI as it's guaranteed to be readable,
    // unlike the name returned by type_info::name() which may need to be
    // demangled, but if wxRTTI macros were not used for this object, it's
    // better to return a not-very-readable-but-informative mangled name rather
    // than a readable but useless "wxDialog".
    if ( ci == wxCLASSINFO(wxDialog) )
    {
        return wxString::Format(wxASCII_STR("dialog of type \"%s\""),
                                wxASCII_STR(ti.name()));
    }

    // We consider that an unmangled name is clear enough to be used on its own.
    return ci->GetClassName();
}

// Non-template base class for wxExpectModal<T> (via wxExpectModalBase).
// Only used internally.
class wxModalExpectation
{
public:
    wxModalExpectation() : m_isOptional(false) {}
    virtual ~wxModalExpectation() {}

    wxString GetDescription() const
    {
        return m_description.empty() ? GetDefaultDescription() : m_description;
    }

    bool IsOptional() const { return m_isOptional; }

    virtual int Invoke(wxDialog *dlg) const = 0;

protected:
    // Override to return the default description of the expected dialog used
    // if no specific description for this particular expectation is given.
    virtual wxString GetDefaultDescription() const = 0;

    // User-provided description of the dialog, may be empty.
    wxString m_description;

    // Is this dialog optional, i.e. not required to be shown?
    bool m_isOptional;
};


// This template is specialized for some of the standard dialog classes and can
// also be specialized outside of the library for the custom dialogs.
//
// All specializations must derive from wxExpectModalBase<T>.
template<class T> class wxExpectModal;


/**
    Base class for the expectation of a dialog of the given type T.

    Test code can derive ad hoc classes from this class directly and implement
    its OnInvoked() to perform the necessary actions or derive wxExpectModal<T>
    and implement it once if the implementation of OnInvoked() is always the
    same, i.e. depends just on the type T.

    T must be a class derived from wxDialog and E is the derived class type,
    i.e. this is an example of using CRTP. The default value of E is fine in
    case you're using this class as a base for your wxExpectModal<>
    specialization anyhow but also if you don't use either Optional() or
    Describe() methods, as the derived class type is only needed for them.
 */
template<class T, class E = wxExpectModal<T> >
class wxExpectModalBase : public wxModalExpectation
{
public:
    typedef T DialogType;
    typedef E ExpectationType;


    // A note about these "modifier" methods: they return copies of this object
    // and not a reference to the object itself (after modifying it) because
    // this object is likely to be temporary and will be destroyed soon, while
    // the new temporary created by these objects is bound to a const reference
    // inside WX_TEST_IMPL_ADD_EXPECTATION() macro ensuring that its lifetime
    // is prolonged until we can check if the expectations were met.
    //
    // This is also the reason these methods must be in this class and use
    // CRTP: a copy of this object can't be created in the base class, which is
    // abstract, and the copy must have the same type as the derived object to
    // avoid slicing.
    //
    // Make sure you understand this comment in its entirety before considering
    // modifying this code.


    /**
        Returns a copy of the expectation where the expected dialog is marked
        as optional.

        Optional dialogs aren't required to appear, it's not an error if they
        don't.
     */
    ExpectationType Optional() const
    {
        ExpectationType e(*static_cast<const ExpectationType*>(this));
        e.m_isOptional = true;
        return e;
    }

    /**
        Sets a description shown in the error message if the expectation fails.

        Using this method with unique descriptions for the different dialogs is
        recommended to make it easier to find out which one of the expected
        dialogs exactly was not shown.
     */
    ExpectationType Describe(const wxString& description) const
    {
        ExpectationType e(*static_cast<const ExpectationType*>(this));
        e.m_description = description;
        return e;
    }

protected:
    virtual int Invoke(wxDialog *dlg) const wxOVERRIDE
    {
        DialogType *t = dynamic_cast<DialogType*>(dlg);
        if ( t )
            return OnInvoked(t);
        else
            return wxID_NONE; // not handled
    }

    /// Returns description of the expected dialog (by default, its class).
    virtual wxString GetDefaultDescription() const wxOVERRIDE
    {
        return wxGetDialogClassDescription(wxCLASSINFO(T), typeid(T));
    }

    /**
        This method is called when ShowModal() was invoked on a dialog of type T.

        @return Return value is used as ShowModal()'s return value.
     */
    virtual int OnInvoked(DialogType *dlg) const = 0;
};


// wxExpectModal<T> specializations for common dialogs:

template<class T>
class wxExpectDismissableModal
    : public wxExpectModalBase<T, wxExpectDismissableModal<T> >
{
public:
    explicit wxExpectDismissableModal(int id)
    {
        switch ( id )
        {
            case wxYES:
                m_id = wxID_YES;
                break;
            case wxNO:
                m_id = wxID_NO;
                break;
            case wxCANCEL:
                m_id = wxID_CANCEL;
                break;
            case wxOK:
                m_id = wxID_OK;
                break;
            case wxHELP:
                m_id = wxID_HELP;
                break;
            default:
                m_id = id;
                break;
        }
    }

protected:
    virtual int OnInvoked(T *WXUNUSED(dlg)) const wxOVERRIDE
    {
        return m_id;
    }

    int m_id;
};

template<>
class wxExpectModal<wxMessageDialog>
    : public wxExpectDismissableModal<wxMessageDialog>
{
public:
    explicit wxExpectModal(int id)
        : wxExpectDismissableModal<wxMessageDialog>(id)
    {
    }

protected:
    virtual wxString GetDefaultDescription() const wxOVERRIDE
    {
        // It can be useful to show which buttons the expected message box was
        // supposed to have, in case there could have been several of them.
        wxString details;
        switch ( m_id )
        {
            case wxID_YES:
            case wxID_NO:
                details = wxASCII_STR("wxYES_NO style");
                break;

            case wxID_CANCEL:
                details = wxASCII_STR("wxCANCEL style");
                break;

            case wxID_OK:
                details = wxASCII_STR("wxOK style");
                break;

            default:
                details.Printf(wxASCII_STR("a button with ID=%d"), m_id);
                break;
        }

        return wxASCII_STR("wxMessageDialog with ") + details;
    }
};

class wxExpectAny : public wxExpectDismissableModal<wxDialog>
{
public:
    explicit wxExpectAny(int id)
        : wxExpectDismissableModal<wxDialog>(id)
    {
    }
};

#if wxUSE_FILEDLG

template<>
class wxExpectModal<wxFileDialog> : public wxExpectModalBase<wxFileDialog>
{
public:
    wxExpectModal(const wxString& path, int id = wxID_OK)
        : m_path(path), m_id(id)
    {
    }

protected:
    virtual int OnInvoked(wxFileDialog *dlg) const wxOVERRIDE
    {
        dlg->SetPath(m_path);
        return m_id;
    }

    wxString m_path;
    int m_id;
};

#endif

// Implementation of wxModalDialogHook for use in testing, with
// wxExpectModal<T> and the wxTEST_DIALOG() macro. It is not intended for
// direct use, use the macro instead.
class wxTestingModalHook : public wxModalDialogHook
{
public:
    // This object is created with the location of the macro containing it by
    // wxTEST_DIALOG macro, otherwise it falls back to the location of this
    // line itself, which is not very useful, so normally you should provide
    // your own values.
    wxTestingModalHook(const char* file = NULL,
                       int line = 0,
                       const char* func = NULL)
        : m_file(file), m_line(line), m_func(func)
    {
        Register();
    }

    // Called to verify that all expectations were met. This cannot be done in
    // the destructor, because ReportFailure() may throw (either because it's
    // overridden or because wx's assertions handling is, globally). And
    // throwing from the destructor would introduce all sort of problems,
    // including messing up the order of errors in some cases.
    void CheckUnmetExpectations()
    {
        while ( !m_expectations.empty() )
        {
            const wxModalExpectation *expect = m_expectations.front();
            m_expectations.pop();
            if ( expect->IsOptional() )
                continue;

            ReportFailure
            (
                wxString::Format
                (
                    wxASCII_STR("Expected %s was not shown."),
                    expect->GetDescription()
                )
            );
            break;
        }
    }

    void AddExpectation(const wxModalExpectation& e)
    {
        m_expectations.push(&e);
    }

protected:
    virtual int Enter(wxDialog *dlg) wxOVERRIDE
    {
        while ( !m_expectations.empty() )
        {
            const wxModalExpectation *expect = m_expectations.front();
            m_expectations.pop();

            int ret = expect->Invoke(dlg);
            if ( ret != wxID_NONE )
                return ret; // dialog shown as expected

            // not showing an optional dialog is OK, but showing an unexpected
            // one definitely isn't:
            if ( !expect->IsOptional() )
            {
                ReportFailure
                (
                    wxString::Format
                    (
                        wxASCII_STR("%s was shown unexpectedly, expected %s."),
                        DescribeUnexpectedDialog(dlg),
                        expect->GetDescription()
                    )
                );
                return wxID_NONE;
            }
            // else: try the next expectation in the chain
        }

        ReportFailure
        (
            wxString::Format
            (
                wxASCII_STR("%s was shown unexpectedly."),
                DescribeUnexpectedDialog(dlg)
            )
        );
        return wxID_NONE;
    }

protected:
    // This method may be overridden to provide a better description of
    // (unexpected) dialogs, e.g. add knowledge of custom dialogs used by the
    // program here.
    virtual wxString DescribeUnexpectedDialog(wxDialog* dlg) const
    {
        // Message boxes are handled specially here just because they are so
        // ubiquitous.
        if ( wxMessageDialog *msgdlg = dynamic_cast<wxMessageDialog*>(dlg) )
        {
            return wxString::Format
                   (
                        wxASCII_STR("A message box \"%s\""),
                        msgdlg->GetMessage()
                   );
        }

        return wxString::Format
               (
                    wxASCII_STR("A %s with title \"%s\""),
                    wxGetDialogClassDescription(dlg->GetClassInfo(), typeid(*dlg)),
                    dlg->GetTitle()
               );
    }

    // This method may be overridden to change the way test failures are
    // handled. By default they result in an assertion failure which, of
    // course, can itself be customized.
    virtual void ReportFailure(const wxString& msg)
    {
#ifdef __WXDEBUG__
        wxFAIL_MSG_AT( msg,
                       m_file ? m_file : __FILE__,
                       m_line ? m_line : __LINE__,
                       m_func ? m_func : __WXFUNCTION__ );
#else // !__WXDEBUG__
        // We still need to report the failure somehow when wx asserts are
        // disabled.
        wxFprintf(stderr, wxASCII_STR("%s at %s:%d in %s()\n"),
                  msg,
                  wxASCII_STR(m_file ? m_file : __FILE__),
                  m_line ? m_line : __LINE__,
                  wxASCII_STR(m_func ? m_func : __WXFUNCTION__));
#endif // __WXDEBUG__/!__WXDEBUG__
    }

private:
    const char* const m_file;
    const int m_line;
    const char* const m_func;

    std::queue<const wxModalExpectation*> m_expectations;

    wxDECLARE_NO_COPY_CLASS(wxTestingModalHook);
};


// Redefining this value makes it possible to customize the hook class,
// including e.g. its error reporting.
#ifndef wxTEST_DIALOG_HOOK_CLASS
    #define wxTEST_DIALOG_HOOK_CLASS wxTestingModalHook
#endif

#define WX_TEST_IMPL_ADD_EXPECTATION(pos, expect)                              \
    const wxModalExpectation& wx_exp##pos = expect;                            \
    wx_hook.AddExpectation(wx_exp##pos);

/**
    Runs given code with all modal dialogs redirected to wxExpectModal<T>
    hooks, instead of being shown to the user.

    The first argument is any valid expression, typically a function call. The
    remaining arguments are wxExpectModal<T> instances defining the dialogs
    that are expected to be shown, in order of appearance.

    Some typical examples:

    @code
    wxTEST_DIALOG
    (
        rc = dlg.ShowModal(),
        wxExpectModal<wxFileDialog>(wxGetCwd() + "/test.txt")
    );
    @endcode

    Sometimes, the code may show more than one dialog:

    @code
    wxTEST_DIALOG
    (
        RunSomeFunction(),
        wxExpectModal<wxMessageDialog>(wxNO),
        wxExpectModal<MyConfirmationDialog>(wxYES),
        wxExpectModal<wxFileDialog>(wxGetCwd() + "/test.txt")
    );
    @endcode

    Notice that wxExpectModal<T> has some convenience methods for further
    tweaking the expectations. For example, it's possible to mark an expected
    dialog as @em optional for situations when a dialog may be shown, but isn't
    required to, by calling the Optional() method:

    @code
    wxTEST_DIALOG
    (
        RunSomeFunction(),
        wxExpectModal<wxMessageDialog>(wxNO),
        wxExpectModal<wxFileDialog>(wxGetCwd() + "/test.txt").Optional()
    );
    @endcode

    @note By default, errors are reported with wxFAIL_MSG(). You may customize this by
          implementing a class derived from wxTestingModalHook, overriding its
          ReportFailure() method and redefining the wxTEST_DIALOG_HOOK_CLASS
          macro to be the name of this class.

    @note Custom dialogs are supported too. All you have to do is to specialize
          wxExpectModal<> for your dialog type and implement its OnInvoked()
          method.
 */
#ifdef HAVE_VARIADIC_MACROS

#define wxTEST_DIALOG(codeToRun, ...)                                          \
    {                                                                          \
        wxTEST_DIALOG_HOOK_CLASS wx_hook(__FILE__, __LINE__, __WXFUNCTION__);  \
        wxCALL_FOR_EACH(WX_TEST_IMPL_ADD_EXPECTATION, __VA_ARGS__)             \
        codeToRun;                                                             \
        wx_hook.CheckUnmetExpectations();                                      \
    }
#endif /* HAVE_VARIADIC_MACROS */

#endif // !WXBUILDING

#endif // _WX_TESTING_H_