Update job api models 14/86514/2
authormaopengzhang <zhang.maopeng1@zte.com.cn>
Mon, 29 Apr 2019 11:43:48 +0000 (19:43 +0800)
committermaopengzhang <zhang.maopeng1@zte.com.cn>
Mon, 29 Apr 2019 12:28:53 +0000 (20:28 +0800)
Update job api models and add tests

Change-Id: I7e349c604077c817d453cc260563cb0516c07589
Issue-ID: VFC-1241
Signed-off-by: maopengzhang <zhang.maopeng1@zte.com.cn>
lcm/jobs/api_model.py
lcm/jobs/job_get.py
lcm/jobs/tests/__init__.py
lcm/jobs/tests/tests.py
lcm/jobs/tests/update_job.json [new file with mode: 0644]
lcm/jobs/views.py
lcm/pub/base.py [new file with mode: 0644]

index 87266fa..6154539 100644 (file)
 # See the License for the specific language governing permissions and
 # limitations under the License.
 
+from lcm.pub.base import ApiModelBase
 
-class JobHistory(object):
+
+class JobHistory(ApiModelBase):
     def __init__(self, status="", progress="", statusDescription="", errorCode="", responseId=""):
         self.status = status
         self.progress = progress
@@ -22,39 +24,30 @@ class JobHistory(object):
         self.responseId = responseId
 
 
-class JobDescriptor(object):
-    def __init__(self, status="", progress=0, statusDescription="", errorCode="", responseId="", responseHistoryList=None):
-        self.status = status
-        self.progress = progress
-        self.statusDescription = statusDescription
-        self.errorCode = errorCode
-        self.responseId = responseId
-        self.responseHistoryList = responseHistoryList
+class JobDescriptor(ApiModelBase):
+    def __init__(self, status="", progress=0, statusDescription="", errorCode="", responseId="", responseHistoryList=None, dict_str=None):
+        self.status = dict_str.get("status", "") if dict_str else status
+        self.progress = dict_str.get("progress", 0) if dict_str else progress
+        self.statusDescription = dict_str.get("statusDescription", "") if dict_str else statusDescription
+        self.errorCode = dict_str.get("errorCode", "") if dict_str else errorCode
+        self.responseId = dict_str.get("responseId", "") if dict_str else responseId
+        self.responseHistoryList = [JobHistory(job_history) for job_history in dict_str.get("responseHistoryList", None)] if dict_str else responseHistoryList
 
 
-class JobQueryResp(object):
-    def __init__(self, jobId="", responseDescriptor=None):
-        self.jobId = jobId
-        self.responseDescriptor = responseDescriptor
+class JobQueryResp(ApiModelBase):
+    def __init__(self, jobId="", responseDescriptor=None, dict_str=None):
+        self.jobId = dict_str.get("jobId", "") if dict_str else jobId
+        self.responseDescriptor = JobDescriptor(dict_str=dict_str.get("responseDescriptor", None)) if dict_str else responseDescriptor
 
 
-class JobUpdReq(object):
+class JobUpdReq(ApiModelBase):
     def __init__(self, progress="", desc="", errcode=""):
         self.progress = progress
         self.desc = desc
         self.errcode = errcode
 
-    def load(self, data):
-        self.progress = data["progress"]
-        self.desc = data["desc"]
-        self.errcode = data["errcode"]
 
-
-class JobUpdResp(object):
+class JobUpdResp(ApiModelBase):
     def __init__(self, result="", msg=""):
         self.result = result
         self.msg = msg
-
-    def load(self, data):
-        self.result = data["result"]
-        self.msg = data["msg"]
index 48edce9..d3ebc2f 100644 (file)
@@ -16,7 +16,6 @@ import logging
 from lcm.pub.utils.jobutil import JobUtil
 from lcm.pub.utils.values import remove_none_key
 from lcm.jobs.api_model import JobQueryResp, JobDescriptor, JobHistory
-from lcm.jobs.serializers import JobQueryRespSerializer
 
 
 logger = logging.getLogger(__name__)
@@ -32,8 +31,7 @@ class GetJobInfoService(object):
         jobs = JobUtil.query_job_status(self.job_id, self.response_id)
         if not jobs:
             job_query_resp = JobQueryResp(self.job_id)
-            job_query_resp_serializer = JobQueryRespSerializer(job_query_resp)
-            return remove_none_key(job_query_resp_serializer.data)
+            return remove_none_key(job_query_resp.to_dict())
         job_query_resp = JobQueryResp(
             self.job_id,
             JobDescriptor(
@@ -53,5 +51,4 @@ class GetJobInfoService(object):
                 ]
             )
         )
-        job_query_resp_serializer = JobQueryRespSerializer(job_query_resp)
-        return remove_none_key(job_query_resp_serializer.data)
+        return remove_none_key(job_query_resp.to_dict())
index 5580cc3..ecbf03a 100644 (file)
@@ -11,3 +11,9 @@
 # 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.
+
+import os
+from lcm.pub.utils import fileutil
+
+cur_path = os.path.dirname(os.path.abspath(__file__))
+UPDATE_JOB_DICT = fileutil.read_json_file(cur_path + '/update_job.json')
index 0e2f0c4..a5e376b 100644 (file)
@@ -16,6 +16,7 @@ from rest_framework.test import APIClient
 from rest_framework import status
 
 from lcm.pub.database.models import JobModel, JobStatusModel
+from lcm.jobs.tests import UPDATE_JOB_DICT
 
 
 class JobsViewTest(TestCase):
@@ -59,3 +60,9 @@ class JobsViewTest(TestCase):
         self.assertIn('responseDescriptor', response.data)
         self.assertEqual(100, response.data['responseDescriptor']['progress'])
         self.assertEqual(1, len(response.data['responseDescriptor']['responseHistoryList']))
+
+    def test_up_job(self):
+        JobModel(jobid=self.job_id, jobtype='VNF', jobaction='INST', resid='1').save()
+        JobStatusModel(indexid=1, jobid=self.job_id, status='inst', progress=20, descp='inst', errcode="0").save()
+        response = self.client.post("/api/nslcm/v1/jobs/%s" % self.job_id, format='json', data=UPDATE_JOB_DICT)
+        self.assertEqual(status.HTTP_202_ACCEPTED, response.status_code)
diff --git a/lcm/jobs/tests/update_job.json b/lcm/jobs/tests/update_job.json
new file mode 100644 (file)
index 0000000..5d763b7
--- /dev/null
@@ -0,0 +1,5 @@
+{
+    "progress": "100",
+    "desc": "completed",
+    "errcode": "0"
+}
index dddb853..1fbaf0d 100644 (file)
@@ -82,11 +82,10 @@ class JobView(APIView):
 
             jobs = JobUtil.query_job_status(job_id)
             if not jobs:
-                raise NSLCMException("Job(%s) does not exist.")
+                raise NSLCMException("Job(%s) does not exist." % job_id)
 
             if jobs[-1].errcode != JOB_ERROR_CODE.ERROR:
-                job_up_req = JobUpdReq()
-                job_up_req.load(request.data)
+                job_up_req = JobUpdReq(**request.data)
                 desc = job_up_req.desc
                 errcode = JOB_ERROR_CODE.NO_ERROR if job_up_req.errcode in ('true', 'active') else JOB_ERROR_CODE.ERROR
                 logger.debug("errcode=%s", errcode)
diff --git a/lcm/pub/base.py b/lcm/pub/base.py
new file mode 100644 (file)
index 0000000..068691f
--- /dev/null
@@ -0,0 +1,31 @@
+# Copyright 2019 ZTE Corporation.
+#
+# Licensed 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.
+
+
+class ApiModelBase(object):
+    def to_dict(self):
+        r_dict = to_dict(self)
+        return r_dict
+
+
+def to_dict(instance, cls=ApiModelBase):
+    r_dict = {}
+    for k, v in instance.__dict__.iteritems():
+        if isinstance(v, cls):
+            r_dict[k] = to_dict(v)
+        elif isinstance(v, list):
+            r_dict[k] = [to_dict(v_instance) for v_instance in v]
+        else:
+            r_dict[k] = v
+    return r_dict