Completed
Pull Request — master (#544)
by
unknown
09:52 queued 03:16
created

WebPageTestAction   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 53
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
dl 0
loc 53
rs 10
c 0
b 0
f 0
wmc 9
1
"""WebPageTest actions."""
2
3
import random
4
import requests
5
from st2actions.runners.pythonrunner import Action
6
7
__all__ = ['WebPageTestAction']
8
9
10
class WebPageTestAction(Action):
11
    def __init__(self, config):
12
        super(WebPageTestAction, self).__init__(config=config)
13
        self.wpt_url = config.get('wpt_url', 'http://webpagetest.org')
14
        self.key = config.get('key', None)
15
16
    def list_locations(self):
17
        """Return available locations."""
18
        params = {'f': 'json'}
19
        if self.key:
20
            params['k'] = self.key
21
        request = requests.get("{0}/getLocations.php".format(self.wpt_url),
22
                               params=params)
23
        locations = request.json()['data']
24
        return sorted(locations.keys())
25
26
    def request_test(self, domain, location):
27
        """
28
        Execute a test for the given domain at a specific location.
29
        Optional key is required for Google's public instance.
30
        """
31
        params = {'f': 'json', 'url': domain, 'location': location}
32
        if self.key:
33
            params['k'] = self.key
34
35
        request = requests.get("{0}/runtest.php".format(self.wpt_url),
36
                               params=params)
37
        return request.json()
38
39
    def get_test_results(self, test_id):
40
        """
41
        Retrieve test results.
42
        Optional key is required for Google's public instance.
43
        """
44
        params = {'test': test_id}
45
        if self.key:
46
            params['k'] = self.key
47
48
        request = requests.get("{0}/jsonResult.php".format(self.wpt_url),
49
                               params=params)
50
        return request.json()
51
52
    def test_random_location(self, domain):
53
        """
54
        Execute a test for the given domain at a random location.
55
        Optional key is required for Google's public instance.
56
        """
57
        locations = self.list_locations()
58
        test = self.request_test(domain, random.choice(locations))
59
        try:
60
            return test['data']['userUrl']
61
        except KeyError:
62
            return "Error: {0}".format(test)
63