Browse Source

Add tests for events

Story: 2004549
Task: 28302
Change-Id: Id505116637ac66de349962c9f804ddaa14601475
Adrian Czarnecki 7 months ago
parent
commit
f1d457fc79

+ 35
- 0
monasca_tempest_tests/clients/event_api.py View File

@@ -0,0 +1,35 @@
1
+# Copyright 2019 FUJITSU LIMITED
2
+#
3
+# Licensed under the Apache License, Version 2.0 (the "License"); you may
4
+# not use this file except in compliance with the License. You may obtain
5
+# a copy of the License at
6
+#
7
+#      http://www.apache.org/licenses/LICENSE-2.0
8
+#
9
+# Unless required by applicable law or agreed to in writing, software
10
+# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11
+# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12
+# License for the specific language governing permissions and limitations
13
+# under the License.
14
+
15
+from tempest import clients
16
+
17
+from monasca_tempest_tests.services import elasticsearch_client
18
+from monasca_tempest_tests.services import events_api_client
19
+
20
+
21
+class Manager(clients.Manager):
22
+    def __init__(self, credentials=None):
23
+        super(Manager, self).__init__(credentials)
24
+
25
+        self.events_api_client = events_api_client.EventApiClient(
26
+            self.auth_provider,
27
+            'events',
28
+            None
29
+        )
30
+
31
+        self.events_search_client = elasticsearch_client.ElasticsearchClient(
32
+            self.auth_provider,
33
+            'events-search',
34
+            None
35
+        )

+ 2
- 2
monasca_tempest_tests/clients/log_api.py View File

@@ -14,8 +14,8 @@
14 14
 
15 15
 from tempest import clients
16 16
 
17
+from monasca_tempest_tests.services import elasticsearch_client
17 18
 from monasca_tempest_tests.services import log_api_v3_client
18
-from monasca_tempest_tests.services import log_search_client
19 19
 
20 20
 
21 21
 class Manager(clients.Manager):
@@ -28,7 +28,7 @@ class Manager(clients.Manager):
28 28
             None
29 29
         )
30 30
 
31
-        self.log_search_client = log_search_client.LogsSearchClient(
31
+        self.log_search_client = elasticsearch_client.ElasticsearchClient(
32 32
             self.auth_provider,
33 33
             'logs-search',
34 34
             None

monasca_tempest_tests/services/log_search_client.py → monasca_tempest_tests/services/elasticsearch_client.py View File

@@ -12,16 +12,19 @@
12 12
 # License for the specific language governing permissions and limitations
13 13
 # under the License.
14 14
 
15
+from oslo_config import cfg
15 16
 from oslo_serialization import jsonutils as json
16 17
 from six import PY3
17 18
 from tempest.lib.common import rest_client
18 19
 
20
+CONF = cfg.CONF
19 21
 
20
-class LogsSearchClient(rest_client.RestClient):
22
+
23
+class ElasticsearchClient(rest_client.RestClient):
21 24
     uri_prefix = "/elasticsearch"
22 25
 
23 26
     def __init__(self, auth_provider, service, region):
24
-        super(LogsSearchClient, self).__init__(
27
+        super(ElasticsearchClient, self).__init__(
25 28
             auth_provider,
26 29
             service,
27 30
             region,
@@ -49,7 +52,7 @@ class LogsSearchClient(rest_client.RestClient):
49 52
     def count_search_messages(self, message, headers):
50 53
         return len(self.search_messages(message, headers))
51 54
 
52
-    def search_messages(self, message, headers):
55
+    def search_messages(self, message, headers=None):
53 56
         uri = '_msearch'
54 57
         body = """
55 58
                {"index" : "*", "search_type" : "dfs_query_then_fetch"}
@@ -60,5 +63,30 @@ class LogsSearchClient(rest_client.RestClient):
60 63
         body = self.deserialize(body)
61 64
         return body['responses'][0].get('hits', {}).get('hits', [])
62 65
 
66
+    def search_event_by_event_type(self, event_type):
67
+        uri = '_msearch'
68
+        body = """
69
+               {"index" : "*", "search_type" : "dfs_query_then_fetch"}
70
+               {"query" : {"match" : {"event_type":" """ + event_type + """ "}}}
71
+        """
72
+        header = {'kbn-version': CONF.monitoring.kibana_version}
73
+        response, body = self.post(self._uri(uri), body, header)
74
+        self.expected_success(200, response.status)
75
+        body = self.deserialize(body)
76
+        return body['responses'][0].get('hits', {}).get('hits', [])
77
+
78
+    def search_event(self, event):
79
+        uri = '_msearch'
80
+        header = {'kbn-version': CONF.monitoring.kibana_version}
81
+        event = json.dumps(event)
82
+        body = """
83
+               {"index" : "*", "search_type" : "dfs_query_then_fetch"}
84
+               {"query" : {"match" : {"event":" """ + event + """ "}}}
85
+        """
86
+        response, body = self.post(self._uri(uri), body, header)
87
+        self.expected_success(200, response.status)
88
+        body = self.deserialize(body)
89
+        return body['responses'][0].get('hits', {}).get('hits', [])
90
+
63 91
     def _uri(self, url):
64 92
         return '{}/{}'.format(self.uri_prefix, url)

+ 34
- 0
monasca_tempest_tests/services/events_api_client.py View File

@@ -0,0 +1,34 @@
1
+# Copyright 2019 FUJITSU LIMITED
2
+#
3
+# Licensed under the Apache License, Version 2.0 (the "License"); you may
4
+# not use this file except in compliance with the License. You may obtain
5
+# a copy of the License at
6
+#
7
+#      http://www.apache.org/licenses/LICENSE-2.0
8
+#
9
+# Unless required by applicable law or agreed to in writing, software
10
+# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11
+# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12
+# License for the specific language governing permissions and limitations
13
+# under the License.
14
+
15
+import json
16
+
17
+from tempest.lib.common import rest_client
18
+
19
+
20
+class EventApiClient(rest_client.RestClient):
21
+
22
+    _uri = '/v1.0/events'
23
+
24
+    def __init__(self, auth_provider, service, region):
25
+        super(EventApiClient, self).__init__(
26
+            auth_provider,
27
+            service,
28
+            region
29
+        )
30
+
31
+    def send_events(self, events, headers=None):
32
+        msg = json.dumps(events)
33
+        resp, body = self.post(self._uri, body=msg, headers=headers)
34
+        return resp, body

+ 0
- 0
monasca_tempest_tests/tests/event_api/__init__.py View File


+ 94
- 0
monasca_tempest_tests/tests/event_api/base.py View File

@@ -0,0 +1,94 @@
1
+# Copyright 2019 FUJITSU LIMITED
2
+#
3
+# Licensed under the Apache License, Version 2.0 (the "License"); you may
4
+# not use this file except in compliance with the License. You may obtain
5
+# a copy of the License at
6
+#
7
+#      http://www.apache.org/licenses/LICENSE-2.0
8
+#
9
+# Unless required by applicable law or agreed to in writing, software
10
+# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11
+# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12
+# License for the specific language governing permissions and limitations
13
+# under the License.
14
+
15
+from datetime import datetime
16
+import json
17
+from os import path
18
+import pytz
19
+import random
20
+import string
21
+
22
+from oslo_config import cfg
23
+from tempest.common import credentials_factory as cred_factory
24
+from tempest import test
25
+
26
+from monasca_tempest_tests.clients import event_api as clients
27
+
28
+CONF = cfg.CONF
29
+
30
+
31
+def get_simple_event():
32
+    json_file_path = path.join(path.dirname(__file__),
33
+                               'req_simple_event.json')
34
+    with open(json_file_path, 'r') as f:
35
+        return json.loads(f.read())
36
+
37
+
38
+def create_header(header={}, content_type='application/json'):
39
+    header.update({'Content-Type': content_type,
40
+                   'kbn-version': CONF.monitoring.kibana_version})
41
+    return header
42
+
43
+
44
+def generate_simple_event_type_string():
45
+    letters = string.ascii_lowercase
46
+    random_string = ''.join((random.choice(letters) for _ in range(15)))
47
+    return '{}.{}'.format(random_string[:7], random_string[8:])
48
+
49
+
50
+def generate_simple_event(event_type=None, timestamp=None, events=None, num_of_events=1):
51
+    if event_type is None:
52
+        event_type = generate_simple_event_type_string()
53
+    if events is None:
54
+        events = \
55
+            [{
56
+                'dimensions': {
57
+                    'service': 'compute',
58
+                    'topic': 'notification.sample',
59
+                    'hostname': 'mars'},
60
+                'project_id': '6f70656e737461636b20342065766572',
61
+                'event': {
62
+                    'event_type': event_type,
63
+                    'payload': {
64
+                        'nova_object.data': {
65
+                            'architecture': 'x86_64',
66
+                            'availability_zone': 'nova',
67
+                            'created_at': '2012-10-29T13:42:11Z'}}}}] \
68
+            * num_of_events
69
+    if timestamp is None:
70
+        timestamp = datetime.now(tz=pytz.utc).strftime("%Y-%m-%dT%H:%M:%SZ%z")
71
+    return {'timestamp': timestamp,
72
+            'events': events}
73
+
74
+
75
+class BaseEventsTestCase(test.BaseTestCase):
76
+    """Base test case class for all Event API tests."""
77
+
78
+    @classmethod
79
+    def skip_checks(cls):
80
+        super(BaseEventsTestCase, cls).skip_checks()
81
+
82
+    @classmethod
83
+    def resource_setup(cls):
84
+        super(BaseEventsTestCase, cls).resource_setup()
85
+        auth_version = CONF.identity.auth_version
86
+        cred_provider = cred_factory.get_credentials_provider(
87
+            cls.__name__,
88
+            identity_version=auth_version)
89
+        credentials = cred_provider.get_creds_by_roles(
90
+            ['admin']).credentials
91
+        cls.os_primary = clients.Manager(credentials=credentials)
92
+
93
+        cls.events_api_client = cls.os_primary.events_api_client
94
+        cls.events_search_client = cls.os_primary.events_search_client

+ 76
- 0
monasca_tempest_tests/tests/event_api/test_simple.py View File

@@ -0,0 +1,76 @@
1
+# Copyright 2019 FUJITSU LIMITED
2
+#
3
+# Licensed under the Apache License, Version 2.0 (the "License"); you may
4
+# not use this file except in compliance with the License. You may obtain
5
+# a copy of the License at
6
+#
7
+#      http://www.apache.org/licenses/LICENSE-2.0
8
+#
9
+# Unless required by applicable law or agreed to in writing, software
10
+# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11
+# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12
+# License for the specific language governing permissions and limitations
13
+# under the License.
14
+
15
+from tempest.lib.common.utils import test_utils
16
+from tempest.lib import decorators
17
+from tempest.lib import exceptions
18
+
19
+from monasca_tempest_tests.tests.event_api import base
20
+
21
+RETRY_COUNT = 15
22
+RETRY_WAIT = 2
23
+
24
+
25
+class BaseEventsTestCase(base.BaseEventsTestCase):
26
+
27
+    def check_if_events_are_present_in_db(self, event_type):
28
+        return len(self.events_search_client.search_event_by_event_type(event_type)) > 0
29
+
30
+    def send_and_retrieve_events(self, events=None, header=None, events_number=1):
31
+        if events is None:
32
+            event_type = base.generate_simple_event_type_string()
33
+            events = base.generate_simple_event(event_type, num_of_events=events_number)
34
+        if header is None:
35
+            header = base.create_header()
36
+        response, _ = self.events_api_client.send_events(events, header)
37
+        self.assertEqual(200, response.status)
38
+        test_utils.call_until_true(self.check_if_events_are_present_in_db,
39
+                                   RETRY_COUNT * RETRY_WAIT,
40
+                                   RETRY_WAIT,
41
+                                   event_type)
42
+        response = self.events_search_client.search_event_by_event_type(event_type)
43
+
44
+        self.assertEqual(events_number, len(response))
45
+
46
+    @decorators.attr(type=['gate', 'smoke'])
47
+    def test_single_event(self):
48
+        self.send_and_retrieve_events()
49
+
50
+    @decorators.attr(type='gate')
51
+    def test_multiple_events(self):
52
+        self.send_and_retrieve_events(events_number=5)
53
+
54
+    @decorators.attr(type='gate')
55
+    def test_missing_body(self):
56
+        header = base.create_header()
57
+        try:
58
+            response, _ = self.events_api_client.send_events(None, header)
59
+        except exceptions.UnprocessableEntity as exc:
60
+            self.assertEqual(422, exc.resp.status)
61
+
62
+    @decorators.attr(type='gate')
63
+    def test_empty_event(self):
64
+        header = base.create_header()
65
+        body = base.generate_simple_event(events=[])
66
+        try:
67
+            response, _ = self.events_api_client.send_events(body, header)
68
+        except exceptions.UnprocessableEntity as exc:
69
+            self.assertEqual(422, exc.resp.status)
70
+
71
+    def test_empty_content_type(self):
72
+        body = base.generate_simple_event()
73
+        try:
74
+            response, _ = self.events_api_client.send_events(body, {})
75
+        except exceptions.BadRequest as exc:
76
+            self.assertEqual(400, exc.resp.status)

Loading…
Cancel
Save