Completed
Push — master ( d9da1e...a7554a )
by Tomaz
02:11
created

ParseDateStringActionTestCase   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 49
Duplicated Lines 0 %
Metric Value
wmc 4
dl 0
loc 49
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A assertTimestampMatchesWithDrift() 0 9 1
A test_run_success() 0 17 1
A test_run_invalid_date_string() 0 3 1
A assertTimestampMatches() 0 8 1
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
        # TODO: Uupstream library is broke, fix it
31
        #result = action.run(date_string='2013-05-12')
32
        #expected = datetime.datetime(2013, 5, 12)
33
        #expected = dt_to_timestamp(expected)
34
        #self.assertTimestampMatchesWithDrift(result, expected)
35
36
    def test_run_invalid_date_string(self):
37
        action = self.get_action_instance()
38
        self.assertRaises(ValueError, action.run, date_string='some invalid string')
39
40
    def assertTimestampMatches(self, actual_ts, expected_ts):
41
        """
42
        Custom function which asserts that the provided two timestamp match.
43
        """
44
        actual_ts = datetime.datetime.fromtimestamp(actual_ts)
45
        expected_ts = datetime.datetime.fromtimestamp(expected_ts)
46
47
        self.assertEqual(actual_ts, expected_ts)
48
49
    def assertTimestampMatchesWithDrift(self, actual_ts, expected_ts):
50
        """
51
        Custom assert function which allows actual result to drift from the expected one
52
        for +/- 1 second (this is to account for the time between the function runs).
53
54
        In addition to that, microseconds are stripped as well.
55
        """
56
        expected_timestamps = [expected_ts, (expected_ts + 1), (expected_ts - 1)]
57
        self.assertTrue(actual_ts in expected_timestamps)
58