Paul Hobbs | 29c37b3 | 2015-12-11 16:24:27 -0800 | [diff] [blame] | 1 | #! /usr/bin/python |
| 2 | |
| 3 | # Copyright 2015 The Chromium OS Authors. All rights reserved. |
| 4 | # Use of this source code is governed by a BSD-style license that can be |
| 5 | # found in the LICENSE file. |
| 6 | |
| 7 | from datetime import timedelta, datetime |
| 8 | import mock |
| 9 | import unittest |
| 10 | |
| 11 | import common |
| 12 | from autotest_lib.frontend import setup_django_readonly_environment |
| 13 | from autotest_lib.frontend import setup_test_environment |
| 14 | from autotest_lib.frontend.afe import models |
| 15 | from autotest_lib.site_utils import count_jobs |
| 16 | from django import test |
| 17 | |
| 18 | |
| 19 | class TestCountJobs(test.TestCase): |
| 20 | """Tests the count_jobs script's functionality. |
| 21 | """ |
| 22 | |
| 23 | def setUp(self): |
| 24 | super(TestCountJobs, self).setUp() |
| 25 | setup_test_environment.set_up() |
| 26 | |
| 27 | |
| 28 | def tearDown(self): |
| 29 | super(TestCountJobs, self).tearDown() |
| 30 | setup_test_environment.tear_down() |
| 31 | |
| 32 | |
| 33 | def test_no_jobs(self): |
| 34 | """Initially, there should be no jobs.""" |
| 35 | self.assertEqual( |
| 36 | 0, |
| 37 | count_jobs.number_of_jobs_since(timedelta(days=999))) |
| 38 | |
| 39 | |
| 40 | def test_count_jobs(self): |
| 41 | """When n jobs are inserted, n jobs should be counted within a day range. |
| 42 | |
| 43 | Furthermore, 0 jobs should be counted within 0 or (-1) days. |
| 44 | """ |
Paul Hobbs | 9145b4b | 2015-12-15 12:40:17 -0800 | [diff] [blame] | 45 | some_day = datetime.fromtimestamp(1450211914) # a time grabbed from time.time() |
Paul Hobbs | 29c37b3 | 2015-12-11 16:24:27 -0800 | [diff] [blame] | 46 | class FakeDatetime(datetime): |
| 47 | """Always returns the same 'now' value""" |
| 48 | @classmethod |
| 49 | def now(self): |
| 50 | """Return a fake 'now', rather than rely on the system's clock.""" |
Paul Hobbs | 9145b4b | 2015-12-15 12:40:17 -0800 | [diff] [blame] | 51 | return some_day |
Paul Hobbs | ebc3460 | 2015-12-16 14:52:48 -0800 | [diff] [blame] | 52 | with mock.patch.object(count_jobs, 'datetime', FakeDatetime): |
| 53 | for i in range(1, 24): |
Paul Hobbs | 9145b4b | 2015-12-15 12:40:17 -0800 | [diff] [blame] | 54 | models.Job(created_on=some_day - timedelta(hours=i)).save() |
Paul Hobbs | 29c37b3 | 2015-12-11 16:24:27 -0800 | [diff] [blame] | 55 | for count, days in ((i, 1), (0, 0), (0, -1)): |
| 56 | self.assertEqual( |
| 57 | count, |
| 58 | count_jobs.number_of_jobs_since(timedelta(days=days))) |
| 59 | |
| 60 | |
| 61 | if __name__ == '__main__': |
| 62 | unittest.main() |