Completed
Pull Request — master (#543)
by
unknown
02:35
created

ParseDateStringActionTestCase   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 48
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
dl 0
loc 48
rs 10
c 0
b 0
f 0
wmc 4
1
import datetime
2
3
from st2tests.base import BaseActionTestCase
4
5
from lib.utils import dt_to_timestamp
6
from parse_date_string import ParseDateStringAction
7
8
9
class ParseDateStringActionTestCase(BaseActionTestCase):
10
    action_cls = ParseDateStringAction
11
12
    def test_run_success(self):
13
        action = self.get_action_instance()
14
15
        result = action.run(date_string='now')
16
        expected = datetime.datetime.utcnow()
17
        expected = dt_to_timestamp(expected)
18
        self.assertTimestampMatchesWithDrift(result, expected)
19
20
        result = action.run(date_string='1 hour ago')
21
        expected = (datetime.datetime.utcnow() - datetime.timedelta(hours=1))
22
        expected = dt_to_timestamp(expected)
23
        self.assertTimestampMatchesWithDrift(result, expected)
24
25
        result = action.run(date_string='3 days ago')
26
        expected = (datetime.datetime.utcnow() - datetime.timedelta(days=3))
27
        expected = dt_to_timestamp(expected)
28
        self.assertTimestampMatchesWithDrift(result, expected)
29
30
        result = action.run(date_string='2013-10-24')
31
        expected = datetime.datetime(2013, 10, 24)
32
        expected = dt_to_timestamp(expected)
33
        self.assertTimestampMatchesWithDrift(result, expected)
34
35
    def test_run_invalid_date_string(self):
36
        action = self.get_action_instance()
37
        self.assertRaises(ValueError, action.run, date_string='some invalid string')
38
39
    def assertTimestampMatches(self, actual_ts, expected_ts):
40
        """
41
        Custom function which asserts that the provided two timestamp match.
42
        """
43
        actual_ts = datetime.datetime.fromtimestamp(actual_ts)
44
        expected_ts = datetime.datetime.fromtimestamp(expected_ts)
45
46
        self.assertEqual(actual_ts, expected_ts)
47
48
    def assertTimestampMatchesWithDrift(self, actual_ts, expected_ts):
49
        """
50
        Custom assert function which allows actual result to drift from the expected one
51
        for +/- 1 second (this is to account for the time between the function runs).
52
53
        In addition to that, microseconds are stripped as well.
54
        """
55
        expected_timestamps = [expected_ts, (expected_ts + 1), (expected_ts - 1)]
56
        self.assertTrue(actual_ts in expected_timestamps)
57