From bb6213e9bdd19bd8644339326fe4aca79a7087a5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=83=91=E4=BD=A9=E7=8F=8A=5Bshiisa=5D?= Date: Mon, 18 Oct 2021 13:39:29 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E5=AE=A1=E8=AE=A1=E6=94=AF=E6=8C=81?= =?UTF-8?q?=E5=A4=B1=E8=B4=A5=E8=AE=B0=E5=BD=95=20#71?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/api/bkuser_core/audit/constants.py | 4 +- src/api/bkuser_core/audit/handlers.py | 3 +- src/api/bkuser_core/audit/models.py | 1 + src/api/bkuser_core/audit/utils.py | 31 +++- src/api/bkuser_core/categories/views.py | 109 +----------- src/api/bkuser_core/common/viewset.py | 25 ++- src/api/bkuser_core/departments/views.py | 4 +- src/api/bkuser_core/profiles/views.py | 9 +- .../tests/apis/audits/test_audits.py | 16 +- src/api/bkuser_core/tests/audit/test_utils.py | 166 +++++++++--------- 10 files changed, 142 insertions(+), 226 deletions(-) diff --git a/src/api/bkuser_core/audit/constants.py b/src/api/bkuser_core/audit/constants.py index fddccd858..1a5f0f822 100644 --- a/src/api/bkuser_core/audit/constants.py +++ b/src/api/bkuser_core/audit/constants.py @@ -61,10 +61,10 @@ class OperationEnum(AutoLowerEnum): class OperationStatusEnum(AutoLowerEnum): - SUCCESS = auto() + SUCCEED = auto() FAILED = auto() _choices_labels = ( - (SUCCESS, "成功"), + (SUCCEED, "成功"), (FAILED, "失败"), ) diff --git a/src/api/bkuser_core/audit/handlers.py b/src/api/bkuser_core/audit/handlers.py index 52395a88d..36c66c2f7 100644 --- a/src/api/bkuser_core/audit/handlers.py +++ b/src/api/bkuser_core/audit/handlers.py @@ -15,7 +15,7 @@ @receiver(post_profile_create) @receiver(post_profile_update) -def create_audit_log(sender, profile, operator, operation_type, status, extra_values, **kwargs): +def create_audit_log(sender, profile, operator, operation_type, extra_values, **kwargs): """Create an audit log""" request = extra_values["request"] create_general_log( @@ -23,7 +23,6 @@ def create_audit_log(sender, profile, operator, operation_type, status, extra_va operate_type=operation_type, operator_obj=profile, request=request, - status=status, ) # 当密码信息存在时,我们需要增加一条记录, diff --git a/src/api/bkuser_core/audit/models.py b/src/api/bkuser_core/audit/models.py index 0c24c9bfc..a3fe0cfc0 100644 --- a/src/api/bkuser_core/audit/models.py +++ b/src/api/bkuser_core/audit/models.py @@ -59,6 +59,7 @@ class Meta: class GeneralLog(Log): """通用操作日志""" + status = models.CharField("状态", max_length=16, choices=OperationStatusEnum.get_choices()) diff --git a/src/api/bkuser_core/audit/utils.py b/src/api/bkuser_core/audit/utils.py index bb76057ab..8a744fdb6 100644 --- a/src/api/bkuser_core/audit/utils.py +++ b/src/api/bkuser_core/audit/utils.py @@ -13,6 +13,7 @@ from django.conf import settings +from ..common.error_codes import CoreAPIError from . import models from .constants import OperationEnum, OperationStatusEnum from .models import GeneralLog, ProfileRelatedLog @@ -45,8 +46,8 @@ def get_client_ip(request: "Request") -> str: def create_general_log( operator: str, operate_type: str, - status: str, operator_obj: Any, + status: str = OperationStatusEnum.SUCCEED.value, extra_info: Dict = None, request=None, ) -> Optional[GeneralLog]: @@ -61,10 +62,6 @@ def create_general_log( logger.exception("operate type<%s> unknown", operate_type) return None - if not OperationStatusEnum.has_value(status): - logger.exception("status unknown", status) - return None - extra_value = { "operation": operate_type, "obj_type": operator_obj.__class__.__name__, @@ -98,3 +95,27 @@ def create_profile_log( raise ValueError("unknown operation for profile log") except Exception: raise ValueError("operation is not a profile log type") + + +def audit_error_general_log(operate_type): + """定义捕获异常的审计日志装饰器""" + + def catch_exc(func): + def _catch_exc(self, request, *args, **kwargs): + try: + func(self, request, *args, **kwargs) + + except CoreAPIError as e: + create_general_log( + operator=request.operator, + operate_type=operate_type, + operator_obj=self.get_object(), + request=request, + status=OperationStatusEnum.FAILED.value, + extra_info={"failed_info": f"{e.message}"}, + ) + return + + return _catch_exc + + return catch_exc diff --git a/src/api/bkuser_core/categories/views.py b/src/api/bkuser_core/categories/views.py index ec1b64061..2287eb341 100644 --- a/src/api/bkuser_core/categories/views.py +++ b/src/api/bkuser_core/categories/views.py @@ -11,8 +11,8 @@ import logging from typing import List -from bkuser_core.audit.constants import OperationEnum, OperationStatusEnum -from bkuser_core.audit.utils import create_general_log +from bkuser_core.audit.constants import OperationEnum +from bkuser_core.audit.utils import audit_error_general_log, create_general_log from bkuser_core.bkiam.permissions import IAMAction, IAMHelper, IAMPermissionExtraInfo, need_iam from bkuser_core.categories.constants import CategoryType, SyncTaskType from bkuser_core.categories.exceptions import ExistsSyncingTaskError, FetchDataFromRemoteFailed @@ -39,7 +39,7 @@ from django.utils.decorators import method_decorator from django.utils.module_loading import import_string from drf_yasg.utils import swagger_auto_schema -from rest_framework import filters, status +from rest_framework import filters from rest_framework.decorators import action from rest_framework.parsers import FormParser, MultiPartParser from rest_framework.response import Response @@ -112,20 +112,18 @@ def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) instance = serializer.save() - headers = self.get_success_headers(serializer.data) + # headers = self.get_success_headers(serializer.data) # 默认添加到最后 TODO: 需要一个更优雅的实现 max_order = ProfileCategory.objects.get_max_order() instance.order = max_order + 1 instance.save(update_fields=["order"]) - post_category_create.send(sender=self, category=instance, creator=request.operator) create_general_log( operator=request.operator, operate_type=OperationEnum.CREATE.value, operator_obj=instance, request=request, - status=OperationStatusEnum.SUCCESS.value, ) def get_serializer(self, *args, **kwargs): @@ -134,6 +132,8 @@ def get_serializer(self, *args, **kwargs): else: return self.serializer_class(*args, **kwargs) + # @method_decorator(audit_error_general_log) + @audit_error_general_log(operate_type=OperationEnum.UPDATE.value) @method_decorator(clear_cache_if_succeed) def update(self, request, *args, **kwargs): """ @@ -148,25 +148,9 @@ def update(self, request, *args, **kwargs): updating_domain = serializer.validated_data.get("domain") if updating_domain and not updating_domain == instance.domain: - create_general_log( - operator=request.operator, - operate_type=OperationEnum.UPDATE.value, - operator_obj=instance, - request=request, - status=OperationStatusEnum.FAILED.value, - extra_info={"failed_info": f"{error_codes.CANNOT_UPDATE_DOMAIN.message}"}, - ) raise error_codes.CANNOT_UPDATE_DOMAIN if instance.default and any(serializer.validated_data.get(x) is False for x in ["enabled", "status"]): - create_general_log( - operator=request.operator, - operate_type=OperationEnum.UPDATE.value, - operator_obj=instance, - request=request, - status=OperationStatusEnum.FAILED.value, - extra_info={"failed_info": f"{error_codes.CANNOT_DISABLE_DOMAIN.message}"}, - ) raise error_codes.CANNOT_DISABLE_DOMAIN self.perform_update(serializer) @@ -181,25 +165,17 @@ def update(self, request, *args, **kwargs): operate_type=OperationEnum.UPDATE.value, operator_obj=instance, request=request, - status=OperationStatusEnum.SUCCESS.value, ) return Response(serializer.data) + @audit_error_general_log(operate_type=OperationEnum.DELETE.value) def destroy(self, request, *args, **kwargs): """ 删除用户目录 """ instance = self.get_object() if instance.default: - create_general_log( - operator=request.operator, - operate_type=OperationEnum.DELETE.value, - operator_obj=instance, - request=request, - status=OperationStatusEnum.FAILED.value, - extra_info={"failed_info": f"{error_codes.CANNOT_DELETE_DEFAULT_CATEGORY.message}"}, - ) raise error_codes.CANNOT_DELETE_DEFAULT_CATEGORY post_category_delete.send(sender=self, category=instance, operator=request.operator) @@ -208,7 +184,6 @@ def destroy(self, request, *args, **kwargs): operate_type=OperationEnum.DELETE.value, operator_obj=instance, request=request, - status=OperationStatusEnum.SUCCESS.value, ) return super().destroy(request, *args, **kwargs) @@ -288,6 +263,7 @@ def test_fetch_data(self, request, lookup_value): return Response() + @audit_error_general_log(operate_type=OperationEnum.SYNC.value) @method_decorator(clear_cache_if_succeed) @swagger_auto_schema(request_body=CategorySyncSerializer, responses={"200": CategorySyncResponseSLZ()}) def sync(self, request, lookup_value): @@ -296,14 +272,6 @@ def sync(self, request, lookup_value): self.check_object_permissions(request, instance) if instance.type == CategoryType.LOCAL.value: - create_general_log( - operator=request.operator, - operate_type=OperationEnum.SYNC.value, - operator_obj=instance, - request=request, - status=OperationStatusEnum.FAILED.value, - extra_info={"failed_info": f"{error_codes.LOCAL_CATEGORY_CANNOT_SYNC.message}"} - ) raise error_codes.LOCAL_CATEGORY_CANNOT_SYNC try: @@ -311,15 +279,6 @@ def sync(self, request, lookup_value): category=instance, operator=request.operator, type_=SyncTaskType.MANUAL ).id except ExistsSyncingTaskError as e: - create_general_log( - operator=request.operator, - operate_type=OperationEnum.SYNC.value, - operator_obj=instance, - request=request, - status=OperationStatusEnum.FAILED.value, - extra_info={"failed_info": f"{e}"} - ) - raise error_codes.LOAD_DATA_FAILED.f(str(e)) try: @@ -328,28 +287,11 @@ def sync(self, request, lookup_value): ) except FetchDataFromRemoteFailed as e: logger.exception("failed to sync data") - create_general_log( - operator=request.operator, - operate_type=OperationEnum.SYNC.value, - operator_obj=instance, - request=request, - status=OperationStatusEnum.FAILED.value, - extra_info={"failed_info": f"{e}"} - ) - raise error_codes.SYNC_DATA_FAILED.f(f"{e}") except CoreAPIError: raise except Exception: logger.exception("failed to sync data") - create_general_log( - operator=request.operator, - operate_type=OperationEnum.SYNC.value, - operator_obj=instance, - request=request, - status=OperationStatusEnum.FAILED.value, - extra_info={"failed_info": f"{error_codes.SYNC_DATA_FAILED.message}"} - ) raise error_codes.SYNC_DATA_FAILED create_general_log( @@ -357,7 +299,6 @@ def sync(self, request, lookup_value): operate_type=OperationEnum.SYNC.value, operator_obj=instance, request=request, - status=OperationStatusEnum.SUCCESS.value, ) return Response({"task_id": task_id}) @@ -369,6 +310,7 @@ class CategoryFileViewSet(AdvancedModelViewSet, AdvancedListAPIView): lookup_field = "id" ordering = ["-create_time"] + @audit_error_general_log(operate_type=OperationEnum.IMPORT.value) @method_decorator(clear_cache_if_succeed) @swagger_auto_schema(request_body=CategorySyncSerializer, responses={"200": EmptySerializer()}) def import_data_file(self, request, lookup_value): @@ -379,14 +321,6 @@ def import_data_file(self, request, lookup_value): self.check_object_permissions(request, instance) if instance.type != CategoryType.LOCAL.value: - create_general_log( - operator=request.operator, - operate_type=OperationEnum.IMPORT.value, - operator_obj=instance, - request=request, - status=OperationStatusEnum.FAILED.value, - extra_info={"failed_info": f"{error_codes.CATEGORY_CANNOT_IMPORT_BY_FILE.message}"} - ) raise error_codes.CATEGORY_CANNOT_IMPORT_BY_FILE try: @@ -394,14 +328,6 @@ def import_data_file(self, request, lookup_value): category=instance, operator=request.operator, type_=SyncTaskType.MANUAL ).id except ExistsSyncingTaskError as e: - create_general_log( - operator=request.operator, - operate_type=OperationEnum.IMPORT.value, - operator_obj=instance, - request=request, - status=OperationStatusEnum.FAILED.value, - extra_info={"failed_info": f"{e}"} - ) raise error_codes.LOAD_DATA_FAILED.f(str(e)) params = {"raw_data_file": serializer.validated_data["raw_data_file"]} @@ -410,25 +336,9 @@ def import_data_file(self, request, lookup_value): adapter_sync(lookup_value, operator=request.operator, task_id=task_id, **params) except DataFormatError as e: logger.exception("failed to sync data") - create_general_log( - operator=request.operator, - operate_type=OperationEnum.IMPORT.value, - operator_obj=instance, - request=request, - status=OperationStatusEnum.FAILED.value, - extra_info={"failed_info": f"{e}"} - ) raise error_codes.SYNC_DATA_FAILED.format(str(e), replace=True) except Exception as e: logger.exception("failed to sync data") - create_general_log( - operator=request.operator, - operate_type=OperationEnum.IMPORT.value, - operator_obj=instance, - request=request, - status=OperationStatusEnum.FAILED.value, - extra_info={"failed_info": f"{e}"} - ) raise error_codes.SYNC_DATA_FAILED.format(str(e), replace=True) create_general_log( @@ -436,7 +346,6 @@ def import_data_file(self, request, lookup_value): operate_type=OperationEnum.IMPORT.value, operator_obj=instance, request=request, - status=OperationStatusEnum.SUCCESS.value, ) return Response() diff --git a/src/api/bkuser_core/common/viewset.py b/src/api/bkuser_core/common/viewset.py index e85fa42ad..bf1c9a855 100644 --- a/src/api/bkuser_core/common/viewset.py +++ b/src/api/bkuser_core/common/viewset.py @@ -113,8 +113,8 @@ def _ensure_enabled_field(self, request, fields: Optional[List] = None): if not fields: return if ( - "enabled" in fields - or getattr(self, "include_disabled_field", "include_disabled") not in request.query_params + "enabled" in fields + or getattr(self, "include_disabled_field", "include_disabled") not in request.query_params ): return fields.append("enabled") @@ -131,10 +131,10 @@ class AdvancedSearchFilter(filters.SearchFilter, DynamicFieldsMixin): @staticmethod def _try_best_match( - best_match: bool, - queryset: QuerySet, - condition_str: str, - params: Optional[list] = None, + best_match: bool, + queryset: QuerySet, + condition_str: str, + params: Optional[list] = None, ): # 最短匹配排在前面 if best_match: @@ -191,7 +191,7 @@ def filter_queryset(self, request, queryset, view): query_data = serializer.validated_data if queryset.model.__name__ in self.SOFT_DELETE_MODELNAMES and not force_str_2_bool( - request.query_params.get(view.include_disabled_field, False) + request.query_params.get(view.include_disabled_field, False) ): queryset = queryset.filter(enabled=True) @@ -296,7 +296,6 @@ def update(self, request, *args, **kwargs): operate_type=OperationEnum.UPDATE.value, operator_obj=instance, request=request, - status=OperationStatusEnum.SUCCESS.value, ) return result @@ -310,7 +309,6 @@ def destroy(self, request, *args, **kwargs): operate_type=OperationEnum.DELETE.value, operator_obj=instance, request=request, - status=OperationStatusEnum.SUCCESS.value, ) return super().destroy(request, *args, **kwargs) @@ -332,8 +330,10 @@ def restoration(self, request, lookup_value): operator_obj=instance, request=request, status=OperationStatusEnum.FAILED.value, - extra_info={"action": f"restoration {instance._meta.model_name}.{self.lookup_field}-{lookup_value}", - "FAILED_info": f"{why}"}, + extra_info={ + "action": f"restoration {instance._meta.model_name}.{self.lookup_field}-{lookup_value}", + "FAILED_info": f"{why}", + }, ) logger.exception("failed to restoration instance: %s, error: %s", instance, why) else: @@ -342,7 +342,6 @@ def restoration(self, request, lookup_value): operate_type=OperationEnum.RESTORATION.value, operator_obj=instance, request=request, - status=OperationStatusEnum.SUCCESS.value, extra_info={"action": f"restoration {instance._meta.model_name}.{self.lookup_field}-{lookup_value}"}, ) return Response() @@ -433,7 +432,6 @@ def multiple_update(self, request): operate_type=OperationEnum.UPDATE.value, operator_obj=instance, request=request, - status=OperationStatusEnum.SUCCESS.value, ) if self.CATEGORY_SENSITIVE: @@ -463,7 +461,6 @@ def multiple_delete(self, request): operate_type=OperationEnum.DELETE.value, operator_obj=instance, request=request, - status=OperationStatusEnum.SUCCESS.value ) instance.delete() diff --git a/src/api/bkuser_core/departments/views.py b/src/api/bkuser_core/departments/views.py index c14bca5d5..60f7d63e2 100644 --- a/src/api/bkuser_core/departments/views.py +++ b/src/api/bkuser_core/departments/views.py @@ -10,7 +10,7 @@ """ from typing import Type -from bkuser_core.audit.constants import OperationEnum, OperationStatusEnum +from bkuser_core.audit.constants import OperationEnum from bkuser_core.audit.utils import create_general_log from bkuser_core.bkiam.exceptions import IAMPermissionDenied from bkuser_core.bkiam.permissions import IAMPermissionExtraInfo @@ -174,7 +174,6 @@ def add_profiles(self, request, *args, **kwargs): operate_type=OperationEnum.UPDATE.value, operator_obj=instance, request=request, - status=OperationStatusEnum.SUCCESS.value, ) return Response(data=ProfileMinimalSerializer(profiles, many=True).data) @@ -229,7 +228,6 @@ def create(self, request, *args, **kwargs): operate_type=OperationEnum.CREATE.value, operator_obj=instance, request=request, - status=OperationStatusEnum.SUCCESS.value, ) return Response(self.serializer_class(instance).data, status=status.HTTP_201_CREATED) diff --git a/src/api/bkuser_core/profiles/views.py b/src/api/bkuser_core/profiles/views.py index 42c1a7d3d..277400391 100644 --- a/src/api/bkuser_core/profiles/views.py +++ b/src/api/bkuser_core/profiles/views.py @@ -427,6 +427,7 @@ def modify_password(self, request, *args, **kwargs): operator=request.operator, extra_values=modify_summary, operation_type=OperationEnum.UPDATE.value, + status=OperationStatusEnum.SUCCEED.value, ) return Response(data=local_serializers.ProfileMinimalSerializer(instance).data) @@ -579,9 +580,9 @@ def login(self, request): time_aware_now = now() valid_period = datetime.timedelta(days=profile.password_valid_days) if ( - profile.password_valid_days > 0 - and ((profile.password_update_time or profile.latest_password_update_time) + valid_period) - < time_aware_now + profile.password_valid_days > 0 + and ((profile.password_update_time or profile.latest_password_update_time) + valid_period) + < time_aware_now ): create_profile_log( profile=profile, @@ -749,7 +750,6 @@ def create(self, request, *args, **kwargs): operate_type=OperationEnum.CREATE.value, operator_obj=instance, request=request, - status=OperationStatusEnum.SUCCESS.value, ) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) @@ -785,7 +785,6 @@ def _update(self, request, partial): operate_type=OperationEnum.UPDATE.value, operator_obj=instance, request=request, - status=OperationStatusEnum.SUCCESS.value, ) return Response(self.serializer_class(instance).data) diff --git a/src/api/bkuser_core/tests/apis/audits/test_audits.py b/src/api/bkuser_core/tests/apis/audits/test_audits.py index 31ce5e6d3..c6fbb2e77 100644 --- a/src/api/bkuser_core/tests/apis/audits/test_audits.py +++ b/src/api/bkuser_core/tests/apis/audits/test_audits.py @@ -9,7 +9,7 @@ specific language governing permissions and limitations under the License. """ import pytest -from bkuser_core.audit.constants import LogInFailReasonEnum, OperationEnum, OperationStatusEnum +from bkuser_core.audit.constants import LogInFailReasonEnum, OperationEnum from bkuser_core.audit.utils import create_general_log, create_profile_log from bkuser_core.audit.views import GeneralLogViewSet, LoginLogViewSet, ResetPasswordLogViewSet from bkuser_core.tests.utils import make_simple_profile @@ -28,19 +28,18 @@ def obj_view(self): # --------------- List --------------- @pytest.mark.parametrize( - "operate_type, username, status", + "operate_type, username", [ - (OperationEnum.UPDATE.value, "abc", OperationStatusEnum.SUCCESS.value), - (OperationEnum.CREATE.value, "edf", OperationStatusEnum.FAILED.value), - (OperationEnum.DELETE.value, "xyz", OperationStatusEnum.SUCCESS.value), + (OperationEnum.UPDATE.value, "abc"), + (OperationEnum.CREATE.value, "edf"), + (OperationEnum.DELETE.value, "xyz"), ], ) - def test_normal_list(self, factory, view, operate_type, username, status): + def test_normal_list(self, factory, view, operate_type, username): """测试拉取日志返回""" operator = "admin" operator_obj = make_simple_profile(username=username) - create_general_log(operator=operator, operator_obj=operator_obj, operate_type=operate_type, - status=status) + create_general_log(operator=operator, operator_obj=operator_obj, operate_type=operate_type) request = factory.get("/api/v2/general_log/") response = view(request=request) @@ -64,7 +63,6 @@ def test_page_size(self, factory, view, count, page_size, page, expected): operator=operator, operator_obj=operator_obj, operate_type=OperationEnum.UPDATE.value, - status=OperationStatusEnum.SUCCESS.value, ) request = factory.get(f"/api/v2/general_log/?page={page}&page_size={page_size}") diff --git a/src/api/bkuser_core/tests/audit/test_utils.py b/src/api/bkuser_core/tests/audit/test_utils.py index 8386d46f0..6a9008cce 100644 --- a/src/api/bkuser_core/tests/audit/test_utils.py +++ b/src/api/bkuser_core/tests/audit/test_utils.py @@ -9,7 +9,7 @@ specific language governing permissions and limitations under the License. """ import pytest -from bkuser_core.audit.constants import OperationEnum, OperationStatusEnum +from bkuser_core.audit.constants import OperationEnum from bkuser_core.audit.utils import create_general_log, create_profile_log from bkuser_core.tests import utils @@ -22,137 +22,131 @@ def make_operator_obj(obj_type_name: str, params: dict): return getattr(utils, "make_simple_" + obj_type_name)(**params) @pytest.mark.parametrize( - "operator, operate_type, status, obj_type, params, expected", + "operator, operate_type, obj_type, params, expected", [ ( - "zhangsan", - OperationEnum.UPDATE.value, - OperationStatusEnum.SUCCESS.value, - "profile", - {"username": "aaa", "force_create_params": {"category_id": 1}}, - { - "operation": OperationEnum.UPDATE.value, - "obj_type": "Profile", - "display_name": "AAA", - "key": "aaa", - "category_id": 1, - }, + "zhangsan", + OperationEnum.UPDATE.value, + "profile", + {"username": "aaa", "force_create_params": {"category_id": 1}}, + { + "operation": OperationEnum.UPDATE.value, + "obj_type": "Profile", + "display_name": "AAA", + "key": "aaa", + "category_id": 1, + }, ), ( - "bbbbb", - OperationEnum.CREATE.value, - OperationStatusEnum.FAILED.value, - "department", - { - "name": "xxxxx", - "force_create_params": {"pk": 10000, "category_id": 1}, - }, - { - "operation": OperationEnum.CREATE.value, - "obj_type": "Department", - "display_name": "xxxxx", - "key": 10000, - "category_id": 1, - }, + "bbbbb", + OperationEnum.CREATE.value, + "department", + { + "name": "xxxxx", + "force_create_params": {"pk": 10000, "category_id": 1}, + }, + { + "operation": OperationEnum.CREATE.value, + "obj_type": "Department", + "display_name": "xxxxx", + "key": 10000, + "category_id": 1, + }, ), ( - "zhangsan", - OperationEnum.UPDATE.value, - OperationStatusEnum.SUCCESS.value, - "category", - { - "domain": "aaa", - "display_name": "qwer", - "force_create_params": {"pk": 10000}, - }, - { - "operation": OperationEnum.UPDATE.value, - "obj_type": "ProfileCategory", - "display_name": "qwer", - "category_id": 10000, - "key": "aaa", - }, + "zhangsan", + OperationEnum.UPDATE.value, + "category", + { + "domain": "aaa", + "display_name": "qwer", + "force_create_params": {"pk": 10000}, + }, + { + "operation": OperationEnum.UPDATE.value, + "obj_type": "ProfileCategory", + "display_name": "qwer", + "category_id": 10000, + "key": "aaa", + }, ), ( - "zhangsan", - OperationEnum.CREATE.value, - OperationStatusEnum.FAILED.value, - "dynamic_field", - {"name": "aaa", "force_create_params": {"display_name": "qqqq"}}, - { - "operation": OperationEnum.CREATE.value, - "obj_type": "DynamicFieldInfo", - "display_name": "qqqq", - "key": "aaa", - }, + "zhangsan", + OperationEnum.CREATE.value, + "dynamic_field", + {"name": "aaa", "force_create_params": {"display_name": "qqqq"}}, + { + "operation": OperationEnum.CREATE.value, + "obj_type": "DynamicFieldInfo", + "display_name": "qqqq", + "key": "aaa", + }, ), ( - "zhangsan", - OperationEnum.CREATE.value, - OperationStatusEnum.SUCCESS.value, - "dynamic_field", - {"name": "aaa", "force_create_params": {"display_name": "qqqq"}}, - { - "operation": OperationEnum.CREATE.value, - "obj_type": "DynamicFieldInfo", - "display_name": "qqqq", - "key": "aaa", - }, + "zhangsan", + OperationEnum.CREATE.value, + "dynamic_field", + {"name": "aaa", "force_create_params": {"display_name": "qqqq"}}, + { + "operation": OperationEnum.CREATE.value, + "obj_type": "DynamicFieldInfo", + "display_name": "qqqq", + "key": "aaa", + }, ), ], ) - def test_create_general_log(self, operator, operate_type, status, obj_type, params, expected): + def test_create_general_log(self, operator, operate_type, obj_type, params, expected): obj = self.make_operator_obj(obj_type, params) - g = create_general_log(operator, operate_type, status, obj) + g = create_general_log(operator, operate_type, obj) assert g.operator == operator assert g.extra_value == expected @pytest.mark.django_db @pytest.mark.parametrize( - "operation_type, status, obj", + "operation_type, obj", [ - ("None", OperationStatusEnum.SUCCESS.value, None), - (OperationEnum.CREATE.value, OperationStatusEnum.FAILED.value, None), - ("ssss", OperationStatusEnum.SUCCESS.value, "zhangsan"), + ("None", None), + (OperationEnum.CREATE.value, None), + ("ssss", "zhangsan"), ], ) - def test_create_general_log_unknown(self, operation_type, status, obj): + def test_create_general_log_unknown(self, operation_type, obj): if obj is not None: obj = utils.make_simple_profile(obj) - assert create_general_log("zhangsan", operation_type, status, obj) is None + assert create_general_log("zhangsan", operation_type, obj) is None @pytest.mark.parametrize( "operation_type,params", [ ( - "LogIn", - {}, + "LogIn", + {}, ), ( - "ResetPassword", - {}, + "ResetPassword", + {}, ), ], ) def test_create_profile_log(self, operation_type, params): assert ( - create_profile_log(utils.make_simple_profile("zhangsan"), operation_type, - params=params).__class__.__name__ - == operation_type + create_profile_log(utils.make_simple_profile("zhangsan"), operation_type, params=params).__class__.__name__ + == operation_type ) @pytest.mark.parametrize( "operation_type,params", [ ( - "ccc", - {}, + "ccc", + {}, ), ( - "uuuu", - {}, + "uuuu", + {}, ), ], )