def setUp(self): self.name = "test" self.task_template_name = "task_template_name" self.creator = "tester" self.extra_info = {"extra_info": "val"} self.pipeline_tree = { "constants": { "key_1": {"value": "val_1", "show_type": "show"}, "key_2": {"value": "val_2", "show_type": "hide"}, }, "activities": {}, "start_event": { "id": "id1", "name": "", "type": "EmptyStartEvent", "incoming": None, "outgoing": "flow_id1", }, "end_event": {"id": "id2", "name": "", "type": "EmptyEndEvent", "incoming": "flow_id1", "outgoing": None}, "gateways": {}, "flows": {"flow_id1": {"id": "flow_id1", "source": "id1", "target": "id2"}}, } self.project = Project.objects.create(name="test_project", time_zone="Asia/Shanghai", creator="test", desc="") self.invalid_project = Project.objects.create( name="invalid_project", time_zone="Asia/Shanghai", creator="test", desc="" ) self.snapshot = Snapshot.objects.create_snapshot({}) self.pipeline_template = PipelineTemplate.objects.create( template_id=uniqid(), name=self.task_template_name, creator=self.creator, snapshot=self.snapshot ) task_template = TaskTemplate(project=self.project, pipeline_template=self.pipeline_template,) task_template.save() self.template = task_template self.task = self.create_a_task()
def setUp(self): self.name = 'test' self.creator = 'tester' self.extra_info = {'extra_info': 'val'} self.pipeline_tree = { 'constants': { 'key_1': { 'value': 'val_1', 'show_type': 'show', }, 'key_2': { 'value': 'val_2', 'show_type': 'hide', } } } self.business = Business.objects.create( cc_id=1, cc_name='mock business', cc_owner='tester', cc_company='', life_cycle='2', executor='', ) self.invalid_business = Business.objects.create( cc_id=2, cc_name='mock business', cc_owner='tester', cc_company='', life_cycle='2', executor='', ) self.snapshot, _ = Snapshot.objects.create_or_get_snapshot({}) self.pipeline_template = PipelineTemplate.objects.create( template_id=uniqid(), name=self.name, creator=self.creator, snapshot=self.snapshot) task_template = TaskTemplate( business=self.business, pipeline_template=self.pipeline_template, ) task_template.save() self.template = task_template self.task = self.create_a_task()
def fast_create_task(request, project_id): params = request.params_json project = request.project logger.info( "[API] fast_create_task info, project_id: {project_id}, params: {params}".format( project_id=project.id, params=params ) ) try: pipeline_tree = params["pipeline_tree"] pipeline_instance_kwargs = { "name": standardize_name(params["name"], TASK_NAME_MAX_LENGTH), "creator": request.user.username, "pipeline_tree": pipeline_tree, "description": params.get("description", ""), } except (KeyError, ValueError) as e: return {"result": False, "message": "invalid params: %s" % str(e), "code": err_code.REQUEST_PARAM_INVALID.code} has_common_subprocess = params.get("has_common_subprocess", False) try: template = ( CommonTemplate(pipeline_template=None) if has_common_subprocess else TaskTemplate(pipeline_template=None) ) pipeline_instance = TaskFlowInstance.objects.create_pipeline_instance( template=template, **pipeline_instance_kwargs ) except PipelineException as e: message = "[API] fast_create_task create pipeline error: %s" % str(e) logger.exception(message) return {"result": False, "message": message, "code": err_code.UNKNOWN_ERROR.code} taskflow_kwargs = { "project": project, "pipeline_instance": pipeline_instance, "template_source": ONETIME, "create_method": "api", } if params.get("category") in [cate[0] for cate in TASK_CATEGORY]: taskflow_kwargs["category"] = params["category"] # 职能化任务,新建后进入职能化认领阶段 if params.get("flow_type", "common") == "common_func": taskflow_kwargs["flow_type"] = "common_func" taskflow_kwargs["current_flow"] = "func_claim" # 常规流程,新建后即可执行 else: taskflow_kwargs["flow_type"] = "common" taskflow_kwargs["current_flow"] = "execute_task" task = TaskFlowInstance.objects.create(**taskflow_kwargs) return { "result": True, "data": {"task_id": task.id, "task_url": task.url, "pipeline_tree": task.pipeline_tree}, "code": err_code.SUCCESS.code, }
def import_template_data(): data_url = getattr(settings, 'V2_DATA_URL') if not data_url: data_url = '%s/o/gcloud/template/export/' % settings.BK_PAAS_HOST response = requests.post(data_url, data=json.dumps( {'key': '___export___v2___template___'})) resp_data = json.loads(response.content) if not response.ok or not resp_data['result']: return {'result': False, 'data': 0} data_list = resp_data['data'] template_list = [] for tmpl in data_list[::-1]: default_user = '******' default_company = 'admin' business, __ = Business.objects.get_or_create( cc_id=tmpl['biz_cc_id'], cc_name=tmpl['biz_cc_name'], defaults={ 'cc_owner': default_user, 'cc_company': default_company, }) stage_data = json.loads(tmpl['stage_data']) param_data = json.loads(tmpl['parameters']) pipeline_tree = convert_stage_and_params_from_v2_to_v3( stage_data, param_data) pipeline_template_kwargs = { 'name': tmpl['name'], 'creator': tmpl['creator'], 'pipeline_tree': pipeline_tree, 'description': '', } pipeline_template = TaskTemplate.objects.create_pipeline_template( **pipeline_template_kwargs) pipeline_template.editor = tmpl['editor'] pipeline_template.create_time = tmpl['create_time'] pipeline_template.edit_time = tmpl['edit_time'] pipeline_template.save() template_list.append( TaskTemplate(business=business, category=tmpl['category'], pipeline_template=pipeline_template, notify_type=tmpl['default_notify_type'], notify_receivers=tmpl['default_notify_receiver'], time_out=tmpl['default_time_out_notify_time'])) TaskTemplate.objects.bulk_create(template_list) return {'result': True, 'data': len(template_list)}
def setUp(self): self.name = 'test' self.task_template_name = 'task_template_name' self.creator = 'tester' self.extra_info = {'extra_info': 'val'} self.pipeline_tree = { 'constants': { 'key_1': { 'value': 'val_1', 'show_type': 'show', }, 'key_2': { 'value': 'val_2', 'show_type': 'hide', } } } self.project = Project.objects.create(name='test_project', time_zone='Asia/Shanghai', creator='test', desc='') self.invalid_project = Project.objects.create( name='invalid_project', time_zone='Asia/Shanghai', creator='test', desc='') self.snapshot, _ = Snapshot.objects.create_or_get_snapshot({}) self.pipeline_template = PipelineTemplate.objects.create( template_id=uniqid(), name=self.task_template_name, creator=self.creator, snapshot=self.snapshot) task_template = TaskTemplate( project=self.project, pipeline_template=self.pipeline_template, ) task_template.save() self.template = task_template self.task = self.create_a_task()
def import_template_data(): data_url = getattr(settings, 'V2_DATA_URL', None) if not data_url: data_url = '%s/o/gcloud/template/export/' % settings.BK_PAAS_INNER_HOST response = requests.post( data_url, data=json.dumps({"key": "___export___v2___template___"}), headers={"Content-Type": "application/json"}, verify=False ) resp_data = json.loads(response.content) if not response.ok or not resp_data['result']: return {'result': False, 'data': 0} data_list = resp_data['data'] template_list = [] failure_dict = { 'num': 0, 'tag_code': [], 'message': u'tag_code:{tag_code}不支持迁移' } for tmpl in data_list[::-1]: default_user = '******' default_company = 'admin' business, __ = Business.objects.get_or_create( cc_id=tmpl['biz_cc_id'], cc_name=tmpl['biz_cc_name'], defaults={ 'cc_owner': default_user, 'cc_company': default_company, } ) stage_data = json.loads(tmpl['stage_data']) param_data = json.loads(tmpl['parameters']) # 判断是否存在不支持迁移的tag_code,如果存在则跳过此模板 import_flag = True for stage in stage_data: for step in stage['steps']: if step['tag_code'] not in component_code_v2_to_v3: import_flag = False failure_dict['num'] += 1 failure_dict['tag_code'].append(step['tag_code']) break if not import_flag: break if not import_flag: continue pipeline_tree = convert_stage_and_params_from_v2_to_v3(stage_data, param_data, tmpl['biz_cc_id']) pipeline_template_kwargs = { 'name': tmpl['name'], 'creator': tmpl['creator'], 'pipeline_tree': pipeline_tree, 'description': '', } pipeline_template = TaskTemplate.objects.create_pipeline_template(**pipeline_template_kwargs) pipeline_template.editor = tmpl['editor'] pipeline_template.create_time = tmpl['create_time'] pipeline_template.edit_time = tmpl['edit_time'] pipeline_template.save() default_notify_receiver = json.loads(tmpl['default_notify_receiver']) notify_receivers = { "receiver_group": default_notify_receiver['notify_group'], "more_receiver": default_notify_receiver['other_notify_receiver'] } template_list.append( TaskTemplate( business=business, category=tmpl['category'], pipeline_template=pipeline_template, notify_type=tmpl['default_notify_type'], notify_receivers=json.dumps(notify_receivers), time_out=tmpl['default_time_out_notify_time'] ) ) TaskTemplate.objects.bulk_create(template_list) return {'result': True, 'data': {"success": len(template_list), "failure": failure_dict}}
class APITest(TestCase): @classmethod def setUpClass(cls): cls.GET_TEMPLATE_LIST_URL = '/apigw/get_template_list/{biz_cc_id}/' cls.GET_TEMPLATE_INFO_URL = '/apigw/get_template_info/{template_id}/{bk_biz_id}/' cls.CREATE_TASK_URL = '/apigw/create_task/{template_id}/{bk_biz_id}/' cls.START_TASK_URL = '/apigw/start_task/{task_id}/{bk_biz_id}/' cls.OPERATE_TASK_URL = '/apigw/operate_task/{task_id}/{bk_biz_id}/' cls.GET_TASK_STATUS_URL = '/apigw/get_task_status/{task_id}/{bk_biz_id}/' cls.QUERY_TASK_COUNT_URL = '/apigw/query_task_count/{bk_biz_id}/' cls.GET_PERIODIC_TASK_LIST_URL = '/apigw/get_periodic_task_list/{bk_biz_id}/' cls.GET_PERIODIC_TASK_INFO_URL = '/apigw/get_periodic_task_info/{task_id}/{bk_biz_id}/' cls.CREATE_PERIODIC_TASK_URL = '/apigw/create_periodic_task/{template_id}/{bk_biz_id}/' cls.SET_PERIODIC_TASK_ENABLED_URL = '/apigw/set_periodic_task_enabled/{task_id}/{bk_biz_id}/' cls.MODIFY_PERIODIC_TASK_CRON_URL = '/apigw/modify_cron_for_periodic_task/{task_id}/{bk_biz_id}/' cls.MODIFY_PERIODIC_TASK_CONSTANTS_URL = '/apigw/modify_constants_for_periodic_task/{task_id}/{bk_biz_id}/' super(APITest, cls).setUpClass() def setUp(self): self.white_list_patcher = mock.patch(APIGW_DECORATOR_CHECK_WHITE_LIST, MagicMock(return_value=True)) self.dummy_user = MagicMock() self.dummy_user.username = '' self.user_cls = MagicMock() self.user_cls.objects = MagicMock() self.user_cls.objects.get_or_create = MagicMock( return_value=(self.dummy_user, False)) self.get_user_model_patcher = mock.patch( APIGW_DECORATOR_GET_USER_MODEL, MagicMock(return_value=self.user_cls)) self.prepare_user_business_patcher = mock.patch( APIGW_DECORATOR_PREPARE_USER_BUSINESS, MagicMock()) self.business_exist_patcher = mock.patch( APIGW_DECORATOR_BUSINESS_EXIST, MagicMock(return_value=True)) self.white_list_patcher.start() self.get_user_model_patcher.start() self.prepare_user_business_patcher.start() self.business_exist_patcher.start() self.client = Client() def tearDown(self): self.white_list_patcher.stop() self.get_user_model_patcher.stop() self.prepare_user_business_patcher.stop() self.business_exist_patcher.stop() @mock.patch(BUSINESS_GET, MagicMock(return_value=MockBusiness(cc_id=TEST_BIZ_CC_ID, cc_name=TEST_BIZ_CC_NAME))) def test_get_template_list__for_business_template(self): pt1 = MockPipelineTemplate(id=1, name='pt1') pt2 = MockPipelineTemplate(id=2, name='pt2') task_tmpl1 = MockTaskTemplate(id=1, pipeline_template=pt1) task_tmpl2 = MockTaskTemplate(id=2, pipeline_template=pt2) task_templates = [task_tmpl1, task_tmpl2] with mock.patch( TASKTEMPLATE_SELECT_RELATE, MagicMock(return_value=MockQuerySet( filter_result=task_templates))): assert_data = [{ 'id': tmpl.id, 'name': tmpl.pipeline_template.name, 'creator': tmpl.pipeline_template.creator, 'create_time': strftime_with_timezone(tmpl.pipeline_template.create_time), 'editor': tmpl.pipeline_template.editor, 'edit_time': strftime_with_timezone(tmpl.pipeline_template.edit_time), 'category': tmpl.category, 'bk_biz_id': TEST_BIZ_CC_ID, 'bk_biz_name': TEST_BIZ_CC_NAME } for tmpl in task_templates] response = self.client.get(path=self.GET_TEMPLATE_LIST_URL.format( biz_cc_id=TEST_BIZ_CC_ID)) self.assertEqual(response.status_code, 200) data = json.loads(response.content) self.assertTrue(data['result']) self.assertEqual(data['data'], assert_data) with mock.patch( TASKTEMPLATE_SELECT_RELATE, MagicMock(return_value=MockQuerySet(filter_result=[]))): assert_data = [] response = self.client.get(path=self.GET_TEMPLATE_LIST_URL.format( biz_cc_id=TEST_BIZ_CC_ID)) data = json.loads(response.content) self.assertTrue(data['result']) self.assertEqual(data['data'], assert_data) @mock.patch(BUSINESS_GET, MagicMock(return_value=MockBusiness(cc_id=TEST_BIZ_CC_ID, cc_name=TEST_BIZ_CC_NAME))) def test_get_template_list__for_common_template(self): pt1 = MockPipelineTemplate(id=1, name='pt1') pt2 = MockPipelineTemplate(id=2, name='pt2') task_tmpl1 = MockCommonTemplate(id=1, pipeline_template=pt1) task_tmpl2 = MockCommonTemplate(id=2, pipeline_template=pt2) task_templates = [task_tmpl1, task_tmpl2] with mock.patch( COMMONTEMPLATE_SELECT_RELATE, MagicMock(return_value=MockQuerySet( filter_result=task_templates))): assert_data = [{ 'id': tmpl.id, 'name': tmpl.pipeline_template.name, 'creator': tmpl.pipeline_template.creator, 'create_time': strftime_with_timezone(tmpl.pipeline_template.create_time), 'editor': tmpl.pipeline_template.editor, 'edit_time': strftime_with_timezone(tmpl.pipeline_template.edit_time), 'category': tmpl.category, 'bk_biz_id': TEST_BIZ_CC_ID, 'bk_biz_name': TEST_BIZ_CC_NAME } for tmpl in task_templates] response = self.client.get(path=self.GET_TEMPLATE_LIST_URL.format( biz_cc_id=TEST_BIZ_CC_ID), data={'template_source': 'common'}) self.assertEqual(response.status_code, 200) data = json.loads(response.content) self.assertTrue(data['result']) self.assertEqual(data['data'], assert_data) with mock.patch( COMMONTEMPLATE_SELECT_RELATE, MagicMock(return_value=MockQuerySet(filter_result=[]))): assert_data = [] response = self.client.get(path=self.GET_TEMPLATE_LIST_URL.format( biz_cc_id=TEST_BIZ_CC_ID), data={'template_source': 'common'}) data = json.loads(response.content) self.assertTrue(data['result']) self.assertEqual(data['data'], assert_data) @mock.patch(BUSINESS_GET, MagicMock(return_value=MockBusiness(cc_id=TEST_BIZ_CC_ID, cc_name=TEST_BIZ_CC_NAME))) def test_get_template_info__for_business_template(self): pt1 = MockPipelineTemplate(id=1, name='pt1') tmpl = MockTaskTemplate(id=1, pipeline_template=pt1) with mock.patch(TASKTEMPLATE_SELECT_RELATE, MagicMock(return_value=MockQuerySet(get_result=tmpl))): pipeline_tree = copy.deepcopy(tmpl.pipeline_tree) pipeline_tree.pop('line') pipeline_tree.pop('location') assert_data = { 'id': tmpl.id, 'name': tmpl.pipeline_template.name, 'creator': tmpl.pipeline_template.creator, 'create_time': strftime_with_timezone(tmpl.pipeline_template.create_time), 'editor': tmpl.pipeline_template.editor, 'edit_time': strftime_with_timezone(tmpl.pipeline_template.edit_time), 'category': tmpl.category, 'bk_biz_id': TEST_BIZ_CC_ID, 'bk_biz_name': TEST_BIZ_CC_NAME, 'pipeline_tree': pipeline_tree } response = self.client.get(path=self.GET_TEMPLATE_INFO_URL.format( template_id=TEST_TEMPLATE_ID, bk_biz_id=TEST_BIZ_CC_ID)) data = json.loads(response.content) self.assertTrue(data['result']) self.assertEqual(assert_data, data['data']) @mock.patch(TASKTEMPLATE_SELECT_RELATE, MagicMock(return_value=MockQuerySet( get_raise=TaskTemplate.DoesNotExist()))) @mock.patch(BUSINESS_GET, MagicMock(return_value=MockBusiness(cc_id=TEST_BIZ_CC_ID, cc_name=TEST_BIZ_CC_NAME))) def test_get_template_info__for_business_template_does_not_exists(self): response = self.client.get(path=self.GET_TEMPLATE_INFO_URL.format( template_id=TEST_TEMPLATE_ID, bk_biz_id=TEST_BIZ_CC_ID), ) data = json.loads(response.content) self.assertFalse(data['result']) self.assertTrue('message' in data) @mock.patch(BUSINESS_GET, MagicMock(return_value=MockBusiness(cc_id=TEST_BIZ_CC_ID, cc_name=TEST_BIZ_CC_NAME))) def test_get_template_info__for_common_template(self): pt1 = MockPipelineTemplate(id=1, name='pt1') tmpl = MockCommonTemplate(id=1, pipeline_template=pt1) with mock.patch(COMMONTEMPLATE_SELECT_RELATE, MagicMock(return_value=MockQuerySet(get_result=tmpl))): pipeline_tree = copy.deepcopy(tmpl.pipeline_tree) pipeline_tree.pop('line') pipeline_tree.pop('location') assert_data = { 'id': tmpl.id, 'name': tmpl.pipeline_template.name, 'creator': tmpl.pipeline_template.creator, 'create_time': strftime_with_timezone(tmpl.pipeline_template.create_time), 'editor': tmpl.pipeline_template.editor, 'edit_time': strftime_with_timezone(tmpl.pipeline_template.edit_time), 'category': tmpl.category, 'bk_biz_id': TEST_BIZ_CC_ID, 'bk_biz_name': TEST_BIZ_CC_NAME, 'pipeline_tree': pipeline_tree } response = self.client.get(path=self.GET_TEMPLATE_INFO_URL.format( template_id=TEST_TEMPLATE_ID, bk_biz_id=TEST_BIZ_CC_ID), data={'template_source': 'common'}) data = json.loads(response.content) self.assertTrue(data['result']) self.assertEqual(assert_data, data['data']) @mock.patch(COMMONTEMPLATE_SELECT_RELATE, MagicMock(return_value=MockQuerySet( get_raise=CommonTemplate.DoesNotExist()))) @mock.patch(BUSINESS_GET, MagicMock(return_value=MockBusiness(cc_id=TEST_BIZ_CC_ID, cc_name=TEST_BIZ_CC_NAME))) def test_get_template_info__for_common_template_does_not_exists(self): response = self.client.get(path=self.GET_TEMPLATE_INFO_URL.format( template_id=TEST_TEMPLATE_ID, bk_biz_id=TEST_BIZ_CC_ID), data={'template_source': 'common'}) data = json.loads(response.content) self.assertFalse(data['result']) self.assertTrue('message' in data) @mock.patch(TASKINSTANCE_CREATE_PIPELINE, MagicMock(return_value=(True, TEST_DATA))) @mock.patch( TASKINSTANCE_CREATE, MagicMock(return_value=MockTaskFlowInstance(id=TEST_TASKFLOW_ID))) @mock.patch(APIGW_VIEW_JSON_SCHEMA_VALIDATE, MagicMock()) def test_create_task__success(self): pt1 = MockPipelineTemplate(id=1, name='pt1') tmpl = MockTaskTemplate(id=1, pipeline_template=pt1) biz = MockBusiness(cc_id=TEST_BIZ_CC_ID, cc_name=TEST_BIZ_CC_NAME) with mock.patch(BUSINESS_GET, MagicMock(return_value=biz)): with mock.patch( TASKTEMPLATE_SELECT_RELATE, MagicMock(return_value=MockQuerySet(get_result=tmpl))): assert_data = {'task_id': TEST_TASKFLOW_ID} response = self.client.post(path=self.CREATE_TASK_URL.format( template_id=TEST_TEMPLATE_ID, bk_biz_id=TEST_BIZ_CC_ID), data=json.dumps({ 'name': 'name', 'constants': 'constants', 'exclude_task_nodes_id': 'exclude_task_nodes_id', 'flow_type': 'common' }), content_type="application/json", HTTP_BK_APP_CODE=TEST_APP_CODE) TaskFlowInstance.objects.create_pipeline_instance_exclude_task_nodes.assert_called_once_with( tmpl, { 'name': 'name', 'creator': '' }, 'constants', 'exclude_task_nodes_id') TaskFlowInstance.objects.create.assert_called_once_with( business=biz, category=tmpl.category, pipeline_instance=TEST_DATA, template_id=TEST_TEMPLATE_ID, create_method='api', create_info=TEST_APP_CODE, flow_type='common', current_flow='execute_task') data = json.loads(response.content) self.assertTrue(data['result']) self.assertEqual(data['data'], assert_data) TaskFlowInstance.objects.create_pipeline_instance_exclude_task_nodes.reset_mock( ) TaskFlowInstance.objects.create.reset_mock() pt1 = MockPipelineTemplate(id=1, name='pt1') tmpl = MockCommonTemplate(id=1, pipeline_template=pt1) with mock.patch( COMMONTEMPLATE_SELECT_RELATE, MagicMock(return_value=MockQuerySet(get_result=tmpl))): assert_data = {'task_id': TEST_TASKFLOW_ID} response = self.client.post(path=self.CREATE_TASK_URL.format( template_id=TEST_TEMPLATE_ID, bk_biz_id=TEST_BIZ_CC_ID), data=json.dumps({ 'name': 'name', 'constants': 'constants', 'exclude_task_nodes_id': 'exclude_task_nodes_id', 'template_source': 'common', 'flow_type': 'common' }), content_type="application/json", HTTP_BK_APP_CODE=TEST_APP_CODE) TaskFlowInstance.objects.create_pipeline_instance_exclude_task_nodes.assert_called_once_with( tmpl, { 'name': 'name', 'creator': '' }, 'constants', 'exclude_task_nodes_id') TaskFlowInstance.objects.create.assert_called_once_with( business=biz, category=tmpl.category, pipeline_instance=TEST_DATA, template_id=TEST_TEMPLATE_ID, create_method='api', create_info=TEST_APP_CODE, flow_type='common', current_flow='execute_task') data = json.loads(response.content) self.assertTrue(data['result']) self.assertEqual(data['data'], assert_data) @mock.patch(BUSINESS_GET, MagicMock(return_value=MockBusiness(cc_id=TEST_BIZ_CC_ID, cc_name=TEST_BIZ_CC_NAME))) @mock.patch(TASKTEMPLATE_SELECT_RELATE, MagicMock(return_value=MockQuerySet())) @mock.patch(COMMONTEMPLATE_SELECT_RELATE, MagicMock(return_value=MockQuerySet())) @mock.patch(APIGW_VIEW_JSON_SCHEMA_VALIDATE, MagicMock(side_effect=jsonschema.ValidationError(''))) def test_create_task__validate_fail(self): response = self.client.post(path=self.CREATE_TASK_URL.format( template_id=TEST_TEMPLATE_ID, bk_biz_id=TEST_BIZ_CC_ID), data=json.dumps({ 'constants': 'constants', 'exclude_task_node_id': 'exclude_task_node_id' }), content_type="application/json") data = json.loads(response.content) self.assertFalse(data['result']) self.assertTrue('message' in data) response = self.client.post( path=self.CREATE_TASK_URL.format(template_id=TEST_TEMPLATE_ID, bk_biz_id=TEST_BIZ_CC_ID), data=json.dumps({ 'constants': 'constants', 'exclude_task_node_id': 'exclude_task_node_id', 'template_source': 'common' }), content_type="application/json") data = json.loads(response.content) self.assertFalse(data['result']) self.assertTrue('message' in data) @mock.patch(BUSINESS_GET, MagicMock(return_value=MockBusiness(cc_id=TEST_BIZ_CC_ID, cc_name=TEST_BIZ_CC_NAME))) @mock.patch(TASKTEMPLATE_SELECT_RELATE, MagicMock(return_value=MockQuerySet())) @mock.patch(COMMONTEMPLATE_SELECT_RELATE, MagicMock(return_value=MockQuerySet())) @mock.patch(APIGW_VIEW_JSON_SCHEMA_VALIDATE, MagicMock()) def test_create_task__without_app_code(self): response = self.client.post(path=self.CREATE_TASK_URL.format( template_id=TEST_TEMPLATE_ID, bk_biz_id=TEST_BIZ_CC_ID), data=json.dumps({ 'constants': 'constants', 'exclude_task_node_id': 'exclude_task_node_id' }), content_type="application/json") data = json.loads(response.content) self.assertFalse(data['result']) self.assertTrue('message' in data) response = self.client.post( path=self.CREATE_TASK_URL.format(template_id=TEST_TEMPLATE_ID, bk_biz_id=TEST_BIZ_CC_ID), data=json.dumps({ 'constants': 'constants', 'exclude_task_node_id': 'exclude_task_node_id', 'template_source': 'common' }), content_type="application/json") data = json.loads(response.content) self.assertFalse(data['result']) self.assertTrue('message' in data) @mock.patch(BUSINESS_GET, MagicMock(return_value=MockBusiness(cc_id=TEST_BIZ_CC_ID, cc_name=TEST_BIZ_CC_NAME))) @mock.patch(TASKINSTANCE_CREATE_PIPELINE, MagicMock(side_effect=PipelineException())) @mock.patch(APIGW_VIEW_JSON_SCHEMA_VALIDATE, MagicMock()) def test_create_task__create_pipeline_raise(self): pt1 = MockPipelineTemplate(id=1, name='pt1') tmpl = MockTaskTemplate(id=1, pipeline_template=pt1) with mock.patch(TASKTEMPLATE_SELECT_RELATE, MagicMock(return_value=MockQuerySet(get_result=tmpl))): response = self.client.post(path=self.CREATE_TASK_URL.format( template_id=TEST_TEMPLATE_ID, bk_biz_id=TEST_BIZ_CC_ID), data=json.dumps({ 'name': 'name', 'constants': 'constants', 'exclude_task_node_id': 'exclude_task_node_id' }), content_type="application/json", HTTP_BK_APP_CODE=TEST_APP_CODE) data = json.loads(response.content) self.assertFalse(data['result']) self.assertTrue('message' in data) pt1 = MockPipelineTemplate(id=1, name='pt1') tmpl = MockCommonTemplate(id=1, pipeline_template=pt1) with mock.patch(COMMONTEMPLATE_SELECT_RELATE, MagicMock(return_value=MockQuerySet(get_result=tmpl))): response = self.client.post(path=self.CREATE_TASK_URL.format( template_id=TEST_TEMPLATE_ID, bk_biz_id=TEST_BIZ_CC_ID), data=json.dumps({ 'name': 'name', 'constants': 'constants', 'exclude_task_node_id': 'exclude_task_node_id', 'template_source': 'common' }), content_type="application/json", HTTP_BK_APP_CODE=TEST_APP_CODE) data = json.loads(response.content) self.assertFalse(data['result']) self.assertTrue('message' in data) @mock.patch(BUSINESS_GET, MagicMock(return_value=MockBusiness(cc_id=TEST_BIZ_CC_ID, cc_name=TEST_BIZ_CC_NAME))) @mock.patch(TASKINSTANCE_CREATE_PIPELINE, MagicMock(return_value=(False, ''))) @mock.patch(APIGW_VIEW_JSON_SCHEMA_VALIDATE, MagicMock()) def test_create_task__create_pipeline_fail(self): pt1 = MockPipelineTemplate(id=1, name='pt1') tmpl = MockTaskTemplate(id=1, pipeline_template=pt1) with mock.patch(TASKTEMPLATE_SELECT_RELATE, MagicMock(return_value=MockQuerySet(get_result=tmpl))): response = self.client.post(path=self.CREATE_TASK_URL.format( template_id=TEST_TEMPLATE_ID, bk_biz_id=TEST_BIZ_CC_ID), data=json.dumps({ 'name': 'name', 'constants': 'constants', 'exclude_task_node_id': 'exclude_task_node_id' }), content_type="application/json", HTTP_BK_APP_CODE=TEST_APP_CODE) data = json.loads(response.content) self.assertFalse(data['result']) self.assertTrue('message' in data) pt1 = MockPipelineTemplate(id=1, name='pt1') tmpl = MockCommonTemplate(id=1, pipeline_template=pt1) with mock.patch(COMMONTEMPLATE_SELECT_RELATE, MagicMock(return_value=MockQuerySet(get_result=tmpl))): response = self.client.post(path=self.CREATE_TASK_URL.format( template_id=TEST_TEMPLATE_ID, bk_biz_id=TEST_BIZ_CC_ID), data=json.dumps({ 'name': 'name', 'constants': 'constants', 'exclude_task_node_id': 'exclude_task_node_id', 'template_source': 'common' }), content_type="application/json", HTTP_BK_APP_CODE=TEST_APP_CODE) data = json.loads(response.content) self.assertFalse(data['result']) self.assertTrue('message' in data) def test_start_task(self): assert_return = {'result': True} task = MockTaskFlowInstance(task_action_return=assert_return) with mock.patch(TASKINSTANCE_GET, MagicMock(return_value=task)): response = self.client.post(path=self.START_TASK_URL.format( task_id=TEST_TASKFLOW_ID, bk_biz_id=TEST_BIZ_CC_ID)) task.task_action.assert_called_once_with('start', '') data = json.loads(response.content) self.assertEqual(data, assert_return) def test_operate_task(self): assert_return = {'result': True} assert_action = 'any_action' task = MockTaskFlowInstance(task_action_return=assert_return) with mock.patch(TASKINSTANCE_GET, MagicMock(return_value=task)): response = self.client.post( path=self.OPERATE_TASK_URL.format(task_id=TEST_TASKFLOW_ID, bk_biz_id=TEST_BIZ_CC_ID), data=json.dumps({'action': assert_action}), content_type='application/json') task.task_action.assert_called_once_with(assert_action, '') data = json.loads(response.content) self.assertEqual(data, assert_return) def test_get_task_status__success(self): task = MockTaskFlowInstance(get_status_return=TEST_DATA) with mock.patch(TASKINSTANCE_GET, MagicMock(return_value=task)): response = self.client.get(path=self.GET_TASK_STATUS_URL.format( task_id=TEST_TASKFLOW_ID, bk_biz_id=TEST_BIZ_CC_ID)) data = json.loads(response.content) self.assertTrue(data['result']) self.assertEqual(data['data'], TEST_DATA) def test_get_task_status__raise(self): task = MockTaskFlowInstance(get_status_raise=Exception()) with mock.patch(TASKINSTANCE_GET, MagicMock(return_value=task)): response = self.client.get(path=self.GET_TASK_STATUS_URL.format( task_id=TEST_TASKFLOW_ID, bk_biz_id=TEST_BIZ_CC_ID)) data = json.loads(response.content) self.assertFalse(data['result']) self.assertTrue('message' in data) @mock.patch(TASKINSTANCE_FORMAT_STATUS, MagicMock()) @mock.patch(APIGW_VIEW_PIPELINE_API_GET_STATUS_TREE, MagicMock(return_value=TEST_DATA)) def test_get_task_status__is_subprocess(self): task = MockTaskFlowInstance( get_status_raise=TaskFlowInstance.DoesNotExist()) with mock.patch(TASKINSTANCE_GET, MagicMock(return_value=task)): response = self.client.get(path=self.GET_TASK_STATUS_URL.format( task_id=TEST_TASKFLOW_ID, bk_biz_id=TEST_BIZ_CC_ID)) TaskFlowInstance.format_pipeline_status.assert_called_once_with( TEST_DATA) data = json.loads(response.content) self.assertTrue(data['result']) self.assertEqual(data['data'], TEST_DATA) @mock.patch(APIGW_VIEW_PIPELINE_API_GET_STATUS_TREE, MagicMock(return_value=TEST_DATA)) def test_get_task_status__is_subprocess_raise(self): task = MockTaskFlowInstance( get_status_raise=TaskFlowInstance.DoesNotExist()) with mock.patch(TASKINSTANCE_GET, MagicMock(return_value=task)): with mock.patch(APIGW_VIEW_PIPELINE_API_GET_STATUS_TREE, MagicMock(side_effect=Exception())): response = self.client.get( path=self.GET_TASK_STATUS_URL.format( task_id=TEST_TASKFLOW_ID, bk_biz_id=TEST_BIZ_CC_ID)) data = json.loads(response.content) self.assertFalse(data['result']) self.assertTrue('message' in data) with mock.patch(TASKINSTANCE_FORMAT_STATUS, MagicMock(side_effect=Exception())): response = self.client.get( path=self.GET_TASK_STATUS_URL.format( task_id=TEST_TASKFLOW_ID, bk_biz_id=TEST_BIZ_CC_ID)) data = json.loads(response.content) self.assertFalse(data['result']) self.assertTrue('message' in data) @mock.patch(TASKINSTANCE_EXTEN_CLASSIFIED_COUNT, MagicMock(return_value=(True, TEST_DATA))) def test_query_task_count__success(self): response = self.client.post( path=self.QUERY_TASK_COUNT_URL.format(bk_biz_id=TEST_BIZ_CC_ID), data=json.dumps({'group_by': 'category'}), content_type='application/json') data = json.loads(response.content) self.assertTrue(data['result']) self.assertEqual(data['data'], TEST_DATA) def test_query_task_count__conditions_is_not_dict(self): response = self.client.post( path=self.QUERY_TASK_COUNT_URL.format(bk_biz_id=TEST_BIZ_CC_ID), data=json.dumps({'conditions': []}), content_type='application/json') data = json.loads(response.content) self.assertFalse(data['result']) self.assertTrue('message' in data) def test_query_task_count__group_by_is_not_valid(self): response = self.client.post( path=self.QUERY_TASK_COUNT_URL.format(bk_biz_id=TEST_BIZ_CC_ID), data=json.dumps({'group_by': 'invalid_value'}), content_type='application/json') data = json.loads(response.content) self.assertFalse(data['result']) self.assertTrue('message' in data) @mock.patch(TASKINSTANCE_EXTEN_CLASSIFIED_COUNT, MagicMock(return_value=(False, ''))) def test_query_task_count__extend_classified_count_fail(self): response = self.client.post( path=self.QUERY_TASK_COUNT_URL.format(bk_biz_id=TEST_BIZ_CC_ID), data=json.dumps({'group_by': 'category'}), content_type='application/json') TaskFlowInstance.objects.extend_classified_count.assert_called_once_with( 'category', { 'business__cc_id': TEST_BIZ_CC_ID, 'is_deleted': False }) data = json.loads(response.content) self.assertFalse(data['result']) self.assertTrue('message' in data) def test_get_periodic_task_list(self): pt1 = MockPeriodicTask(id='1') pt2 = MockPeriodicTask(id='2') pt3 = MockPeriodicTask(id='3') periodic_tasks = [pt1, pt2, pt3] assert_data = [{ 'id': task.id, 'name': task.name, 'template_id': task.template_id, 'creator': task.creator, 'cron': task.cron, 'enabled': task.enabled, 'last_run_at': strftime_with_timezone(task.last_run_at), 'total_run_count': task.total_run_count, } for task in periodic_tasks] with mock.patch(PERIODIC_TASK_FILTER, MagicMock(return_value=periodic_tasks)): response = self.client.get( path=self.GET_PERIODIC_TASK_LIST_URL.format( bk_biz_id=TEST_BIZ_CC_ID)) data = json.loads(response.content) self.assertTrue(data['result']) self.assertEqual(data['data'], assert_data) def test_get_periodic_task_info__success(self): task = MockPeriodicTask() assert_data = { 'id': task.id, 'name': task.name, 'template_id': task.template_id, 'creator': task.creator, 'cron': task.cron, 'enabled': task.enabled, 'last_run_at': strftime_with_timezone(task.last_run_at), 'total_run_count': task.total_run_count, 'form': task.form, 'pipeline_tree': task.pipeline_tree } with mock.patch(PERIODIC_TASK_GET, MagicMock(return_value=task)): response = self.client.get( path=self.GET_PERIODIC_TASK_INFO_URL.format( task_id=TEST_PERIODIC_TASK_ID, bk_biz_id=TEST_BIZ_CC_ID)) data = json.loads(response.content) self.assertTrue(data['result']) self.assertEqual(data['data'], assert_data) @mock.patch(PERIODIC_TASK_GET, MagicMock(side_effect=PeriodicTask.DoesNotExist)) def test_periodic_task_info__task_does_not_exist(self): response = self.client.get(path=self.GET_PERIODIC_TASK_INFO_URL.format( task_id=TEST_PERIODIC_TASK_ID, bk_biz_id=TEST_BIZ_CC_ID)) data = json.loads(response.content) self.assertFalse(data['result']) self.assertTrue('message' in data) @mock.patch(TASKINSTANCE_PREVIEW_TREE, MagicMock()) @mock.patch(APIGW_VIEW_JSON_SCHEMA_VALIDATE, MagicMock()) def test_create_periodic_task__success(self): task = MockPeriodicTask() assert_data = { 'id': task.id, 'name': task.name, 'template_id': task.template_id, 'creator': task.creator, 'cron': task.cron, 'enabled': task.enabled, 'last_run_at': strftime_with_timezone(task.last_run_at), 'total_run_count': task.total_run_count, 'form': task.form, 'pipeline_tree': task.pipeline_tree } biz = MockBusiness(cc_id=TEST_BIZ_CC_ID, cc_name=TEST_BIZ_CC_NAME) template = MockTaskTemplate() with mock.patch(TASKTEMPLATE_GET, MagicMock(return_value=template)): with mock.patch(BUSINESS_GET, MagicMock(return_value=biz)): with mock.patch(PERIODIC_TASK_CREATE, MagicMock(return_value=task)): response = self.client.post( path=self.CREATE_PERIODIC_TASK_URL.format( template_id=TEST_TEMPLATE_ID, bk_biz_id=TEST_BIZ_CC_ID), data=json.dumps({ 'name': task.name, 'cron': task.cron, 'exclude_task_nodes_id': 'exclude_task_nodes_id' }), content_type='application/json') TaskFlowInstance.objects.preview_pipeline_tree_exclude_task_nodes.assert_called_with( template.pipeline_tree, 'exclude_task_nodes_id') PeriodicTask.objects.create.assert_called_once_with( business=biz, template=template, name=task.name, cron=task.cron, pipeline_tree=template.pipeline_tree, creator='') data = json.loads(response.content) self.assertTrue(data['result']) self.assertEqual(data['data'], assert_data) @mock.patch(TASKTEMPLATE_GET, MagicMock(side_effect=TaskTemplate.DoesNotExist())) def test_create_periodic_task__template_does_not_exist(self): response = self.client.post(path=self.CREATE_PERIODIC_TASK_URL.format( template_id=TEST_TEMPLATE_ID, bk_biz_id=TEST_BIZ_CC_ID), content_type='application/json') data = json.loads(response.content) self.assertFalse(data['result']) self.assertTrue('message' in data) @mock.patch(TASKTEMPLATE_GET, MagicMock(return_value=MockTaskTemplate())) @mock.patch(APIGW_VIEW_JSON_SCHEMA_VALIDATE, MagicMock(side_effect=jsonschema.ValidationError(''))) def test_create_periodic_task__params_validate_fail(self): response = self.client.post(path=self.CREATE_PERIODIC_TASK_URL.format( template_id=TEST_TEMPLATE_ID, bk_biz_id=TEST_BIZ_CC_ID), content_type='application/json') data = json.loads(response.content) self.assertFalse(data['result']) self.assertTrue('message' in data) @mock.patch(TASKTEMPLATE_GET, MagicMock(return_value=MockTaskTemplate())) @mock.patch(APIGW_VIEW_JSON_SCHEMA_VALIDATE, MagicMock()) @mock.patch(TASKINSTANCE_PREVIEW_TREE, MagicMock(side_effect=Exception())) def test_create_periodic_task__preview_pipeline_fail(self): response = self.client.post(path=self.CREATE_PERIODIC_TASK_URL.format( template_id=TEST_TEMPLATE_ID, bk_biz_id=TEST_BIZ_CC_ID), content_type='application/json') data = json.loads(response.content) self.assertFalse(data['result']) self.assertTrue('message' in data) @mock.patch(BUSINESS_GET, MagicMock(return_value=MockBusiness(cc_id=TEST_BIZ_CC_ID, cc_name=TEST_BIZ_CC_NAME))) @mock.patch(TASKTEMPLATE_GET, MagicMock(return_value=MockTaskTemplate())) @mock.patch(APIGW_VIEW_JSON_SCHEMA_VALIDATE, MagicMock()) @mock.patch(TASKINSTANCE_PREVIEW_TREE, MagicMock()) @mock.patch(PERIODIC_TASK_CREATE, MagicMock(side_effect=Exception())) def test_create_periodic_task__periodic_task_create_fail(self): response = self.client.post(path=self.CREATE_PERIODIC_TASK_URL.format( template_id=TEST_TEMPLATE_ID, bk_biz_id=TEST_BIZ_CC_ID), data=json.dumps({ 'name': 'name', 'cron': 'cron' }), content_type='application/json') data = json.loads(response.content) self.assertFalse(data['result']) self.assertTrue('message' in data) @mock.patch(BUSINESS_GET, MagicMock(return_value=MockBusiness())) def test_set_periodic_task_enabled__success(self): task = MockPeriodicTask() with mock.patch(PERIODIC_TASK_GET, MagicMock(return_value=task)): response = self.client.post( path=self.SET_PERIODIC_TASK_ENABLED_URL.format( task_id=TEST_PERIODIC_TASK_ID, bk_biz_id=TEST_BIZ_CC_ID), data=json.dumps({'enabled': True}), content_type='application/json') task.set_enabled.assert_called_once_with(True) data = json.loads(response.content) self.assertTrue(data['result']) self.assertEqual(data['data'], {'enabled': task.enabled}) @mock.patch(PERIODIC_TASK_GET, MagicMock(side_effect=PeriodicTask.DoesNotExist)) def test_set_periodic_task_enabled__task_does_not_exist(self): response = self.client.post( path=self.SET_PERIODIC_TASK_ENABLED_URL.format( task_id=TEST_PERIODIC_TASK_ID, bk_biz_id=TEST_BIZ_CC_ID), data=json.dumps({'enabled': True}), content_type='application/json') data = json.loads(response.content) self.assertFalse(data['result']) self.assertTrue('message' in data) def test_modify_cron_for_periodic_task__success(self): biz = MockBusiness() task = MockPeriodicTask() cron = {'minute': '*/1'} with mock.patch(BUSINESS_GET, MagicMock(return_value=biz)): with mock.patch(PERIODIC_TASK_GET, MagicMock(return_value=task)): response = self.client.post( path=self.MODIFY_PERIODIC_TASK_CRON_URL.format( task_id=TEST_PERIODIC_TASK_ID, bk_biz_id=TEST_BIZ_CC_ID), data=json.dumps({'cron': cron}), content_type='application/json') task.modify_cron.assert_called_once_with(cron, biz.time_zone) data = json.loads(response.content) self.assertTrue(data['result']) self.assertEqual(data['data'], {'cron': task.cron}) @mock.patch(BUSINESS_GET, MagicMock(return_value=MockBusiness())) @mock.patch(PERIODIC_TASK_GET, MagicMock(side_effect=PeriodicTask.DoesNotExist)) def test_modify_cron_for_periodic_task__task_does_not_exist(self): response = self.client.post( path=self.MODIFY_PERIODIC_TASK_CRON_URL.format( task_id=TEST_PERIODIC_TASK_ID, bk_biz_id=TEST_BIZ_CC_ID), data=json.dumps({'enabled': True}), content_type='application/json') data = json.loads(response.content) self.assertFalse(data['result']) self.assertTrue('message' in data) def test_modify_cron_for_periodic_task__modify_raise(self): biz = MockBusiness() task = MockPeriodicTask() task.modify_cron = MagicMock(side_effect=Exception()) cron = {'minute': '*/1'} with mock.patch(BUSINESS_GET, MagicMock(return_value=biz)): with mock.patch(PERIODIC_TASK_GET, MagicMock(return_value=task)): response = self.client.post( path=self.MODIFY_PERIODIC_TASK_CRON_URL.format( task_id=TEST_PERIODIC_TASK_ID, bk_biz_id=TEST_BIZ_CC_ID), data=json.dumps({'cron': cron}), content_type='application/json') data = json.loads(response.content) self.assertFalse(data['result']) self.assertTrue('message' in data) def test_modify_constants_for_periodic_task__success(self): biz = MockBusiness() task = MockPeriodicTask() constants = {'k': 'v'} with mock.patch(BUSINESS_GET, MagicMock(return_value=biz)): with mock.patch(PERIODIC_TASK_GET, MagicMock(return_value=task)): response = self.client.post( path=self.MODIFY_PERIODIC_TASK_CONSTANTS_URL.format( task_id=TEST_PERIODIC_TASK_ID, bk_biz_id=TEST_BIZ_CC_ID), data=json.dumps({'constants': constants}), content_type='application/json') task.modify_constants.assert_called_once_with(constants) data = json.loads(response.content) self.assertTrue(data['result']) self.assertEqual(data['data'], task.modify_constants.return_value) @mock.patch(PERIODIC_TASK_GET, MagicMock(side_effect=PeriodicTask.DoesNotExist)) def test_modify_constants_for_periodic_task__task_does_not_exist(self): response = self.client.post( path=self.MODIFY_PERIODIC_TASK_CONSTANTS_URL.format( task_id=TEST_PERIODIC_TASK_ID, bk_biz_id=TEST_BIZ_CC_ID), content_type='application/json') data = json.loads(response.content) self.assertFalse(data['result']) self.assertTrue('message' in data) def test_modify_constants_for_periodic_task__modify_constants_raise(self): biz = MockBusiness() task = MockPeriodicTask() task.modify_constants = MagicMock(side_effect=Exception()) with mock.patch(BUSINESS_GET, MagicMock(return_value=biz)): with mock.patch(PERIODIC_TASK_GET, MagicMock(return_value=task)): response = self.client.post( path=self.MODIFY_PERIODIC_TASK_CONSTANTS_URL.format( task_id=TEST_PERIODIC_TASK_ID, bk_biz_id=TEST_BIZ_CC_ID), content_type='application/json') data = json.loads(response.content) self.assertFalse(data['result']) self.assertTrue('message' in data)
class CreatePeriodicTaskAPITest(APITest): def url(self): return "/apigw/create_periodic_task/{template_id}/{project_id}/" @mock.patch(TASKINSTANCE_PREVIEW_TREE, MagicMock()) @mock.patch(APIGW_CREATE_PERIODIC_TASK_JSON_SCHEMA_VALIDATE, MagicMock()) def test_create_periodic_task__success(self): task = MockPeriodicTask() assert_data = { "id": task.id, "name": task.name, "template_id": task.template_id, "template_source": "project", "creator": task.creator, "cron": task.cron, "enabled": task.enabled, "last_run_at": format_datetime(task.last_run_at), "total_run_count": task.total_run_count, "form": task.form, "pipeline_tree": task.pipeline_tree, } proj = MockProject( project_id=TEST_PROJECT_ID, name=TEST_PROJECT_NAME, bk_biz_id=TEST_BIZ_CC_ID, from_cmdb=True, ) template = MockTaskTemplate() replace_template_id_mock = MagicMock() with mock.patch(TASKTEMPLATE_GET, MagicMock(return_value=template)): with mock.patch(PROJECT_GET, MagicMock(return_value=proj)): with mock.patch(PERIODIC_TASK_CREATE, MagicMock(return_value=task)): with mock.patch( APIGW_CREATE_PERIODIC_TASK_REPLACE_TEMPLATE_ID, replace_template_id_mock, ): response = self.client.post( path=self.url().format( template_id=TEST_TEMPLATE_ID, project_id=TEST_PROJECT_ID), data=json.dumps({ "name": task.name, "cron": task.cron, "template_source": "project", "exclude_task_nodes_id": "exclude_task_nodes_id", }), content_type="application/json", ) PipelineTemplateWebPreviewer.preview_pipeline_tree_exclude_task_nodes.assert_called_with( template.pipeline_tree, "exclude_task_nodes_id") PeriodicTask.objects.create.assert_called_once_with( project=proj, template=template, template_source="project", name=task.name, cron=task.cron, pipeline_tree=template.pipeline_tree, creator="", ) data = json.loads(response.content) replace_template_id_mock.assert_called_once_with( TaskTemplate, template.pipeline_tree) self.assertTrue(data["result"], msg=data) self.assertEqual(data["data"], assert_data) @mock.patch(TASKINSTANCE_PREVIEW_TREE, MagicMock()) @mock.patch(APIGW_CREATE_PERIODIC_TASK_JSON_SCHEMA_VALIDATE, MagicMock()) def test_create_periodic_task__common_template(self): task = MockPeriodicTask(template_source="common") assert_data = { "id": task.id, "name": task.name, "template_id": task.template_id, "template_source": "common", "creator": task.creator, "cron": task.cron, "enabled": task.enabled, "last_run_at": format_datetime(task.last_run_at), "total_run_count": task.total_run_count, "form": task.form, "pipeline_tree": task.pipeline_tree, } proj = MockProject( project_id=TEST_PROJECT_ID, name=TEST_PROJECT_NAME, bk_biz_id=TEST_BIZ_CC_ID, from_cmdb=True, ) template = MockCommonTemplate() replace_template_id_mock = MagicMock() with mock.patch(COMMONTEMPLATE_GET, MagicMock(return_value=template)): with mock.patch(PROJECT_GET, MagicMock(return_value=proj)): with mock.patch(PERIODIC_TASK_CREATE, MagicMock(return_value=task)): with mock.patch( APIGW_CREATE_PERIODIC_TASK_REPLACE_TEMPLATE_ID, replace_template_id_mock, ): response = self.client.post( path=self.url().format( template_id=TEST_TEMPLATE_ID, project_id=TEST_PROJECT_ID), data=json.dumps({ "name": task.name, "cron": task.cron, "template_source": "common", "exclude_task_nodes_id": "exclude_task_nodes_id", }), content_type="application/json", ) PipelineTemplateWebPreviewer.preview_pipeline_tree_exclude_task_nodes.assert_called_with( template.pipeline_tree, "exclude_task_nodes_id") PeriodicTask.objects.create.assert_called_once_with( project=proj, template=template, template_source="common", name=task.name, cron=task.cron, pipeline_tree=template.pipeline_tree, creator="", ) data = json.loads(response.content) replace_template_id_mock.assert_called_once_with( TaskTemplate, template.pipeline_tree) self.assertTrue(data["result"], msg=data) self.assertEqual(data["data"], assert_data) @mock.patch(TASKTEMPLATE_GET, MagicMock(side_effect=TaskTemplate.DoesNotExist())) def test_create_periodic_task__template_does_not_exist(self): response = self.client.post( path=self.url().format(template_id=TEST_TEMPLATE_ID, project_id=TEST_PROJECT_ID), content_type="application/json", ) data = json.loads(response.content) self.assertFalse(data["result"]) self.assertTrue("message" in data) @mock.patch(TASKTEMPLATE_GET, MagicMock(return_value=MockTaskTemplate())) @mock.patch( APIGW_CREATE_PERIODIC_TASK_JSON_SCHEMA_VALIDATE, MagicMock(side_effect=jsonschema.ValidationError("")), ) def test_create_periodic_task__params_validate_fail(self): response = self.client.post( path=self.url().format(template_id=TEST_TEMPLATE_ID, project_id=TEST_PROJECT_ID), content_type="application/json", ) data = json.loads(response.content) self.assertFalse(data["result"]) self.assertTrue("message" in data) @mock.patch(TASKTEMPLATE_GET, MagicMock(return_value=MockTaskTemplate())) @mock.patch(APIGW_CREATE_PERIODIC_TASK_JSON_SCHEMA_VALIDATE, MagicMock()) @mock.patch(TASKINSTANCE_PREVIEW_TREE, MagicMock(side_effect=Exception())) def test_create_periodic_task__preview_pipeline_fail(self): response = self.client.post( path=self.url().format(template_id=TEST_TEMPLATE_ID, project_id=TEST_PROJECT_ID), content_type="application/json", ) data = json.loads(response.content) self.assertFalse(data["result"]) self.assertTrue("message" in data) @mock.patch( PROJECT_GET, MagicMock(return_value=MockProject( project_id=TEST_PROJECT_ID, name=TEST_PROJECT_NAME, bk_biz_id=TEST_BIZ_CC_ID, from_cmdb=True, )), ) @mock.patch(TASKTEMPLATE_GET, MagicMock(return_value=MockTaskTemplate())) @mock.patch(APIGW_CREATE_PERIODIC_TASK_JSON_SCHEMA_VALIDATE, MagicMock()) @mock.patch(TASKINSTANCE_PREVIEW_TREE, MagicMock()) @mock.patch(APIGW_CREATE_PERIODIC_TASK_REPLACE_TEMPLATE_ID, MagicMock(side_effect=Exception)) def test_create_periodic_task__replace_template_id_fail(self): response = self.client.post( path=self.url().format(template_id=TEST_TEMPLATE_ID, project_id=TEST_PROJECT_ID), data=json.dumps({ "name": "name", "cron": "cron" }), content_type="application/json", ) data = json.loads(response.content) self.assertFalse(data["result"]) self.assertTrue("message" in data) @mock.patch( PROJECT_GET, MagicMock(return_value=MockProject( project_id=TEST_PROJECT_ID, name=TEST_PROJECT_NAME, bk_biz_id=TEST_BIZ_CC_ID, from_cmdb=True, )), ) @mock.patch(TASKTEMPLATE_GET, MagicMock(return_value=MockTaskTemplate())) @mock.patch(APIGW_CREATE_PERIODIC_TASK_JSON_SCHEMA_VALIDATE, MagicMock()) @mock.patch(TASKINSTANCE_PREVIEW_TREE, MagicMock()) @mock.patch(PERIODIC_TASK_CREATE, MagicMock(side_effect=Exception())) @mock.patch(APIGW_CREATE_PERIODIC_TASK_REPLACE_TEMPLATE_ID, MagicMock()) def test_create_periodic_task__periodic_task_create_fail(self): response = self.client.post( path=self.url().format(template_id=TEST_TEMPLATE_ID, project_id=TEST_PROJECT_ID), data=json.dumps({ "name": "name", "cron": "cron" }), content_type="application/json", ) data = json.loads(response.content) self.assertFalse(data["result"]) self.assertTrue("message" in data)
class GetTemplateInfoAPITest(APITest): def url(self): return "/apigw/get_template_info/{template_id}/{project_id}/" @mock.patch( PROJECT_GET, MagicMock(return_value=MockProject( project_id=TEST_PROJECT_ID, name=TEST_PROJECT_NAME, bk_biz_id=TEST_BIZ_CC_ID, from_cmdb=True, )), ) def test_get_template_info__for_project_template(self): pt1 = MockPipelineTemplate(id=1, name="pt1") tmpl = MockTaskTemplate(id=1, pipeline_template=pt1) with mock.patch( TASKTEMPLATE_SELECT_RELATE, MagicMock(return_value=MockQuerySet(get_result=tmpl)), ): pipeline_tree = copy.deepcopy(tmpl.pipeline_tree) pipeline_tree.pop("line") pipeline_tree.pop("location") assert_data = { "id": tmpl.id, "name": tmpl.pipeline_template.name, "creator": tmpl.pipeline_template.creator, "create_time": format_datetime(tmpl.pipeline_template.create_time), "editor": tmpl.pipeline_template.editor, "edit_time": format_datetime(tmpl.pipeline_template.edit_time), "category": tmpl.category, "project_id": TEST_PROJECT_ID, "project_name": TEST_PROJECT_NAME, "bk_biz_id": TEST_BIZ_CC_ID, "bk_biz_name": TEST_PROJECT_NAME, "pipeline_tree": pipeline_tree, } response = self.client.get(path=self.url().format( template_id=TEST_TEMPLATE_ID, project_id=TEST_PROJECT_ID)) data = json.loads(response.content) self.assertTrue(data["result"], msg=data) self.assertEqual(assert_data, data["data"]) @mock.patch( TASKTEMPLATE_SELECT_RELATE, MagicMock(return_value=MockQuerySet( get_raise=TaskTemplate.DoesNotExist())), ) @mock.patch( PROJECT_GET, MagicMock(return_value=MockProject( project_id=TEST_PROJECT_ID, name=TEST_PROJECT_NAME, bk_biz_id=TEST_BIZ_CC_ID, from_cmdb=True, )), ) def test_get_template_info__for_project_template_does_not_exists(self): response = self.client.get(path=self.url().format( template_id=TEST_TEMPLATE_ID, project_id=TEST_PROJECT_ID)) data = json.loads(response.content) self.assertFalse(data["result"]) self.assertTrue("message" in data) @mock.patch( PROJECT_GET, MagicMock(return_value=MockProject( project_id=TEST_PROJECT_ID, name=TEST_PROJECT_NAME, bk_biz_id=TEST_BIZ_CC_ID, from_cmdb=True, )), ) def test_get_template_info__for_common_template(self): pt1 = MockPipelineTemplate(id=1, name="pt1") tmpl = MockCommonTemplate(id=1, pipeline_template=pt1) with mock.patch( COMMONTEMPLATE_SELECT_RELATE, MagicMock(return_value=MockQuerySet(get_result=tmpl)), ): pipeline_tree = copy.deepcopy(tmpl.pipeline_tree) pipeline_tree.pop("line") pipeline_tree.pop("location") assert_data = { "id": tmpl.id, "name": tmpl.pipeline_template.name, "creator": tmpl.pipeline_template.creator, "create_time": format_datetime(tmpl.pipeline_template.create_time), "editor": tmpl.pipeline_template.editor, "edit_time": format_datetime(tmpl.pipeline_template.edit_time), "category": tmpl.category, "project_id": TEST_PROJECT_ID, "project_name": TEST_PROJECT_NAME, "bk_biz_id": TEST_BIZ_CC_ID, "bk_biz_name": TEST_PROJECT_NAME, "pipeline_tree": pipeline_tree, } response = self.client.get( path=self.url().format(template_id=TEST_TEMPLATE_ID, project_id=TEST_PROJECT_ID), data={"template_source": "common"}, ) data = json.loads(response.content) self.assertTrue(data["result"], msg=data) self.assertEqual(assert_data, data["data"]) @mock.patch( COMMONTEMPLATE_SELECT_RELATE, MagicMock(return_value=MockQuerySet( get_raise=CommonTemplate.DoesNotExist())), ) @mock.patch( PROJECT_GET, MagicMock(return_value=MockProject( project_id=TEST_PROJECT_ID, name=TEST_PROJECT_NAME, bk_biz_id=TEST_BIZ_CC_ID, from_cmdb=True, )), ) def test_get_template_info__for_common_template_does_not_exists(self): response = self.client.get( path=self.url().format(template_id=TEST_TEMPLATE_ID, project_id=TEST_PROJECT_ID), data={"template_source": "common"}, ) data = json.loads(response.content) self.assertFalse(data["result"]) self.assertTrue("message" in data)