Source

cheesecake-service / tests / test_store.py

Full commit
  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
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
import doctest
import os
import shutil
import tempfile
import time
import unittest

from _test_case_with_spec import TestCaseWithSpec
from mock import Mock
import _path_setup

import store

from store import Store, CheesecakeScore, CheesecakeScoreFromValues, CheesecakeRun
from util import create_empty_files_in_directory
from util import set

################################################################################
## Test helpers.
################################################################################
def pluralize(word, count):
    """Pluralize word if count > 1.

    >>> pluralize('time', 1)
    'time'
    >>> pluralize('time', 2)
    'times'
    """
    if count < 2:
        return word

    return word + 's'

def returning(value):
    """Return a procedure that returns `value`.
    """
    return lambda *a: value

def args_are(*values):
    """Return a predicate that checks if its arguments are equal to `values`.

    >>> predicate = args_are(1, [], ())
    >>> predicate(1, [], ())
    True
    >>> predicate(1, [2], (3,))
    False
    """
    return lambda *a: a == values

def expectation_args_are(*values):
    """Return a predicate for use with mockSetExpectation.

    >>> mock = Mock()
    >>> mock.mockSetExpectation('call', expectation_args_are(1, 2, 3))
    >>> mock.call(1, 2, 3) # ok
    >>> mock.call('a', 'b', 'c')
    Traceback (most recent call last):
      ...
    AssertionError: Expectation failed: call('a', 'b', 'c')
    """
    return lambda mock, call, count: args_are(*values)(*call.params)

def check_calls_count(mock, name, exactly=None, min=None, max=None):
    """Assert that given method was called given number of times
    for this mock object.

    >>> m = Mock()
    >>> m.foo()
    >>> m.foo()
    >>> check_calls_count(m, 'foo', exactly=2) # ok
    >>> check_calls_count(m, 'foo', min=0, max=5) # ok
    >>> check_calls_count(m, 'foo', min=3)
    Traceback (most recent call last):
      ...
    AssertionError: Called foo less than 3 times
    >>> check_calls_count(m, 'foo', max=1)
    Traceback (most recent call last):
      ...
    AssertionError: Called foo more than 1 time
    """
    calls_number = len(filter(lambda c: c.name == name, mock.mockGetAllCalls()))

    if exactly is not None:
        assert calls_number == exactly, "Didn't call %s exactly %d %s as expected" % (name, exactly, pluralize('time', exactly))

    if min is not None:
        assert calls_number >= min, "Called %s less than %d %s" % (name, min, pluralize('time', min))

    if max is not None:
        assert calls_number <= max, "Called %s more than %d %s" % (name, max, pluralize('time', max))

class StoreMock(Store, Mock):
    """Behave like a Store with few exceptions:

    * don't call any of initialization methods (helps in testing each one
      of them separately), only set attributes
    * inherit from Mock, so we can set expectations on store object
    """
    def __init__(self):
        Mock.__init__(self)

        self.directory = '/log_directory'
        self.timestamp_file = 'timestamp_file'

        self.closed = False

        self._runs_by_release = {}
        self._runs_by_number = {}
        self._runs_failure = []
        self._runs_success = []

        self.releases_to_score = []
        self.score = {}
        self.timestamp = 0

def make_postgres_mock(execute=None,
                       fetchall=None,
                       fetchone=None,
                       commit=None,
                       close=None):
    cursor_mock = Mock({'execute': execute,
                        'fetchall': fetchall,
                        'fetchone': fetchone})

    connection_mock = Mock({'commit': commit,
                            'cursor': cursor_mock,
                            'close': close})

    mock = Mock({'connect': connection_mock})

    mock.cursor_mock = cursor_mock
    mock.connection_mock = connection_mock

    return (mock, connection_mock, cursor_mock)

################################################################################
## Data.
################################################################################

cheesecake_run_output = """py_pi_download .........................  50  (downloaded package Durus-3.4.1.tar.gz following 1 link from http://www.mems-exchange.org/software/durus/Durus-3.4.1.tar.gz)
unpack .................................  25  (package unpacked successfully)
unpack_dir .............................  15  (unpack directory is Durus-3.4.1 as expected)
setup.py ...............................  25  (setup.py found)
install ................................  50  (package installed in /tmp/cheesecakebJ2JTZ/tmp_install_Durus-3.4.1)
generated_files ........................   0  (0 .pyc and 0 .pyo files found)
---------------------------------------------
INSTALLABILITY INDEX (ABSOLUTE) ........ 165
INSTALLABILITY INDEX (RELATIVE) ........ 100  (165 out of a maximum of 165 points is 100%)

required_files ......................... 150  (4 files and 2 required directories found)
docstrings .............................  33  (found 121/369=32.79% objects with docstrings)
formatted_docstrings ...................   0  (found 6/369=1.63% objects with formatted docstrings)
---------------------------------------------
DOCUMENTATION INDEX (ABSOLUTE) ......... 183
DOCUMENTATION INDEX (RELATIVE) .........  53  (183 out of a maximum of 350 points is 53%)

pylint .................................  33  (pylint score was 6.59 out of 10)
use_test_framework .....................  30  (use one or more of known test frameworks)
pep8 ................................... -14  (pep8.py check: 6 error types, 2 warning types)
---------------------------------------------
CODE KWALITEE INDEX (ABSOLUTE) .........  63
CODE KWALITEE INDEX (RELATIVE) .........  79  (63 out of a maximum of 80 points is 79%)


=============================================
OVERALL CHEESECAKE INDEX (ABSOLUTE) .... 411
OVERALL CHEESECAKE INDEX (RELATIVE) ....  69  (411 out of a maximum of 595 points is 69%)
"""

successive_lognames = [
    '1-twill==0.8.5-success-42.log',
    '2-PIL==1.1.5-failure-42.log',
    '3-PIL==1.1.5-failure-42.log',
    '4-setuptools==0.6c1-success-42.log',
]

################################################################################
## Test classes.
################################################################################

class TestStoreInit(TestCaseWithSpec):
    context = "Method Store.__init__()"

    def test_recognizes_all_standard_indexes(self):
        score = CheesecakeScore(cheesecake_run_output)

        assert score.installability.absolute == 165
        assert score.installability.relative == 100

        assert score.documentation.absolute == 183
        assert score.documentation.relative == 53

        assert score.code_kwalitee.absolute == 63
        assert score.code_kwalitee.relative == 79

        sub_scores_installability = {
            'py_pi_download': (50, 'downloaded package Durus-3.4.1.tar.gz following 1 link from http://www.mems-exchange.org/software/durus/Durus-3.4.1.tar.gz'),
            'unpack': (25, 'package unpacked successfully'),
            'unpack_dir': (15, 'unpack directory is Durus-3.4.1 as expected'), 
            'setup.py': (25, 'setup.py found'), 
            'install': (50, 'package installed in /tmp/cheesecakebJ2JTZ/tmp_install_Durus-3.4.1'),
            'generated_files': (0, '0 .pyc and 0 .pyo files found'),
        }

        sub_scores_documentation = {
            'required_files': (150, '4 files and 2 required directories found'),
            'docstrings': (33, 'found 121/369=32.79% objects with docstrings'),
            'formatted_docstrings': (0, 'found 6/369=1.63% objects with formatted docstrings'),
        }

        sub_scores_code_kwalitee = {
            'pylint': (33, 'pylint score was 6.59 out of 10'),
            'use_test_framework': (30, 'use one or more of known test frameworks'),
            'pep8': (-14, 'pep8.py check: 6 error types, 2 warning types'),
        }

        def check_subindices(main_index, expected_values):
            for expected_name in expected_values.keys():
                print "Checking if %s exist." % expected_name
                assert main_index.get_subindex(expected_name) is not None

            for sub in main_index.subindices:
                print "Trying %s: %d (%s)" % (sub.name, sub.value, sub.details)
                assert sub.value == expected_values[sub.name][0]
                assert sub.details == expected_values[sub.name][1]

        check_subindices(score.installability, sub_scores_installability)
        check_subindices(score.documentation, sub_scores_documentation)
        check_subindices(score.code_kwalitee, sub_scores_code_kwalitee)

class TestReadCheesecakeRuns(TestCaseWithSpec):
    context = "Method Store._read_cheesecake_runs()"

    def setUp(self):
        self.original_os_listdir = os.listdir

    def tearDown(self):
        os.listdir = self.original_os_listdir

    def test_doesnt_call_save_run_for_empty_log_directory(self):
        os.listdir = returning([])

        store = StoreMock()
        store._read_cheesecake_runs()

        check_calls_count(store, 'save_run', exactly=0)

    def test_calls_save_run_four_times_for_four_lognames_in_log_directory(self):
        os.listdir = returning(['1-twill==0.8.5-success-42.log',
                                '2-PIL==1.1.5-failure-42.log',
                                '3-PIL==1.1.5-failure-42.log',
                                '4-setuptools==0.6c1-success-42.log'])

        store = StoreMock()
        store._read_cheesecake_runs()

        check_calls_count(store, 'save_run', exactly=4)

    def test_calls_save_run_three_times_for_three_lognames_with_successive_numbers(self):
        os.listdir = returning(['12-rope==0.2-success-42.log',
                                '13-ctypes==1.0.0-failure-42.log',
                                '101-chimera==0.4.4-failure-42.log'])

        store = StoreMock()
        store._read_cheesecake_runs()

        check_calls_count(store, 'save_run', exactly=3)

    def test_ignores_files_that_doesnt_match_cheesecake_logfile_pattern(self):
        os.listdir = returning(['foobar',
                                '1-twill==0.8.5-success-42.log',
                                'some random file with spaces',
                                'different.log'])

        store = StoreMock()
        store._read_cheesecake_runs()

        check_calls_count(store, 'save_run', exactly=1)

    def test_calls_save_run_with_appropriate_cheesecake_run_object(self):
        os.listdir = returning(['1-twill==0.8.5-success-42.log'])

        def check_run(mock, call, count):
            run = call.getParam(0)
            return isinstance(run, CheesecakeRun) \
                   and run.number == 1 \
                   and run.package == 'twill' \
                   and run.version == '0.8.5' \
                   and run.result == 'success' \
                   and run.execution_time == 42

        store = StoreMock()
        store.mockSetExpectation('save_run', check_run)
        store._read_cheesecake_runs()

class TestRunsCount(TestCaseWithSpec):
    context = "Method Store._get_runs_count()"

    def setUp(self):
        self.original_os_listdir = os.listdir

    def tearDown(self):
        os.listdir = self.original_os_listdir

    def test_returns_one_for_no_runs(self):
        os.listdir = returning([])

        store = StoreMock()
        store._read_cheesecake_runs()

        self.assertEqual(store.runs_count, 1)

    def test_returns_five_for_four_successive_runs_1_2_3_and_4(self):
        os.listdir = returning(['1-twill==0.8.5-success-42.log',
                                '2-PIL==1.1.5-failure-42.log',
                                '3-PIL==1.1.5-failure-42.log',
                                '4-setuptools==0.6c1-success-42.log'])

        store = StoreMock()
        store._read_cheesecake_runs()

        self.assertEqual(store.runs_count, 5)

    def test_returns_102_for_three_runs_and_last_with_number_101(self):
        os.listdir = returning(['12-rope==0.2-success-42.log',
                                '13-ctypes==1.0.0-failure-42.log',
                                '101-chimera==0.4.4-failure-42.log'])

        store = StoreMock()
        store._read_cheesecake_runs()

        self.assertEqual(store.runs_count, 102)

class TestGetFailures(TestCaseWithSpec):
    context = "Method Store._get_failures()"

    def test_returns_empty_list_for_successive_lognames(self):
        os.listdir = returning(['12-rope==0.2-success-42.log',
                                '1-twill==0.8.5-success-42.log'])

        store = StoreMock()
        store._read_cheesecake_runs()

        self.assertEqual(store.failures, [])

    def test_returns_only_logs_with_failure_status(self):
        os.listdir = returning(['1-twill==0.8.5-success-42.log',
                                '2-PIL==1.1.5-failure-42.log',
                                '3-PIL==1.1.5-failure-42.log',
                                '4-setuptools==0.6c1-success-42.log'])

        store = StoreMock()
        store._read_cheesecake_runs()

        self.assertEqual(set(store.failures),
                         set(['2-PIL==1.1.5-failure-42.log',
                              '3-PIL==1.1.5-failure-42.log']))

class TestReleasesToScore(TestCaseWithSpec):
    context = "Attribute Store.releases_to_score"

    def setUp(self):
        self.original_store_psycopg = store.psycopg

    def tearDown(self):
        store.psycopg = self.original_store_psycopg

    def test_is_empty_when_database_table_is_empty(self):
        store.psycopg = make_postgres_mock(fetchall=[])[0]

        store_mock = StoreMock()
        store_mock._init_database()
        store_mock._read_releases_to_score()

        self.assertEqual(store_mock.releases_to_score, [])

    def test_is_preserved_in_a_database(self):
        psycopg_mock, connection_mock, cursor_mock = make_postgres_mock()
        store.psycopg = psycopg_mock

        store_mock = StoreMock()
        store_mock._init_database()
        store_mock.releases_to_score = [
            ('cheesecake', '0.6'),
            ('cheesecake', '0.7'),
            ('twill', '0.8.5'),
        ]

        # Table should be cleaned first...
        cursor_mock.mockSetExpectation('execute',
                                       expectation_args_are('DELETE FROM releases_to_score', ()),
                                       at=1)
        # ...then filled with entries.
        cursor_mock.mockSetExpectation('execute',
                                       expectation_args_are('INSERT INTO releases_to_score VALUES (%s, %s)', ('cheesecake', '0.6')),
                                       at=2)
        cursor_mock.mockSetExpectation('execute',
                                       expectation_args_are('INSERT INTO releases_to_score VALUES (%s, %s)', ('cheesecake', '0.7')),
                                       at=3)
        cursor_mock.mockSetExpectation('execute',
                                       expectation_args_are('INSERT INTO releases_to_score VALUES (%s, %s)', ('twill', '0.8.5')),
                                       at=4)

        # Expectations are checked as we go.
        store_mock._save_releases_to_score()

    def test_can_be_initialized_from_database(self):
        list_of_releases = [('cheesecake', '0.6'),
                            ('cheesecake', '0.7'),
                            ('twill', '0.8.5')]

        psycopg_mock, connection_mock, cursor_mock = make_postgres_mock(fetchall=list_of_releases[:])
        store.psycopg = psycopg_mock

        store_mock = StoreMock()
        store_mock._init_database()

        cursor_mock.mockSetExpectation('execute',
                                       expectation_args_are('SELECT * FROM releases_to_score', ()),
                                       at=1)

        store_mock._read_releases_to_score()

        self.assertEqual(store_mock.releases_to_score, list_of_releases)

class TestCaseWithTestDatbase(unittest.TestCase):
    postgres_config = 'dbname=cheesecake_test'

    def setUp(self):
        store = Store(postgres_config=self.postgres_config)
        store.clean_all()
        store.close()

class SaveScoreTest(TestCaseWithTestDatbase):
    def test_save_score(self):
        """Test Store.save_score and Store._read_cheesecake_scores.
        """
        # We create Store instance and save sample results to the database.
        store_one = Store(postgres_config=self.postgres_config)
        durus_score_one = CheesecakeScore(cheesecake_run_output)
        store_one.save_score('Durus', '3.4.1', durus_score_one)

        # Then we create another Store instance and see if saved results were
        # preserved.
        store_two = Store(postgres_config=self.postgres_config)
        assert ('Durus', '3.4.1') in store_two.score
        durus_score_two = store_two.score[('Durus', '3.4.1')]

        assert durus_score_one.installability == durus_score_two.installability
        assert durus_score_one.documentation == durus_score_two.documentation
        assert durus_score_one.code_kwalitee == durus_score_two.code_kwalitee

class ReplaceReleaseScoreTest(TestCaseWithTestDatbase):
    def test_replace_release_score(self):
        """Test if Store.save_score handles assigning new scores for existing
        releases.
        """
        # Save Durus 3.4.1 score into database.
        store = Store(postgres_config=self.postgres_config)
        durus_score = CheesecakeScore(cheesecake_run_output)
        store.save_score('Durus', '3.4.1', durus_score)

        # Change documentation.absolute value to 184.
        durus_score.documentation.absolute = 184

        # Save new version of Durus score.
        store.save_score('Durus', '3.4.1', durus_score)
        store.close()

        # Create new Store instance and check if change was preserved.
        store = Store(postgres_config=self.postgres_config)
        assert store.score[('Durus', '3.4.1')].documentation.absolute == 184


class NumberOfFailuresTest(unittest.TestCase):
    def test_number_of_failures(self):
        runs_list = [
            CheesecakeRun(1, 'cheesecake', '0.6', 'failure'),
            CheesecakeRun(2, 'Durus', '3.4.1', 'success'),
            CheesecakeRun(3, 'cheesecake', '0.6', 'failure'),
            CheesecakeRun(4, 'cheesecake', '0.6', 'failure'),
        ]

        store = Store()
        for run in runs_list:
            store.save_run(run)

        assert 3 == store.number_of_failures('cheesecake', '0.6')

        # Add another failure and see if counter rises.
        store.save_run(CheesecakeRun(5, 'cheesecake', '0.6', 'failure'))
        assert 4 == store.number_of_failures('cheesecake', '0.6')

        # Add different package run.
        store.save_run(CheesecakeRun(6, 'twill', '0.8.5', 'success'))
        assert 4 == store.number_of_failures('cheesecake', '0.6')

        # Add different version of the same package with failure.
        store.save_run(CheesecakeRun(7, 'cheesecake', '0.7', 'failure'))
        assert 4 == store.number_of_failures('cheesecake', '0.6')

        # Add different version of the same package with success.
        store.save_run(CheesecakeRun(7, 'cheesecake', '0.7', 'success'))
        assert 4 == store.number_of_failures('cheesecake', '0.6')

        # Adding a success for this release should reset the counter.
        store.save_run(CheesecakeRun(7, 'cheesecake', '0.6', 'success'))
        assert 0 == store.number_of_failures('cheesecake', '0.6')


class DatabaseLogTest(TestCaseWithTestDatbase):
    def test_database_log(self):
        """Test Store.log and Store.get_messages.
        """
        store = Store(postgres_config=self.postgres_config)

        # Insert a message and make sure it was saved.
        store.log.debug("Hello world!")
        messages = [msg[2] for msg in store.get_messages()]
        assert len(messages) == 1
        assert "[DEBUG] Hello world!" in messages

        # Generate short delay, so that two messages get different timestamps.
        time.sleep(0.01)

        # Insert another message, then clear all but 1 message from
        # log and check that only the last one is present.
        store.log.info("Bye bye!")
        store.clean_messages(all_but=1)
        messages = [msg[2] for msg in store.get_messages()]
        assert len(messages) == 1
        assert "[DEBUG] Hello world!" not in messages
        assert "[INFO] Bye bye!" in messages


class CheesecakeScoreSerializeTest(unittest.TestCase):
    def test_cheesecake_score_serialize(self):
        """Test CheesecakeScore.serialize.
        """
        MainIndex = CheesecakeScore.MainIndex
        SubIndex = CheesecakeScore.SubIndex

        expected = {
            'INSTALLABILITY': (40,
                               10,
                               [('unpack', 25, 'package unpacked successfully'),
                               ('unpack_dir', 15, 'unpack directory is cheesecake-0.6 as expected')]),
            'DOCUMENTATION': (214,
                              20,
                              [('required_files', 180, '6 files and 2 required directories found'),
                              ('docstrings', 34, 'found 109/328=33.23% objects with docstrings'),
                              ('formatted_docstrings', 0, 'found 20/328=6.10% objects with formatted docstrings')]),
            'CODE_KWALITEE': (65,
                              30,
                              [('pylint', 35, 'pylint score was 7.00 out of 10'),
                              ('unit_tested', 30, 'has unit tests')])
        }

        installability_sub = [
            SubIndex('unpack', 25, 'package unpacked successfully'),
            SubIndex('unpack_dir''', 15, 'unpack directory is cheesecake-0.6 as expected'),
        ]
        documentation_sub = [
            SubIndex('required_files', 180, '6 files and 2 required directories found'),
            SubIndex('docstrings', 34, 'found 109/328=33.23% objects with docstrings'),
            SubIndex('formatted_docstrings', 0, 'found 20/328=6.10% objects with formatted docstrings'),
        ]
        code_kwalitee_sub = [
            SubIndex('pylint', 35, 'pylint score was 7.00 out of 10'),
            SubIndex('unit_tested', 30, 'has unit tests'),
        ]

        installability = MainIndex(40, 10, installability_sub)
        documentation = MainIndex(214, 20, documentation_sub)
        code_kwalitee = MainIndex(65, 30, code_kwalitee_sub)

        score = CheesecakeScoreFromValues(installability, documentation, code_kwalitee)

        serialized = score.serialize()

        assert serialized == expected

################################################################################
## Main.
################################################################################

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