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
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
import doctest
import os
import shutil
import tempfile
import time
import unittest

from mock import Mock, ReturnValues
import _path_setup

import store

from store import Store, CheesecakeScore, CheesecakeScoreFromValues,\
  CheesecakeRun, DatabaseError
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

class OF_TYPE(object):
    def __init__(self, expected_type):
        self.type = expected_type

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

    Special OF_TYPE values can be used to mark expected argument type:
    >>> predicate = args_are(42, OF_TYPE(str))
    >>> predicate(42, 'hello')
    True
    >>> predicate(42, 123)
    False
    >>> predicate(42)
    False
    """
    def predicate(*args):
        if len(args) != len(values): return False
        for got, expected in zip(args, values):
            if isinstance(expected, OF_TYPE):
                if not isinstance(got, expected.type): return False
            else:
                if got != expected: return False
        return True

    return predicate

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))

def check_calls(mock, expectations):
    """Check that methods were called in given order and with given arguments.

    >>> m = Mock()
    >>> m.foo()
    >>> m.bar(1, 2)
    >>> m.baz('whatever')
    >>> check_calls(m, ['foo', 'bar', 'baz']) # ok
    >>> check_calls(m, ['foo', ('bar', args_are(1, 2)), ('baz', args_are(OF_TYPE(str)))]) # ok
    >>> check_calls(m, ['foo'])
    Traceback (most recent call last):
      ...
    AssertionError: Unexpected call to bar(1, 2)
    >>> check_calls(m, [('foo', args_are(1)), 'bar', 'baz'])
    Traceback (most recent call last):
      ...
    AssertionError: Expectation failed for method 'foo': got foo()
    """
    calls = mock.mockGetAllCalls()

    for i in xrange(max(len(expectations), len(calls))):
        assert i < len(expectations), "Unexpected call to %s" % calls[i]
        assert i < len(calls), "Expected call to '%s', got nothing instead" % \
               (isinstance(expectations[i], str) and expectations[i] or expectations[i][0])

        expect, call = expectations[i], calls[i]

        if isinstance(expect, str):
            method = expect
            predicate = returning(True)
        else:
            method, predicate = expect

        assert call.name == method, "Expected call to '%s', got %s" % (method, call)
        assert predicate(*call.params, **call.kwparams), "Expectation failed for method '%s': got %s" % (method, call)

class Copycat(object):
    def extract(self, klass, method):
        """Extract a `method` from given `klass` so it can be used on this object.

        >>> class A(object):
        ...    def inc(self, n):
        ...        return n + 1
        >>> p = Copycat()
        >>> p.extract(A, 'inc')(5)
        6
        """
        return lambda *args, **kwds: klass.__dict__[method](self, *args, **kwds)

    def copy_method(self, klass, method):
        """Copy a method from `klass` into this object.

        >>> class A(object):
        ...     def inc(self, n):
        ...         return n + 1
        >>> p = Copycat()
        >>> p.inc(11)
        Traceback (most recent call last):
          ...
        AttributeError: 'Copycat' object has no attribute 'inc'
        >>> p.copy_method(A, 'inc')
        >>> p.inc(11)
        12
        """
        self.__dict__[method] = self.extract(klass, method)

    def copy_methods(self, klass, *methods):
        """Copy methods from `klass` into this object.
        """
        for method in methods:
            self.copy_method(klass, method)

class CopycatMock(Mock, Copycat): pass

def make_store_mock(mock_values={}, cursor={}, db={}):
    mock = CopycatMock(mock_values, Store)

    mock.directory = '/log_directory'
    mock.timestamp_file = 'timestamp_file'
    mock.logname_regex = Store.logname_regex

    mock.closed = False

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

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

    mock.cursor = Mock(cursor)
    mock.db = Mock(db)

    return 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',
]

################################################################################
## Unit tests.
################################################################################

class TestStoreInit(unittest.TestCase):
    "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 TestCheesecakeScore(unittest.TestCase):
    "Class CheesecakeScore"

    def test_can_serialize_itself(self):
        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

class TestReadCheesecakeRuns(unittest.TestCase):
    "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_mock = make_store_mock()
        store_mock.extract(Store, '_read_cheesecake_runs')()

        check_calls_count(store_mock, '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_mock = make_store_mock()
        store_mock.extract(Store, '_read_cheesecake_runs')()

        check_calls_count(store_mock, '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_mock = make_store_mock()
        store_mock.extract(Store, '_read_cheesecake_runs')()

        check_calls_count(store_mock, '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_mock = make_store_mock()
        store_mock.extract(Store, '_read_cheesecake_runs')()

        check_calls_count(store_mock, '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(run):
            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_mock = make_store_mock()

        store_mock.extract(Store, '_read_cheesecake_runs')()

        check_calls(store_mock, [('save_run', check_run)])

class TestRunsCount(unittest.TestCase):
    "Method Store._get_runs_count()"

    def setUp(self):
        self.original_os_listdir = os.listdir
        self.store_mock = make_store_mock()
        self.store_mock.copy_methods(Store,
                                     '_read_cheesecake_runs',
                                     '_get_runs_count',
                                     'save_run')

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

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

        self.store_mock._read_cheesecake_runs()

        self.assertEqual(self.store_mock._get_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'])

        self.store_mock._read_cheesecake_runs()

        self.assertEqual(self.store_mock._get_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'])

        self.store_mock._read_cheesecake_runs()

        self.assertEqual(self.store_mock._get_runs_count(), 102)

class TestGetFailures(unittest.TestCase):
    "Method Store._get_failures()"

    def setUp(self):
        self.original_os_listdir = os.listdir
        self.store_mock = make_store_mock()
        self.store_mock.copy_methods(Store,
                                     '_map_to_lognames',
                                     '_read_cheesecake_runs',
                                     '_get_failures',
                                     'save_run')

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

    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'])

        self.store_mock._read_cheesecake_runs()

        self.assertEqual(self.store_mock._get_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'])

        self.store_mock._read_cheesecake_runs()

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

class TestReleasesToScore(unittest.TestCase):
    "Attribute Store.releases_to_score"

    def test_is_empty_when_database_table_is_empty(self):
        store_mock = make_store_mock(cursor={'fetchall': []})
        store_mock.extract(Store, '_read_releases_to_score')()

        self.assertEqual(store_mock.releases_to_score, [])

    def test_is_preserved_in_a_database(self):
        store_mock = make_store_mock()
        store_mock.releases_to_score = [
            ('cheesecake', '0.6'),
            ('cheesecake', '0.7'),
            ('twill', '0.8.5'),
        ]

        store_mock.extract(Store, '_save_releases_to_score')()

        check_calls(store_mock.cursor, [
            # Table should be cleaned first...
            ('execute', args_are('DELETE FROM releases_to_score', ())),
            # ...then filled with entries.
            ('execute', args_are('INSERT INTO releases_to_score VALUES (%s, %s)', ('cheesecake', '0.6'))),
            ('execute', args_are('INSERT INTO releases_to_score VALUES (%s, %s)', ('cheesecake', '0.7'))),
            ('execute', args_are('INSERT INTO releases_to_score VALUES (%s, %s)', ('twill', '0.8.5')))])

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

        store_mock = make_store_mock(cursor={'fetchall': list_of_releases[:]})

        # Call method we're interested in.
        store_mock.extract(Store, '_read_releases_to_score')()

        check_calls(store_mock.cursor, [
            ('execute', args_are('SELECT * FROM releases_to_score', ())),
            'fetchall'])
        self.assertEqual(store_mock.releases_to_score, list_of_releases)


class TestSaveScore(unittest.TestCase):
    "Method Store.save_score()"

    def test_saves_main_indexes_with_all_subindexes(self):
        store_mock = make_store_mock({'_save_main_index': ReturnValues(1,2,3),
                                      '_release_exists': False})

        durus_score = CheesecakeScore(cheesecake_run_output)

        # Pretend our mock is a Store class object.
        store_mock.extract(Store, 'save_score')('Durus', '3.4.1', durus_score)

        check_calls(store_mock, [
            # Should save main indexes first...
            ('_save_main_index', args_are(durus_score.installability)),
            ('_save_main_index', args_are(durus_score.documentation)),
            ('_save_main_index', args_are(durus_score.code_kwalitee)),
            # ...then check if release score already exists (it doesn't)...
            ('_release_exists', args_are('Durus', '3.4.1')),
            # ...and finally save new release score.
            ('_insert_score_for_release', args_are('Durus', '3.4.1', 1, 2, 3)),
            # Should use _add_score to keep Store up-to-date.
            ('_add_score', args_are('Durus', '3.4.1', durus_score))])

    def test_will_replace_old_score_with_new_one(self):
        store_mock = make_store_mock({'_save_main_index': ReturnValues(1,2,3),
                                      '_release_exists': True})

        durus_score = CheesecakeScore(cheesecake_run_output)

        store_mock.extract(Store, 'save_score')('Durus', '3.4.1', durus_score)

        check_calls(store_mock, [
            # Should save main indexes first...
            ('_save_main_index', args_are(durus_score.installability)),
            ('_save_main_index', args_are(durus_score.documentation)),
            ('_save_main_index', args_are(durus_score.code_kwalitee)),
            # ...then check if release score already exists (it does)...
            ('_release_exists', args_are('Durus', '3.4.1')),
            # ...then remove an old score...
            ('_remove_indices_for_release', args_are('Durus', '3.4.1')),
            # ...and finally save new release score.
            ('_insert_score_for_release', args_are('Durus', '3.4.1', 1, 2, 3)),
            # Should use _add_score to keep Store up-to-date.
            ('_add_score', args_are('Durus', '3.4.1', durus_score))])

class TestNumberOfFailures(unittest.TestCase):
    "Method Store.number_of_failures()"

    def setUp(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'),
        ]

        self.store_mock = make_store_mock()
        self.store_mock.copy_methods(Store,
                                'save_run',
                                'number_of_failures')

        for run in runs_list:
            self.store_mock.save_run(run)

    def test_counts_number_of_failures_for_a_release(self):
        assert 3 == self.store_mock.number_of_failures('cheesecake', '0.6')

    def test_rises_by_one_on_new_failure_of_this_release(self):
        self.store_mock.save_run(CheesecakeRun(5, 'cheesecake', '0.6', 'failure'))

        assert 4 == self.store_mock.number_of_failures('cheesecake', '0.6')

    def test_doesnt_mix_up_different_packages_failures(self):
        self.store_mock.save_run(CheesecakeRun(6, 'twill', '0.8.5', 'success'))

        assert 3 == self.store_mock.number_of_failures('cheesecake', '0.6')

    def test_doesnt_mix_up_different_versions_of_the_same_package(self):
        self.store_mock.save_run(CheesecakeRun(7, 'cheesecake', '0.7', 'failure'))

        assert 3 == self.store_mock.number_of_failures('cheesecake', '0.6')

    def test_ignores_success_runs_for_other_versions(self):
        self.store_mock.save_run(CheesecakeRun(7, 'cheesecake', '0.7', 'success'))

        assert 3 == self.store_mock.number_of_failures('cheesecake', '0.6')

    def test_is_zero_when_last_run_was_a_success(self):
        self.store_mock.save_run(CheesecakeRun(7, 'cheesecake', '0.6', 'success'))

        assert 0 == self.store_mock.number_of_failures('cheesecake', '0.6')

class TestStoreClass(unittest.TestCase):
    "Class Store"

    def test_will_throw_database_error_on_connection_error_during_init(self):
        old_psycopg_connect = store.psycopg.connect
        def raise_operational_exception(*a):
            raise store.psycopg.OperationalError
        store.psycopg.connect = raise_operational_exception

        self.assertRaises(DatabaseError, lambda: Store())

        store.psycopg.connect = old_psycopg_connect

################################################################################
## Functional tests.
################################################################################

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

    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 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

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

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