Welcome to mirror list, hosted at ThFree Co, Russian Federation.

ActionTestCase.php « tests - github.com/roundcube/roundcubemail.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 5122d6bea788bcf7093ba9a89ca5974e444fb9b5 (plain)
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
<?php

/**
 * Test class to test rcmail_action_mail_index
 *
 * @package Tests
 */
class ActionTestCase extends PHPUnit\Framework\TestCase
{
    static $files = [];


    static function setUpBeforeClass(): void
    {
        // reset some interfering globals set in other tests
        $_SERVER['REQUEST_URI'] = '';

        $rcmail = rcmail::get_instance();
        $rcmail->load_gui();
    }

    static function tearDownAfterClass(): void
    {
        foreach (self::$files as $file) {
            unlink($file);
        }

        self::$files = [];

        $rcmail = rcmail::get_instance();
        $rcmail->shutdown();
    }

    public function setUp(): void
    {
        $_GET     = [];
        $_POST    = [];
        $_REQUEST = [];
    }

    /**
     * Initialize the testing suite
     */
    public static function init()
    {
        self::initSession();
        self::initDB();
        self::initUser();
        self::initStorage();
    }

    /**
     * Initialize "mocked" output class
     */
    protected static function initOutput($mode, $task, $action, $framed = false)
    {
        $rcmail = rcmail::get_instance();

        $rcmail->task = $task;
        $rcmail->action = $action;

        if ($mode == rcmail_action::MODE_AJAX) {
            return $rcmail->output = new OutputJsonMock();
        }

        $rcmail->output = new OutputHtmlMock($task, $framed);

        if ($framed) {
            $rcmail->comm_path .= '&_framed=1';
            $rcmail->output->set_env('framed', true);
        }

        $rcmail->output->set_env('task', $task);
        $rcmail->output->set_env('action', $action);
        $rcmail->output->set_env('comm_path', $rcmail->comm_path);
        $rcmail->output->set_charset(RCUBE_CHARSET);

        return $rcmail->output;
    }

    /**
     * Wipe and re-initialize database
     */
    public static function initDB($file = null)
    {
        $rcmail = rcmail::get_instance();
        $dsn    = rcube_db::parse_dsn($rcmail->config->get('db_dsnw'));
        $db     = $rcmail->get_dbh();

        if ($file) {
            self::loadSQLScript($db, $file);
            return;
        }

        if ($dsn['phptype'] == 'mysql' || $dsn['phptype'] == 'mysqli') {
            // drop all existing tables first
            $db->query("SET FOREIGN_KEY_CHECKS=0");
            $sql_res = $db->query("SHOW TABLES");
            while ($sql_arr = $db->fetch_array($sql_res)) {
                $table = reset($sql_arr);
                $db->query("DROP TABLE $table");
            }

            // init database with schema
            system(sprintf('cat %s %s | mysql -h %s -u %s --password=%s %s',
                realpath(INSTALL_PATH . '/SQL/mysql.initial.sql'),
                realpath(TESTS_DIR . 'src/sql/init.sql'),
                escapeshellarg($dsn['hostspec']),
                escapeshellarg($dsn['username']),
                escapeshellarg($dsn['password']),
                escapeshellarg($dsn['database'])
            ));
        }
        else if ($dsn['phptype'] == 'sqlite') {
            $db->closeConnection();
            // delete database file
            system(sprintf('rm -f %s', escapeshellarg($dsn['database'])));

            // load sample test data
            self::loadSQLScript($db, 'init');
        }
    }

    /**
     * Set the $rcmail->user property
     */
    public static function initUser()
    {
        $rcmail = rcmail::get_instance();
        $rcmail->set_user(new rcube_user(1));
    }

    /**
     * Set the $rcmail->session property
     */
    public static function initSession()
    {
        $rcmail = rcmail::get_instance();
        $rcmail->session = new rcube_session_php($rcmail->config);
    }

    /**
     * Set the $rcmail->storage property
     *
     * @return StorageMock The storage object
     */
    public static function initStorage()
    {
        $rcmail = rcmail::get_instance();
        $rcmail->storage = new StorageMock();

        return $rcmail->storage;
    }

    /**
     * Create a temp file
     */
    protected function createTempFile($content = '')
    {
        $file = rcube_utils::temp_filename('tests');

        if ($content !== '') {
            file_put_contents($file, $content);
        }

        self::$files[] = $file;

        return $file;
    }

    /**
     * Prepare fake file upload handling
     */
    protected function fakeUpload($name = '_file', $is_array = true, $error = 0)
    {
        $content = base64_decode(rcmail_output::BLANK_GIF);
        $file = [
            'name'     => 'test.gif',
            'type'     => 'image/gif',
            'tmp_name' => $this->createTempFile($content),
            'error'    => $error,
            'size'     => strlen($content),
            'id'       => 'i' . microtime(true),
        ];

        // Attachments handling plugins use move_uploaded_file() which does not work
        // here. We'll add a fake hook handler for our purposes.
        $rcmail = rcmail::get_instance();
        $rcmail->plugins->register_hook('attachment_upload', function($att) use ($file) {
            $att['status'] = true;
            $att['id']     = $file['id'];
            return $att;
        });

        $_FILES = [];

        if ($is_array) {
            $_FILES[$name] = [
                'name'     => [$file['name']],
                'type'     => [$file['type']],
                'tmp_name' => [$file['tmp_name']],
                'error'    => [$file['error']],
                'size'     => [$file['size']],
                'id'       => [$file['id']],
            ];
        }
        else {
            $_FILES[$name] = $file;
        }

        return $file;
    }

    /**
     * Create file upload record
     */
    protected function fileUpload($group)
    {
        $content = base64_decode(rcmail_output::BLANK_GIF);
        $file = [
            'name'     => 'test.gif',
            'type'     => 'image/gif',
            'size'     => strlen($content),
            'group'    => $group,
            'id'       => 'i' . microtime(true),
        ];

        // Attachments handling plugins use move_uploaded_file() which does not work
        // here. We'll add a fake hook handler for our purposes.
        $rcmail = rcmail::get_instance();
        $rcmail->plugins->register_hook('attachment_upload', function($att) use ($file) {
            $att['status'] = true;
            $att['id']     = $file['id'];
            return $att;
        });

        $rcmail->insert_uploaded_file($file);

        $upload = rcube::get_instance()->get_uploaded_file($file['id']);

        $this->assertTrue(is_array($upload));

        return $upload;
    }

    /**
     * Load an execute specified SQL script
     */
    protected static function loadSQLScript($db, $name)
    {
        // load sample test data
        // Note: exec_script() does not really work with these queries
        $sql = file_get_contents(TESTS_DIR . "src/sql/{$name}.sql");
        $sql = preg_split('/;\n/', $sql, -1, PREG_SPLIT_NO_EMPTY);

        foreach ($sql as $query) {
            $result = $db->query($query);
            if ($error = $db->is_error($result)) {
                rcube::raise_error($error, false, true);
            }
        }
    }

    /**
     * Call the action's run() method and handle exit exception
     */
    protected function runAndAssert($action, $expected_code, $args = [])
    {
        // Reset output in case we execute the method multiple times in a single test
        $rcmail = rcmail::get_instance();
        $rcmail->output->reset(true);

        // reset some static props
        setProperty($action, 'edit_form', null);

        try {
            StderrMock::start();
            $action->run($args);
            StderrMock::stop();
        }
        catch (ExitException $e) {
            $this->assertSame($expected_code, $e->getCode());
        }
        catch (Exception $e) {
            if ($e->getMessage() == 'Error raised' && $expected_code == OutputHtmlMock::E_EXIT) {
                return;
            }

            echo StderrMock::$output;
            throw $e;
        }
    }
}