File: test.py

package info (click to toggle)
apertium-apy 0.13.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 3,128 kB
  • sloc: python: 3,665; sh: 321; makefile: 47
file content (475 lines) | stat: -rwxr-xr-x 17,518 bytes parent folder | download
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
#!/usr/bin/python3
# coding=utf-8

import io
import json
import logging
import mimetypes
import os
import shlex
import shutil
import subprocess
import sys
import time
import unittest
import urllib.parse
import urllib.request
import uuid

from tornado.log import enable_pretty_logging
from tornado.testing import AsyncHTTPTestCase

base_path = os.path.join(os.path.abspath(os.path.dirname(__file__)), '..')
sys.path.append(base_path)
from apertium_apy.apy import check_utf8, parse_args, setup_application  # noqa: E402

logging.getLogger().setLevel(logging.DEBUG)

PORT = int(os.environ.get('APY_PORT', '2737'))  # TODO: consider tornado.testing.bind_unused_port and/or validating input
NONPAIRS = os.environ.get('NONPAIRS', '/l/a/languages')
INSTALLEDPAIRS = os.environ.get('INSTALLEDPAIRS', '/usr/share/apertium')

MAX_STARTUP_SECONDS = 10

check_utf8()
cli_args = shlex.split('-p {} -v2 -j1 -i3 -u1 -n1 -m3 -s "{}"  -- "{}"'.format(PORT, NONPAIRS, INSTALLEDPAIRS))
args = parse_args(cli_args=cli_args)
enable_pretty_logging()
application = setup_application(args)

server_handle = None


def setUpModule():  # noqa: N802
    global server_handle
    coverage_cli_args = []
    if shutil.which('coverage'):
        coverage_cli_args = shlex.split('coverage run --rcfile {}'.format(os.path.join(base_path, '.coveragerc')))
    else:
        logging.warning("Couldn't find `coverage` executable, not running server with coverage instrumentation!")
        for _ in range(3):
            time.sleep(1)
            print('.')
    server_handle = subprocess.Popen(coverage_cli_args + [os.path.join(base_path, 'apy.py')] + cli_args)  # TODO: print only on error?

    started = False
    waited = 0
    while not started and waited < MAX_STARTUP_SECONDS:
        try:
            urllib.request.urlopen('http://localhost:{}'.format(PORT))  # TODO: consider using sockets instead
            started = True
            logging.info('APy started on port {} with PID {}'.format(PORT, server_handle.pid))
        except urllib.error.URLError:  # type: ignore
            print('.', end='')
            waited += 1
            time.sleep(1)

    if not started:
        raise Exception('Starting APy failed after waiting for {} seconds'.format(MAX_STARTUP_SECONDS))


def tearDownModule():  # noqa: N802
    if server_handle:
        server_handle.terminate()  # don't kill so that coverage works


class BaseTestCase(AsyncHTTPTestCase):
    def get_app(self):
        return application

    def get_http_port(self):
        return PORT

    def fetch(self, path, params={}, **kwargs):  # type: ignore[override]
        if params:
            method = kwargs.get('method', 'GET')
            if method == 'GET':
                path += '?' + urllib.parse.urlencode(params)
            elif method == 'POST':
                if 'files' in kwargs:
                    boundary_code = uuid.uuid4().hex
                    boundary = '--{}'.format(boundary_code).encode()

                    headers = kwargs.get('headers', {})
                    headers['Content-Type'] = 'multipart/form-data; boundary={}'.format(boundary_code)
                    kwargs['headers'] = headers

                    body = io.BytesIO()

                    for param_name, param_value in params.items():
                        body.write(
                            boundary + b'\r\n' +
                            'Content-Disposition: form-data; name="{}"\r\n'.format(param_name).encode() + b'\r\n' +
                            param_value.encode() + b'\r\n',
                        )

                    for file_name, file_content in kwargs.pop('files').items():
                        mimetype = mimetypes.guess_type(file_name)[0] or 'application/octet-stream'
                        body.write(
                            boundary + b'\r\n' +
                            'Content-Disposition: form-data; name="file"; filename="{}"\r\n'.format(file_name).encode() +
                            'Content-Type: {}\r\n'.format(mimetype).encode() + b'\r\n' +
                            file_content + b'\r\n',
                        )

                    body.write(boundary + b'--\r\n')
                    kwargs['body'] = body.getvalue()
                else:
                    kwargs['body'] = kwargs.get('body', '') + urllib.parse.urlencode(params)

        return super().fetch(path, **kwargs)

    def fetch_json(self, path, params={}, **kwargs):
        expect_success = kwargs.pop('expect_success', True)
        response = self.fetch(path, params=params, **kwargs)

        body = None
        if expect_success:
            self.assertEqual(response.code, 200, msg='Request unsuccessful: {}'.format(response.body))

            body = json.loads(response.body.decode('utf-8'))
            if 'responseStatus' in body:
                self.assertEqual(body['responseStatus'], 200)

        return body or json.loads(response.body.decode('utf-8'))

# TODO: split the handler tests into another file


class TestRootHandler(BaseTestCase):
    def test_home_page(self):
        response = self.fetch('/')
        self.assertTrue('Apertium APy' in response.body.decode('utf-8'))


class TestListHandler(BaseTestCase):
    def test_list_pairs(self):
        response = self.fetch_json('/list', {'q': 'pairs'})
        self.assertIsNone(response['responseDetails'])
        self.assertEqual(response['responseStatus'], 200)
        expect = set(map(lambda x: frozenset(x.items()), [
            {'sourceLanguage': 'sme', 'targetLanguage': 'nob'},
            {'sourceLanguage': 'eng', 'targetLanguage': 'spa'},
            {'sourceLanguage': 'spa', 'targetLanguage': 'eng_US'},
            {'sourceLanguage': 'spa', 'targetLanguage': 'eng'},
        ]))
        response_data = set(map(lambda x: frozenset(x.items()), response['responseData']))
        self.assertTrue(response_data >= expect, '{} is missing one of {}'.format(response_data, expect))

    def test_list_generators(self):
        response = self.fetch_json('/list', {'q': 'generators'})
        expect = {'nno': 'nno-gener'}
        self.assertTrue(response.items() >= expect.items(), '{} is missing {}'.format(response, expect))

    def test_list_analyzers(self):
        response = self.fetch_json('/list', {'q': 'analyzers'})
        expect = {'nno': 'nno-morph'}
        self.assertTrue(response.items() >= expect.items(), '{} is missing {}'.format(response, expect))

    def test_list_taggers(self):
        response = self.fetch_json('/list', {'q': 'taggers'})
        expect = {'nno': 'nno-tagger'}
        self.assertTrue(response.items() >= expect.items(), '{} is missing {}'.format(response, expect))


class TestPerWordHandler(BaseTestCase):
    def test_per_word_nno(self):
        response = self.fetch_json('/perWord', {'lang': 'nno', 'modes': 'morph tagger', 'q': 'og ikkje'})
        expected = [
            {
                'input': 'og',
                'tagger': 'og<cnjcoo><clb>',
                'morph': [
                    'og<cnjcoo>',
                    'og<cnjcoo><clb>',
                ],
            },
            {
                'input': 'ikkje',
                'tagger': 'ikkje<adv>',
                'morph': [
                    'ikkje<adv>',
                ],
            },
            {
                'input': '.',
                'tagger': '.<sent><clb>',
                'morph': [
                    '.<sent><clb>',
                ],
            },
        ]
        self.assertEqual(response, expected)


class TestTranslateHandler(BaseTestCase):
    def fetch_translation(self, query, pair, **kwargs):
        params = kwargs.get('params', {})
        params.update({'q': query, 'langpair': pair})
        kwargs['params'] = params

        response = self.fetch_json('/translate', **kwargs)
        return response

    def test_valid_pair(self):
        response = self.fetch_translation('government', 'eng|spa')
        self.assertEqual(response['responseData']['translatedText'], 'Gobierno')

    def test_valid_pair_unknown(self):
        response = self.fetch_translation('notaword', 'eng|spa')
        self.assertEqual(response['responseData']['translatedText'], '*notaword')

        response = self.fetch_translation('notaword', 'eng|spa', params={'markUnknown': False})
        self.assertEqual(response['responseData']['translatedText'], 'notaword')

    def test_valid_giella_pair(self):
        response = self.fetch_translation('ja', 'sme|nob')
        self.assertEqual(response['responseData']['translatedText'], 'og')

    def test_valid_pair_post(self):
        response = self.fetch_translation('government', 'eng|spa', method='POST')
        self.assertEqual(response['responseData']['translatedText'], 'Gobierno')

    def test_valid_pair_jsonp(self):
        callback_fn_name = 'callback123456'
        response = self.fetch('/translate', params={
            'q': 'government',
            'langpair': 'eng|spa',
            'callback': callback_fn_name,
        })
        body_text = response.body.decode('utf-8')
        self.assertTrue(body_text.startswith(callback_fn_name))
        self.assertTrue(body_text.endswith(')'))
        body = json.loads(body_text[len(callback_fn_name) + 1:-1])
        self.assertEqual(body['responseData']['translatedText'], 'Gobierno')

    def test_invalid_pair(self):
        response = self.fetch_translation('ignored', 'typomode', expect_success=False)
        self.assertDictEqual(response, {
            'status': 'error',
            'code': 400,
            'message': 'Bad Request',
            'explanation': 'That pair is invalid, use e.g. eng|spa',
        })

    def test_missing_pair(self):
        response = self.fetch_translation('ignored', 'non|mod', expect_success=False)
        self.assertDictEqual(response, {
            'status': 'error',
            'code': 400,
            'message': 'Bad Request',
            'explanation': 'That pair is not installed',
        })


class TestTranslateWebpageHandler(BaseTestCase):
    def test_translate_webpage(self):
        response = self.fetch_json('/translatePage', params={
            'langpair': 'eng|spa',
            'url': 'http://example.org/',
            'markUnknown': 'no',
        })
        self.assertIn('literatura', response['responseData']['translatedText'])

    def test_translate_invalid_webpage(self):
        response = self.fetch_json('/translatePage', params={
            'langpair': 'eng|spa',
            'url': 'thisisnotawebsite',
        }, expect_success=False)
        self.assertEqual(response['status'], 'error')
        self.assertEqual(response['code'], 404)
        self.assertEqual(response['message'], 'Not Found')
        self.assertTrue(response['explanation'].startswith('Error 404 on fetching url: '))


class TestDocTranslateHandler(BaseTestCase):
    def test_translate_txt(self):
        response = self.fetch(
            '/translateDoc',
            method='POST',
            params={
                'langpair': 'eng|spa',
            },
            files={
                'test.txt': b'hello',
            },
        )
        self.assertEqual(response.body.decode('utf-8'), 'hola')

    def test_invalid_pair_translate(self):
        response = self.fetch_json(
            '/translateDoc',
            method='POST',
            expect_success=False,
            params={
                'langpair': 'typomode',
            },
        )
        self.assertDictEqual(response, {
            'status': 'error',
            'code': 400,
            'message': 'Bad Request',
            'explanation': 'That pair is invalid, use e.g. eng|spa',
        })

    def test_invalid_format_translate(self):
        response = self.fetch_json(
            '/translateDoc',
            method='POST',
            expect_success=False,
            params={
                'langpair': 'eng|spa',
            },
            files={
                'test.txt': b'\0',
            },
        )
        self.assertDictEqual(response, {
            'status': 'error',
            'code': 400,
            'message': 'Bad Request',
            'explanation': 'Invalid file type application/octet-stream',
        })

    def test_translate_too_large(self):
        response = self.fetch_json(
            '/translateDoc',
            method='POST',
            expect_success=False,
            params={
                'langpair': 'eng|spa',
            },
            files={
                'test.txt': b'0' * int(32E6 + 1),
            },
        )
        self.assertDictEqual(response, {
            'status': 'error',
            'code': 413,
            'message': 'Request Entity Too Large',
            'explanation': 'That file is too large',
        })


class TestAnalyzeHandler(BaseTestCase):
    def test_analyze(self):
        response = self.fetch_json('/analyze', {'q': 'ikkje', 'lang': 'nno'})
        self.assertEqual(response, [['ikkje/ikkje<adv>', 'ikkje']])

    def test_invalid_analyze(self):
        response = self.fetch_json('/analyze', {'q': 'ignored', 'lang': 'zzz'}, expect_success=False)
        self.assertDictEqual(response, {
            'status': 'error',
            'code': 400,
            'message': 'Bad Request',
            'explanation': 'That mode is not installed',
        })


class TestGenerateHandler(BaseTestCase):
    def test_generate(self):
        response = self.fetch_json('/generate', {'q': '^ja<ij>$', 'lang': 'nno'})
        self.assertEqual(response, [['ja', '^ja<ij>$']])

    def test_generate_single(self):
        response = self.fetch_json('/generate', {'q': 'ja<ij>', 'lang': 'nno'})
        self.assertEqual(response, [['ja', '^ja<ij>$']])

    def test_invalid_generate(self):
        response = self.fetch_json('/generate', {'q': 'ignored', 'lang': 'zzz'}, expect_success=False)
        self.assertDictEqual(response, {
            'status': 'error',
            'code': 400,
            'message': 'Bad Request',
            'explanation': 'That mode is not installed',
        })


class TestStatsHandler(BaseTestCase):
    def test_stats(self):
        response = self.fetch_json('/stats')
        data = response['responseData']
        self.assertGreater(data['uptime'], 0)
        for key in ['useCount', 'runningPipes', 'holdingPipes', 'periodStats']:
            self.assertIn(key, data)
        for period_key in ['charsPerSec', 'totChars', 'totTimeSpent', 'requests', 'ageFirstRequest']:
            self.assertIn(period_key, data['periodStats'])


class TestListLanguageNamesHandler(BaseTestCase):
    def test_english_lang_names_list(self):
        response = self.fetch_json('/listLanguageNames', params={'locale': 'eng'})
        self.assertEqual(response['en'], 'English')
        self.assertGreater(len(response.keys()), 50, msg='Should have at least 100 English language names')

    def test_limited_english_lang_names_list(self):
        response = self.fetch_json('/listLanguageNames', params={'locale': 'eng', 'languages': 'spa arg cat'})
        self.assertDictEqual(response, {
            'spa': 'Spanish',
            'arg': 'Aragonese',
            'cat': 'Catalan',
        })

    def test_no_locale_lang_names_list(self):
        response = self.fetch_json('/listLanguageNames')
        self.assertEqual(response['en'], 'English')

    def test_accept_languages_header_lang_names_list(self):
        response = self.fetch_json('/listLanguageNames', headers={
            'Accept-Language': 'fr-CH, fr;q=0.9, en;q=0.8, de;q=0.7, *;q=0.5',
        })
        self.assertEqual(response['en'], 'anglais')


class TestIdentifyLangHandler(BaseTestCase):
    def test_identify_lang(self):
        response = self.fetch_json('/identifyLang', {'q': 'ikkje'})
        self.assertAlmostEqual(response['nno'], 1.0)


class TestCoverageHandler(BaseTestCase):
    def test_coverage(self):
        response = self.fetch_json('/calcCoverage', {'q': 'ikkje notnno', 'lang': 'nno'})
        self.assertListEqual(response, [0.5])

    def test_no_query_coverage(self):
        response = self.fetch_json('/calcCoverage', {'q': '', 'lang': 'nno'}, expect_success=False)
        self.assertDictEqual(response, {
            'status': 'error',
            'code': 400,
            'message': 'Bad Request',
            'explanation': 'Missing q argument',
        })

    def test_invalid_mode_coverage(self):
        response = self.fetch_json('/calcCoverage', {'q': 'ignored', 'lang': 'xxx'}, expect_success=False)
        self.assertDictEqual(response, {
            'status': 'error',
            'code': 400,
            'message': 'Bad Request',
            'explanation': 'That mode is not installed',
        })


class TestPipeDebugHandler(BaseTestCase):
    def test_pipe_debug(self):
        response = self.fetch_json('/pipedebug', {'q': 'house', 'langpair': 'eng|spa'})
        self.assertEqual(response['responseStatus'], 200)

        pipeline = response['responseData']['pipeline']
        output = response['responseData']['output']
        self.assertEqual(len(pipeline) + 1, len(output))
        self.assertGreater(len(output), 10)

    def test_invalid_mode(self):
        response = self.fetch_json('/pipedebug', {'q': 'ignored', 'langpair': 'eng-spa'}, expect_success=False)
        self.assertDictEqual(response, {
            'status': 'error',
            'code': 400,
            'message': 'Bad Request',
            'explanation': 'That pair is invalid, use e.g. eng|spa',
        })


if __name__ == '__main__':
    unittest.main()