๐Ÿ“ฆ apache / superset

๐Ÿ“„ log_api_tests.py ยท 363 lines
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.
# isort:skip_file
"""Unit tests for Superset"""

from datetime import datetime, timedelta
from typing import Optional
from unittest.mock import ANY

from flask_appbuilder.security.sqla.models import User
import prison
from unittest.mock import patch

from superset import db
from superset.models.core import Log
from superset.views.log.api import LogRestApi
from superset.utils import json
from tests.integration_tests.base_tests import SupersetTestCase
from tests.integration_tests.conftest import with_feature_flags  # noqa: F401
from tests.integration_tests.constants import (
    ADMIN_USERNAME,
    ALPHA_USERNAME,
    GAMMA_USERNAME,
)
from tests.integration_tests.dashboard_utils import create_dashboard
from tests.integration_tests.test_app import app  # noqa: F401

EXPECTED_COLUMNS = [
    "action",
    "dashboard_id",
    "dttm",
    "duration_ms",
    "json",
    "referrer",
    "slice_id",
    "user",
    "user_id",
]


class TestLogApi(SupersetTestCase):
    def insert_log(
        self,
        action: str,
        user: "User",
        dashboard_id: Optional[int] = 0,
        slice_id: Optional[int] = 0,
        json: Optional[str] = "",
        duration_ms: Optional[int] = 0,
    ):
        log = Log(
            action=action,
            user=user,
            dashboard_id=dashboard_id,
            slice_id=slice_id,
            json=json,
            duration_ms=duration_ms,
        )
        db.session.add(log)
        db.session.commit()
        return log

    def test_not_enabled(self):
        with patch.object(LogRestApi, "is_enabled", return_value=False):
            admin_user = self.get_user("admin")
            self.insert_log("some_action", admin_user)
            self.login(ADMIN_USERNAME)
            arguments = {"filters": [{"col": "action", "opr": "sw", "value": "some_"}]}
            uri = f"api/v1/log/?q={prison.dumps(arguments)}"
            rv = self.client.get(uri)
            assert rv.status_code == 404

    def test_get_list(self):
        """
        Log API: Test get list
        """
        admin_user = self.get_user("admin")
        log = self.insert_log("some_action", admin_user)
        self.login(ADMIN_USERNAME)
        arguments = {"filters": [{"col": "action", "opr": "sw", "value": "some_"}]}
        uri = f"api/v1/log/?q={prison.dumps(arguments)}"
        rv = self.client.get(uri)
        assert rv.status_code == 200
        response = json.loads(rv.data.decode("utf-8"))
        assert list(response["result"][0].keys()) == EXPECTED_COLUMNS
        assert response["result"][0]["action"] == "some_action"
        assert response["result"][0]["user"]["username"] == "admin"
        db.session.delete(log)
        db.session.commit()

    def test_get_list_not_allowed(self):
        """
        Log API: Test get list
        """
        admin_user = self.get_user("admin")
        log = self.insert_log("action", admin_user)
        self.login(GAMMA_USERNAME)
        uri = "api/v1/log/"
        rv = self.client.get(uri)
        assert rv.status_code == 403
        self.login(ALPHA_USERNAME)
        rv = self.client.get(uri)
        assert rv.status_code == 403
        db.session.delete(log)
        db.session.commit()

    def test_get_item(self):
        """
        Log API: Test get item
        """
        admin_user = self.get_user("admin")
        log = self.insert_log("some_action", admin_user)
        self.login(ADMIN_USERNAME)
        uri = f"api/v1/log/{log.id}"
        rv = self.client.get(uri)
        assert rv.status_code == 200
        response = json.loads(rv.data.decode("utf-8"))

        assert list(response["result"].keys()) == EXPECTED_COLUMNS
        assert response["result"]["action"] == "some_action"
        assert response["result"]["user"]["username"] == "admin"
        db.session.delete(log)
        db.session.commit()

    def test_delete_log(self):
        """
        Log API: Test delete (does not exist)
        """
        admin_user = self.get_user("admin")
        log = self.insert_log("action", admin_user)
        self.login(ADMIN_USERNAME)
        uri = f"api/v1/log/{log.id}"
        rv = self.client.delete(uri)
        assert rv.status_code == 405
        db.session.delete(log)
        db.session.commit()

    def test_update_log(self):
        """
        Log API: Test update (does not exist)
        """
        admin_user = self.get_user("admin")
        log = self.insert_log("action", admin_user)
        self.login(ADMIN_USERNAME)

        log_data = {"action": "some_action"}
        uri = f"api/v1/log/{log.id}"
        rv = self.client.put(uri, json=log_data)
        assert rv.status_code == 405
        db.session.delete(log)
        db.session.commit()

    def test_get_recent_activity(self):
        """
        Log API: Test recent activity endpoint
        """
        admin_user = self.get_user("admin")
        self.login(ADMIN_USERNAME)
        dash = create_dashboard("dash_slug", "dash_title", "{}", [])
        log1 = self.insert_log(
            "log",
            admin_user,
            dashboard_id=dash.id,
            json='{"event_name": "mount_dashboard"}',
        )
        log2 = self.insert_log(
            "log",
            admin_user,
            dashboard_id=dash.id,
            json='{"event_name": "mount_dashboard"}',
        )

        uri = f"api/v1/log/recent_activity/"  # noqa: F541
        rv = self.client.get(uri)
        assert rv.status_code == 200
        response = json.loads(rv.data.decode("utf-8"))

        db.session.delete(log1)
        db.session.delete(log2)
        db.session.delete(dash)
        db.session.commit()

        assert response == {
            "result": [
                {
                    "action": "log",
                    "item_type": "dashboard",
                    "item_url": "/superset/dashboard/dash_slug/",
                    "item_title": "dash_title",
                    "time": ANY,
                    "time_delta_humanized": ANY,
                }
            ]
        }

    def test_get_recent_activity_actions_filter(self):
        """
        Log API: Test recent activity actions argument
        """
        admin_user = self.get_user("admin")
        self.login(ADMIN_USERNAME)
        dash = create_dashboard("dash_slug", "dash_title", "{}", [])
        log = self.insert_log(
            "log",
            admin_user,
            dashboard_id=dash.id,
            json='{"event_name": "mount_dashboard"}',
        )
        log2 = self.insert_log(
            "log",
            admin_user,
            dashboard_id=dash.id,
            json='{"event_name": "mount_explorer"}',
        )

        arguments = {"actions": ["mount_dashboard"]}
        uri = f"api/v1/log/recent_activity/?q={prison.dumps(arguments)}"
        rv = self.client.get(uri)

        db.session.delete(log)
        db.session.delete(log2)
        db.session.delete(dash)
        db.session.commit()

        assert rv.status_code == 200
        response = json.loads(rv.data.decode("utf-8"))
        assert len(response["result"]) == 1

    def test_get_recent_activity_distinct_false(self):
        """
        Log API: Test recent activity when distinct is false
        """
        db.session.query(Log).delete(synchronize_session=False)
        db.session.commit()
        admin_user = self.get_user("admin")
        self.login(ADMIN_USERNAME)
        dash = create_dashboard("dash_slug", "dash_title", "{}", [])
        log = self.insert_log(
            "log",
            admin_user,
            dashboard_id=dash.id,
            json='{"event_name": "mount_dashboard"}',
        )
        log2 = self.insert_log(
            "log",
            admin_user,
            dashboard_id=dash.id,
            json='{"event_name": "mount_dashboard"}',
        )

        arguments = {"distinct": False}
        uri = f"api/v1/log/recent_activity/?q={prison.dumps(arguments)}"
        rv = self.client.get(uri)

        db.session.delete(log)
        db.session.delete(log2)
        db.session.delete(dash)
        db.session.commit()
        assert rv.status_code == 200
        response = json.loads(rv.data.decode("utf-8"))
        assert len(response["result"]) == 2

    def test_get_recent_activity_pagination(self):
        """
        Log API: Test recent activity pagination arguments
        """
        admin_user = self.get_user("admin")
        self.login(ADMIN_USERNAME)
        dash = create_dashboard("dash_slug", "dash_title", "{}", [])
        dash2 = create_dashboard("dash2_slug", "dash2_title", "{}", [])
        dash3 = create_dashboard("dash3_slug", "dash3_title", "{}", [])
        log = self.insert_log(
            "log",
            admin_user,
            dashboard_id=dash.id,
            json='{"event_name": "mount_dashboard"}',
        )
        log2 = self.insert_log(
            "log",
            admin_user,
            dashboard_id=dash2.id,
            json='{"event_name": "mount_dashboard"}',
        )
        log3 = self.insert_log(
            "log",
            admin_user,
            dashboard_id=dash3.id,
            json='{"event_name": "mount_dashboard"}',
        )

        now = datetime.now()
        log3.dttm = now
        log2.dttm = now - timedelta(days=1)
        log.dttm = now - timedelta(days=2)

        arguments = {"page": 0, "page_size": 2}
        uri = f"api/v1/log/recent_activity/?q={prison.dumps(arguments)}"
        rv = self.client.get(uri)

        assert rv.status_code == 200
        response = json.loads(rv.data.decode("utf-8"))
        assert response == {
            "result": [
                {
                    "action": "log",
                    "item_type": "dashboard",
                    "item_url": "/superset/dashboard/dash3_slug/",
                    "item_title": "dash3_title",
                    "time": ANY,
                    "time_delta_humanized": ANY,
                },
                {
                    "action": "log",
                    "item_type": "dashboard",
                    "item_url": "/superset/dashboard/dash2_slug/",
                    "item_title": "dash2_title",
                    "time": ANY,
                    "time_delta_humanized": ANY,
                },
            ]
        }

        arguments = {"page": 1, "page_size": 2}
        uri = f"api/v1/log/recent_activity/?q={prison.dumps(arguments)}"
        rv = self.client.get(uri)

        db.session.delete(log)
        db.session.delete(log2)
        db.session.delete(log3)
        db.session.delete(dash)
        db.session.delete(dash2)
        db.session.delete(dash3)
        db.session.commit()

        assert rv.status_code == 200
        response = json.loads(rv.data.decode("utf-8"))
        assert response == {
            "result": [
                {
                    "action": "log",
                    "item_type": "dashboard",
                    "item_url": "/superset/dashboard/dash_slug/",
                    "item_title": "dash_title",
                    "time": ANY,
                    "time_delta_humanized": ANY,
                }
            ]
        }