xref: /aosp_15_r20/external/autotest/site_utils/count_jobs_unittest.py (revision 9c5db1993ded3edbeafc8092d69fe5de2ee02df7)
1#!/usr/bin/python3
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
7from __future__ import absolute_import
8from __future__ import division
9from __future__ import print_function
10
11from datetime import timedelta, datetime
12import unittest
13from unittest import mock
14
15import common
16from autotest_lib.frontend import setup_django_readonly_environment
17from autotest_lib.frontend import setup_test_environment
18from autotest_lib.frontend.afe import models
19from autotest_lib.site_utils import count_jobs
20from six.moves import range
21
22
23class TestCountJobs(unittest.TestCase):
24    """Tests the count_jobs script's functionality.
25    """
26
27    def setUp(self):
28        super(TestCountJobs, self).setUp()
29        setup_test_environment.set_up()
30
31
32    def tearDown(self):
33        super(TestCountJobs, self).tearDown()
34        setup_test_environment.tear_down()
35
36
37    def test_no_jobs(self):
38        """Initially, there should be no jobs."""
39        self.assertEqual(
40            0,
41            count_jobs.number_of_jobs_since(timedelta(days=999)))
42
43
44    def test_count_jobs(self):
45        """When n jobs are inserted, n jobs should be counted within a day range.
46
47        Furthermore, 0 jobs should be counted within 0 or (-1) days.
48        """
49        some_day = datetime.fromtimestamp(1450211914)  # a time grabbed from time.time()
50        class FakeDatetime(datetime):
51            """Always returns the same 'now' value"""
52            @classmethod
53            def now(self):
54                """Return a fake 'now', rather than rely on the system's clock."""
55                return some_day
56        with mock.patch.object(count_jobs, 'datetime', FakeDatetime):
57            for i in range(1, 24):
58                 models.Job(created_on=some_day - timedelta(hours=i)).save()
59                 for count, days in ((i, 1), (0, 0), (0, -1)):
60                     self.assertEqual(
61                        count,
62                        count_jobs.number_of_jobs_since(timedelta(days=days)))
63
64
65if __name__ == '__main__':
66    unittest.main()
67