From 3ff9cccbdee6b4528046e3a990148d4bce116825 Mon Sep 17 00:00:00 2001 From: Sarah Lima Date: Thu, 25 Jun 2020 11:50:40 -0300 Subject: [PATCH 1/5] Add service orders patch --- api/v2/controllers/dtos/__init__.py | 0 .../controllers/dtos/service_order_request.py | 13 ++++++ .../dtos/service_orders_request.py | 6 +++ .../service_orders_many_controller.py | 14 ++++++- api/v2/routes.py | 0 api/v2/services/service_order_service.py | 12 ++++++ config/routes.py | 5 ++- tests/v2/controllers/fixtures/__init__.py | 0 .../v2/controllers/fixtures/service_orders.py | 4 ++ tests/v2/controllers/test_service_orders.py | 40 +++++++++++-------- 10 files changed, 76 insertions(+), 18 deletions(-) create mode 100644 api/v2/controllers/dtos/__init__.py create mode 100644 api/v2/controllers/dtos/service_order_request.py create mode 100644 api/v2/controllers/dtos/service_orders_request.py create mode 100644 api/v2/routes.py create mode 100644 tests/v2/controllers/fixtures/__init__.py create mode 100644 tests/v2/controllers/fixtures/service_orders.py diff --git a/api/v2/controllers/dtos/__init__.py b/api/v2/controllers/dtos/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/api/v2/controllers/dtos/service_order_request.py b/api/v2/controllers/dtos/service_order_request.py new file mode 100644 index 0000000..5b14b00 --- /dev/null +++ b/api/v2/controllers/dtos/service_order_request.py @@ -0,0 +1,13 @@ +class ServiceOrderRequest(): + def __init__(self, data): + self.tipo = data['tipo'] + self.data = data + + def get(self): + return self.data + + def valid(self): + return True + + def errors(self): + return [{}] \ No newline at end of file diff --git a/api/v2/controllers/dtos/service_orders_request.py b/api/v2/controllers/dtos/service_orders_request.py new file mode 100644 index 0000000..6a4bbfa --- /dev/null +++ b/api/v2/controllers/dtos/service_orders_request.py @@ -0,0 +1,6 @@ +class ServiceOrdersRequest(): + def __init__(self, data): + self.data = data + + def errors(self): + pass \ No newline at end of file diff --git a/api/v2/controllers/service_orders_many_controller.py b/api/v2/controllers/service_orders_many_controller.py index cfffc9f..78fcc2c 100644 --- a/api/v2/controllers/service_orders_many_controller.py +++ b/api/v2/controllers/service_orders_many_controller.py @@ -4,7 +4,7 @@ from ..services.service_order_service import ServiceOrderService from http import HTTPStatus from flask import request - +from .dtos.service_order_request import ServiceOrderRequest class ServiceOrdersManyController(Resource): def get(self): @@ -18,3 +18,15 @@ def get(self): service_orders = ServiceOrderService().fetch_active() return get_response(service_orders, deleted_included) + + def patch(self, id=None): + body = request.get_json() + + service_order_request = ServiceOrderRequest(body['content']) + so = service_order_request.get() + + ServiceOrderService().update(so) + return "", 200 + + + diff --git a/api/v2/routes.py b/api/v2/routes.py new file mode 100644 index 0000000..e69de29 diff --git a/api/v2/services/service_order_service.py b/api/v2/services/service_order_service.py index 28e6791..4eaedd7 100644 --- a/api/v2/services/service_order_service.py +++ b/api/v2/services/service_order_service.py @@ -11,3 +11,15 @@ def fetch_active(self): def fetch_all(self): return self.parser_mongo_response_to_list( OrdemServico.objects()) + + def update(self, id): + pass + + def insert_or_update(self, service_order): + if '_id' in service_order.keys(): + update(service_order) + else: + insert(service_order) + + def insert(self, service_order): + pass diff --git a/config/routes.py b/config/routes.py index 3c34aba..9eb0a1e 100644 --- a/config/routes.py +++ b/config/routes.py @@ -66,5 +66,8 @@ def initialize_routes(api): api.add_resource(items_many_controller.ItemsManyController, '/v2/items') api.add_resource(service_order_image_controller.ServiceOrderImageController, '/v2/service_order//foto_antes_limpeza.jpg') api.add_resource(items_migration_base.ItemsMigrationBase, '/v2/items/migrate') - api.add_resource(service_orders_many_controller.ServiceOrdersManyController, '/v2/service_orders') + api.add_resource(service_orders_many_controller.ServiceOrdersManyController, *[ + '/v2/service_orders/', + '/v2/service_orders', + ]) diff --git a/tests/v2/controllers/fixtures/__init__.py b/tests/v2/controllers/fixtures/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/v2/controllers/fixtures/service_orders.py b/tests/v2/controllers/fixtures/service_orders.py new file mode 100644 index 0000000..0af4a8f --- /dev/null +++ b/tests/v2/controllers/fixtures/service_orders.py @@ -0,0 +1,4 @@ +def valid_service_order(): + return { + "content": { "id": "1", "tipo": "Tipo 1"} + } \ No newline at end of file diff --git a/tests/v2/controllers/test_service_orders.py b/tests/v2/controllers/test_service_orders.py index 9e1de3d..39834e5 100644 --- a/tests/v2/controllers/test_service_orders.py +++ b/tests/v2/controllers/test_service_orders.py @@ -1,16 +1,17 @@ import json from run import app from unittest import TestCase -from mockito import when, mock +from mockito import when +from unittest.mock import MagicMock, patch from api.v2.services.service_order_service import ServiceOrderService from http import HTTPStatus - +from .fixtures.service_orders import valid_service_order class ServiceOrdersController(TestCase): def setUp(self): self.client = app.test_client() - def test_returns_service_orders_on_successful_request(self): + def test_get_returns_service_orders_on_successful_request(self): service_orders = [{'equipamento_id': 1, 'numero_ordem_servico': '0400'}] when(ServiceOrderService).fetch_active().thenReturn(service_orders) @@ -18,22 +19,12 @@ def test_returns_service_orders_on_successful_request(self): self.assertEqual(response.status_code, HTTPStatus.OK) content = response.json['content'] - self.assertEqual(type(content), list) + self.assertEqual(type(content), list) self.assertIn('content', response.json) self.assertIn('equipamento_id', content[0]) self.assertEqual(content[0]['equipamento_id'], service_orders[0]['equipamento_id']) - - def test_returns_empty_list(self): - service_orders = [] - when(ServiceOrderService).fetch_active().thenReturn(service_orders) - - response = self.client.get('/v2/service_orders') - - self.assertEqual(response.status_code, HTTPStatus.OK) - self.assertEqual(response.json['content'], []) - - def test_returns_deleted_service_orders_on_successful_request(self): + def test_get_returns_deleted_service_orders_on_successful_request(self): service_orders = [{'equipamento_id': 1, 'numero_ordem_servico': '0400'}] when(ServiceOrderService).fetch_all().thenReturn(service_orders) @@ -43,7 +34,24 @@ def test_returns_deleted_service_orders_on_successful_request(self): content = response.json['content'] self.assertEqual(content[0]['equipamento_id'], service_orders[0]['equipamento_id']) - def test_return_invalid_param_error(self): + def test_get_return_invalid_param_error(self): response = self.client.get('/v2/service_orders?deleted=trueee') self.assertEqual(response.status_code, HTTPStatus.BAD_REQUEST) self.assertEqual(response.json['error'], 'Parameter deleted is not equal true.') + + def test_patch_with_id(self): + payload = json.dumps(valid_service_order()) + + with patch.object(ServiceOrderService, 'update', return_value=None) as mock_method: + service = ServiceOrderService() + response = self.client.patch('/v2/service_orders', + headers={"Content-Type": "application/json"}, + data=payload) + + + self.assertEqual(response.status_code, HTTPStatus.OK) + + mock_method.assert_called_with(valid_service_order()['content']) + + + From d98a40e0907502fcf85e63d112fc936fd60a4548 Mon Sep 17 00:00:00 2001 From: adrilene Date: Mon, 29 Jun 2020 11:55:44 -0300 Subject: [PATCH 2/5] =?UTF-8?q?[@adrilene/@denisousa]=20Issue=20#91=20-=20?= =?UTF-8?q?Iniciando=20valida=C3=A7=C3=B5es=20de=20PATCH.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../service_orders_many_controller.py | 24 ++++++++++++----- .../validators/validation_request.py | 18 ++++++++----- api/v2/models/schemas/schema_base.py | 6 +++++ api/v2/models/schemas/service_order_schema.py | 4 +++ api/v2/services/service_order_service.py | 3 +++ .../v2/controllers/fixtures/service_orders.py | 4 +-- tests/v2/controllers/test_service_orders.py | 26 ++++++++++++++++--- tests/v2/mocks/mock_service_orders.py | 5 +++- 8 files changed, 72 insertions(+), 18 deletions(-) diff --git a/api/v2/controllers/service_orders_many_controller.py b/api/v2/controllers/service_orders_many_controller.py index 8507b93..bf2fa3b 100644 --- a/api/v2/controllers/service_orders_many_controller.py +++ b/api/v2/controllers/service_orders_many_controller.py @@ -4,11 +4,10 @@ from flask_restful import Resource from ..helpers.helper_response import get_response from ..validation.validation_request import invalid_deleted_parameter -from api.v2.controllers.validators.validation_request import validate_request +from api.v2.controllers.validators.validation_request import validate_request, validate_request_id, validate_request_dict_id from api.v2.services.service_order_service import ServiceOrderService from api.v2.models.schemas.service_order_schema import ServiceOrderSchema from api.v2.utils.util_response import error_response, post_response -from .validators.validation_request import validate_request_id class ServiceOrdersManyController(Resource): @@ -25,13 +24,26 @@ def get(self): return get_response(service_orders, deleted_included) - def patch(self, id=None): + def patch(self): body = request.get_json() + validade, message = validate_request(body) + if not validate: + return error_response(message) + + errors = [] + for index, service_order in enumerate(body['content']): + validate, message = validate_request_dict_id('service_order', service_order) + if not validate: + errors.append({index: message}) - service_order_request = ServiceOrderRequest(body["content"]) - so = service_order_request.get() + # ServiceOrderSchema().validate_updates(service_order, index) + # service_order_request = ServiceOrderRequest(body["content"]) + # so = service_order_request.get() + + # ServiceOrderService().update(so) + if errors: + return error_response(errors) - ServiceOrderService().update(so) return "", 200 def post(self): diff --git a/api/v2/controllers/validators/validation_request.py b/api/v2/controllers/validators/validation_request.py index 83469d7..4630c3f 100644 --- a/api/v2/controllers/validators/validation_request.py +++ b/api/v2/controllers/validators/validation_request.py @@ -1,6 +1,7 @@ from bson import ObjectId from api.v2.services.item_service import ItemService from api.services.equipamento_service import listar_equipamento_by_id +from ...services.service_order_service import ServiceOrderService def invalid_deleted_parameter(param): @@ -61,28 +62,33 @@ def validate_id_exists(entity, _id): if not listar_equipamento_by_id(_id): return (False, "Nonexistent equipamento ID") + if entity == "service_order": + if not ServiceOrderService().fetch_service_order_by_id(_id): + return (False, "Nonexistent service order ID") + + return (True, "OK") -def validate_request_dict_id(entity): +def validate_request_dict_id(name_entity: str, entity: dict): validate, message = validate_id_included(entity) if not validate: return (validate, message) - validate, message = validate_request_id(entity["_id"]) + validate, message = validate_request_id(name_entity, entity["_id"]) if not validate: return (validate, message) return (True, "OK") -def validate_request_id(entity, _id): +def validate_request_id(name_entity: str, _id: str): validate, message = validate_id_objectID(_id) if not validate: - return (validate, message) + return validate, message - validate, message = validate_id_exists(entity, _id) + validate, message = validate_id_exists(name_entity, _id) if not validate: - return (validate, message) + return validate, message return (True, "OK") diff --git a/api/v2/models/schemas/schema_base.py b/api/v2/models/schemas/schema_base.py index 3af3175..b6c9e52 100644 --- a/api/v2/models/schemas/schema_base.py +++ b/api/v2/models/schemas/schema_base.py @@ -18,3 +18,9 @@ def validate_save(self, body): return False, err.messages return True, "OK" + + def validate_updates(self, entity: dict, index: int, fields: tuple): + try: + self.load(entity, partial=fields) + except ValidationError as err: + return {index: err.messages} diff --git a/api/v2/models/schemas/service_order_schema.py b/api/v2/models/schemas/service_order_schema.py index 88228f8..e6ec4fa 100644 --- a/api/v2/models/schemas/service_order_schema.py +++ b/api/v2/models/schemas/service_order_schema.py @@ -90,3 +90,7 @@ class Meta: calibragem = fields.Nested(CalibrationSchema, required=True) status = fields.String(validate=validate.OneOf(["triagem", "diagnostico"]), required=True) + + def validate_updates(self, service_order: dict, index: int, fields: tuple): + fields = ('numero_ordem_servico', 'calibragem', 'status') + super().validate_updates(service_order, index, fields) diff --git a/api/v2/services/service_order_service.py b/api/v2/services/service_order_service.py index 895b4a7..ccbc2b7 100644 --- a/api/v2/services/service_order_service.py +++ b/api/v2/services/service_order_service.py @@ -11,6 +11,9 @@ def fetch_active(self): def fetch_all(self): return self.parser_mongo_response_to_list(OrdemServico.objects()) + def fetch_service_order_by_id(self): + return OrdemServico.objects(id=_id).first() + def update(self, id): pass diff --git a/tests/v2/controllers/fixtures/service_orders.py b/tests/v2/controllers/fixtures/service_orders.py index 0af4a8f..83ff9be 100644 --- a/tests/v2/controllers/fixtures/service_orders.py +++ b/tests/v2/controllers/fixtures/service_orders.py @@ -1,4 +1,4 @@ def valid_service_order(): return { - "content": { "id": "1", "tipo": "Tipo 1"} - } \ No newline at end of file + "content": { "id": "1", "tipo": "Tipo 1"} + } diff --git a/tests/v2/controllers/test_service_orders.py b/tests/v2/controllers/test_service_orders.py index 29ae897..70f51f9 100644 --- a/tests/v2/controllers/test_service_orders.py +++ b/tests/v2/controllers/test_service_orders.py @@ -19,7 +19,7 @@ def test_get_returns_service_orders_on_successful_request(self): when(ServiceOrderService).fetch_active().thenReturn(service_orders) response = self.client.get("/v2/service_orders") -api.add_resource(service_orders_many_controller.ServiceOrdersManyController, *[ + api.add_resource(service_orders_many_controller.ServiceOrdersManyController, *[ '/v2/service_orders/', '/v2/service_orders', ]) @@ -67,8 +67,6 @@ def test_patch_with_id(self): mock_method.assert_called_with(valid_service_order()['content']) - - # POST tests def test_returns_list_with_the_saved_ids(self): service_order_id = "5ee37c19d86b6a8893d1a3a7" # Fake Id @@ -89,3 +87,25 @@ def test_returns_list_with_the_saved_ids(self): self.assertEqual(type(response.json["content"]), list) for id in response.json["content"]: self.assertEqual(ObjectId.is_valid(id), True) + + # PATCH tests + def test_service_order_has_patch_route(self): + response = self.client.patch( + '/v2/service_order', + headers={"Content-Type": "application/json"}) + self.assertNotEqual(response.status_code, 405) + + def test_patch_service_order_has_empty_body(self): + response = self.client.patch( + '/v2/service_order', + headers={"Content-Type": "application/json"}) + self.assertNotEqual(response.status_code, 405) + + def test_patch_service_order_has_wrong_field(self): + pass + + def test_patch_service_order_has_invalid_id(self): + pass + + def test_patch_service_order_has_nonexistent_id(self): + pass diff --git a/tests/v2/mocks/mock_service_orders.py b/tests/v2/mocks/mock_service_orders.py index f717a3c..dfc7f8e 100644 --- a/tests/v2/mocks/mock_service_orders.py +++ b/tests/v2/mocks/mock_service_orders.py @@ -63,6 +63,9 @@ "calibragem": { "status": "TESTE" } - } + }, + + 'valid_patch': + } From b88e7a94eb230bdde5ea564312a9477e248e6698 Mon Sep 17 00:00:00 2001 From: denisousa Date: Tue, 30 Jun 2020 10:56:45 -0300 Subject: [PATCH 3/5] [@adrilene/@denisousa/@sarahraqueld] issue #91 testes e update da ordem de servico finalizados. --- .../service_orders_many_controller.py | 31 ++-- .../validators/validation_request.py | 2 +- api/v2/models/schemas/schema_base.py | 6 +- api/v2/models/schemas/service_order_schema.py | 6 +- api/v2/services/service_order_service.py | 12 +- api/v2/utils/util_update.py | 39 +++++ tests/v2/controllers/test_service_orders.py | 135 +++++++++++++----- tests/v2/mocks/mock_service_orders.py | 58 +++----- 8 files changed, 195 insertions(+), 94 deletions(-) create mode 100644 api/v2/utils/util_update.py diff --git a/api/v2/controllers/service_orders_many_controller.py b/api/v2/controllers/service_orders_many_controller.py index bf2fa3b..8aa79c6 100644 --- a/api/v2/controllers/service_orders_many_controller.py +++ b/api/v2/controllers/service_orders_many_controller.py @@ -4,10 +4,15 @@ from flask_restful import Resource from ..helpers.helper_response import get_response from ..validation.validation_request import invalid_deleted_parameter -from api.v2.controllers.validators.validation_request import validate_request, validate_request_id, validate_request_dict_id +from api.v2.controllers.validators.validation_request import ( + validate_request, + validate_request_id, + validate_request_dict_id, +) from api.v2.services.service_order_service import ServiceOrderService from api.v2.models.schemas.service_order_schema import ServiceOrderSchema from api.v2.utils.util_response import error_response, post_response +from ..utils.util_update import pop_id class ServiceOrdersManyController(Resource): @@ -26,24 +31,30 @@ def get(self): def patch(self): body = request.get_json() - validade, message = validate_request(body) - if not validate: + validate, message = validate_request(body) + if not validate: return error_response(message) errors = [] - for index, service_order in enumerate(body['content']): - validate, message = validate_request_dict_id('service_order', service_order) - if not validate: + for index, service_order in enumerate(body["content"]): + validate, message = ServiceOrderSchema().validate_updates( + service_order, index + ) + + if not validate: errors.append({index: message}) - # ServiceOrderSchema().validate_updates(service_order, index) - # service_order_request = ServiceOrderRequest(body["content"]) - # so = service_order_request.get() + validate, message = validate_request_dict_id("service_order", service_order) + if not validate: + errors.append({index: message}) - # ServiceOrderService().update(so) if errors: return error_response(errors) + for index, service_order in enumerate(body["content"]): + id = pop_id(service_order) + ServiceOrderService().update(id, service_order) + return "", 200 def post(self): diff --git a/api/v2/controllers/validators/validation_request.py b/api/v2/controllers/validators/validation_request.py index 4630c3f..cb46756 100644 --- a/api/v2/controllers/validators/validation_request.py +++ b/api/v2/controllers/validators/validation_request.py @@ -32,6 +32,7 @@ def validate_request(body): if not len(body["content"]): return (False, "Empty list. Nothing to do.") + for item in body["content"]: if not item: return (False, "Some entry has no data.") @@ -66,7 +67,6 @@ def validate_id_exists(entity, _id): if not ServiceOrderService().fetch_service_order_by_id(_id): return (False, "Nonexistent service order ID") - return (True, "OK") diff --git a/api/v2/models/schemas/schema_base.py b/api/v2/models/schemas/schema_base.py index b6c9e52..1cf8f5c 100644 --- a/api/v2/models/schemas/schema_base.py +++ b/api/v2/models/schemas/schema_base.py @@ -1,7 +1,8 @@ from marshmallow import ValidationError +from marshmallow import Schema -class SchemaBase: +class SchemaBase(Schema): def validate_save(self, body): if "_id" in body: return False, "Id must not be sent" @@ -22,5 +23,6 @@ def validate_save(self, body): def validate_updates(self, entity: dict, index: int, fields: tuple): try: self.load(entity, partial=fields) + return True, "OK" except ValidationError as err: - return {index: err.messages} + return False, err.messages diff --git a/api/v2/models/schemas/service_order_schema.py b/api/v2/models/schemas/service_order_schema.py index e6ec4fa..158eea3 100644 --- a/api/v2/models/schemas/service_order_schema.py +++ b/api/v2/models/schemas/service_order_schema.py @@ -65,7 +65,7 @@ class Meta: status = fields.String(required=False) -class ServiceOrderSchema(Schema, SchemaBase): +class ServiceOrderSchema(SchemaBase): class Meta: model = service_order_model.OrdemServico fields = ("_id", @@ -91,6 +91,6 @@ class Meta: status = fields.String(validate=validate.OneOf(["triagem", "diagnostico"]), required=True) - def validate_updates(self, service_order: dict, index: int, fields: tuple): + def validate_updates(self, service_order: dict, index: int): fields = ('numero_ordem_servico', 'calibragem', 'status') - super().validate_updates(service_order, index, fields) + return super().validate_updates(service_order, index, fields) diff --git a/api/v2/services/service_order_service.py b/api/v2/services/service_order_service.py index ccbc2b7..0b8d610 100644 --- a/api/v2/services/service_order_service.py +++ b/api/v2/services/service_order_service.py @@ -1,6 +1,6 @@ from .service_base import ServiceBase from ..models.service_order_model import OrdemServico - +from ..utils.util_update import update_only_fields class ServiceOrderService(ServiceBase): def fetch_active(self): @@ -11,17 +11,17 @@ def fetch_active(self): def fetch_all(self): return self.parser_mongo_response_to_list(OrdemServico.objects()) - def fetch_service_order_by_id(self): + def fetch_service_order_by_id(self, _id): return OrdemServico.objects(id=_id).first() - def update(self, id): - pass + def update(self, id, service_order): + update_only_fields(_id=id, data=service_order, model=OrdemServico) def insert_or_update(self, service_order): if "_id" in service_order.keys(): - update(service_order) + self.update(service_order) else: - insert(service_order) + self.insert(service_order) def insert(self, service_order): pass diff --git a/api/v2/utils/util_update.py b/api/v2/utils/util_update.py new file mode 100644 index 0000000..4a08df7 --- /dev/null +++ b/api/v2/utils/util_update.py @@ -0,0 +1,39 @@ +def pop_id(data): + id = data['_id'] + try: + del data['_id'] + except Exception: + pass + + return id + + +def define_updated_fields(current_key, current_value): + """ + current_key: String + current_value: Any Primitive type + """ + query = {} + if type(current_value) == dict: + for k, v in current_value.items(): + query.update(define_updated_fields( + current_key + "__{}".format(k), v)) + + else: + query[current_key] = current_value + + return query + + +def update_only_fields(_id, data, model): + """ + _id: ObjectId + data: Dict + model: Mongoengine.Document + """ + query = {} + root_key = "set" + root_value = data + query.update(define_updated_fields(root_key, root_value)) + + model.objects(id=_id).update(**query) diff --git a/tests/v2/controllers/test_service_orders.py b/tests/v2/controllers/test_service_orders.py index 70f51f9..b47e625 100644 --- a/tests/v2/controllers/test_service_orders.py +++ b/tests/v2/controllers/test_service_orders.py @@ -3,6 +3,9 @@ from unittest import TestCase from mockito import when from unittest.mock import MagicMock, patch +from api.v2.controllers.service_orders_many_controller import ( + ServiceOrdersManyController, +) from api.v2.services.service_order_service import ServiceOrderService from http import HTTPStatus from .fixtures.service_orders import valid_service_order @@ -15,23 +18,26 @@ def setUp(self): self.client = app.test_client() def test_get_returns_service_orders_on_successful_request(self): - service_orders = [{'equipamento_id': 1, 'numero_ordem_servico': '0400'}] + service_orders = [{"equipamento_id": 1, "numero_ordem_servico": "0400"}] when(ServiceOrderService).fetch_active().thenReturn(service_orders) response = self.client.get("/v2/service_orders") - api.add_resource(service_orders_many_controller.ServiceOrdersManyController, *[ - '/v2/service_orders/', - '/v2/service_orders', - ]) + app.add_resource( + ServiceOrdersManyController, + *["/v2/service_orders/", "/v2/service_orders",] + ) self.assertEqual(response.status_code, HTTPStatus.OK) - content = response.json['content'] - self.assertEqual(type(content), list) - self.assertIn('content', response.json) - self.assertIn('equipamento_id', content[0]) - self.assertEqual(content[0]['equipamento_id'], service_orders[0]['equipamento_id']) + content = response.json["content"] + self.assertEqual(type(content), list) + self.assertIn("content", response.json) + self.assertIn("equipamento_id", content[0]) + self.assertEqual( + content[0]["equipamento_id"], service_orders[0]["equipamento_id"] + ) def test_get_returns_deleted_service_orders_on_successful_request(self): - service_orders = [{'equipamento_id': 1, 'numero_ordem_servico': '0400'}] + service_orders = [{"equipamento_id": 1, "numero_ordem_servico": "0400"}] + response = self.client.get("/v2/service_orders/?deleted=true") content = response.json["content"] self.assertEqual(type(content), list) self.assertIn("content", response.json) @@ -50,22 +56,26 @@ def test_returns_empty_list(self): self.assertEqual(response.json["content"], []) def test_get_return_invalid_param_error(self): - response = self.client.get('/v2/service_orders?deleted=trueee') + response = self.client.get("/v2/service_orders?deleted=trueee") self.assertEqual(response.status_code, HTTPStatus.BAD_REQUEST) - self.assertEqual(response.json['error'], 'Parameter deleted is not equal true.') + self.assertEqual(response.json["error"], "Parameter deleted is not equal true.") def test_patch_with_id(self): payload = json.dumps(valid_service_order()) - with patch.object(ServiceOrderService, 'update', return_value=None) as mock_method: + with patch.object( + ServiceOrderService, "update", return_value=None + ) as mock_method: service = ServiceOrderService() - response = self.client.patch('/v2/service_orders', - headers={"Content-Type": "application/json"}, - data=payload) + response = self.client.patch( + "/v2/service_orders", + headers={"Content-Type": "application/json"}, + data=payload, + ) self.assertEqual(response.status_code, HTTPStatus.OK) - mock_method.assert_called_with(valid_service_order()['content']) + mock_method.assert_called_with(valid_service_order()["content"]) # POST tests def test_returns_list_with_the_saved_ids(self): @@ -74,9 +84,7 @@ def test_returns_list_with_the_saved_ids(self): mock_service_orders["complete_to_mockito"] ).thenReturn(service_order_id) - payload = json.dumps( - {"content": [mock_service_orders["complete"]]} - ) + payload = json.dumps({"content": [mock_service_orders["complete"]]}) response = self.client.post( "/v2/service_orders", @@ -91,21 +99,80 @@ def test_returns_list_with_the_saved_ids(self): # PATCH tests def test_service_order_has_patch_route(self): response = self.client.patch( - '/v2/service_order', - headers={"Content-Type": "application/json"}) - self.assertNotEqual(response.status_code, 405) + "/v2/service_orders", headers={"Content-Type": "application/json"} + ) + self.assertNotEqual(response.status_code, HTTPStatus.NOT_FOUND) - def test_patch_service_order_has_empty_body(self): + def test_patch_with_empty_body_has_error(self): + payload = json.dumps({"test": None}) response = self.client.patch( - '/v2/service_order', - headers={"Content-Type": "application/json"}) - self.assertNotEqual(response.status_code, 405) + "/v2/service_orders", + headers={"Content-Type": "application/json"}, + data=payload, + ) + self.assertEqual(response.json["error"], "No content found") + self.assertEqual(response.status_code, HTTPStatus.BAD_REQUEST) - def test_patch_service_order_has_wrong_field(self): - pass + def test_patch_with_invalid_fields_has_error(self): + payload = json.dumps( + { + "content": [ + {"numero_ordem_servicooo": 5, "_id": "5ee37c19d86b6a8893d1a3a7"} + ] + } + ) + response = self.client.patch( + "/v2/service_orders", + headers={"Content-Type": "application/json"}, + data=payload, + ) - def test_patch_service_order_has_invalid_id(self): - pass + self.assertEqual( + response.json["error"][0]["0"], + {"numero_ordem_servicooo": ["Unknown field."]}, + ) - def test_patch_service_order_has_nonexistent_id(self): - pass + def test_patch_with_invalid_ids_has_error(self): + id = "aaaa" + payload = json.dumps({"content": [{"_id": id}]}) + response = self.client.patch( + "/v2/service_orders", + headers={"Content-Type": "application/json"}, + data=payload, + ) + + self.assertEqual(response.status_code, HTTPStatus.BAD_REQUEST) + self.assertEqual(response.json["error"][0]["0"], "Invalid ID") + + def test_patch_with_nonexistent_id_has_error(self): + id = "5ee37c19d86b6a8893d1a3a7" + when(ServiceOrderService).fetch_service_order_by_id(id).thenReturn(False) + payload = json.dumps({"content": [{"_id": id}]}) + response = self.client.patch( + "/v2/service_orders", + headers={"Content-Type": "application/json"}, + data=payload, + ) + + self.assertEqual(response.status_code, HTTPStatus.BAD_REQUEST) + self.assertEqual(response.json["error"][0]["0"], "Nonexistent service order ID") + + def test_patch_with_valid_request_has_success(self): + when(ServiceOrderService).fetch_service_order_by_id( + mock_service_orders["correct_patch"]["_id"] + ).thenReturn(mock_service_orders["correct_patch"]) + + when(ServiceOrderService).update( + mock_service_orders["correct_patch"] + ).thenReturn(True) + + payload = json.dumps({"content": [mock_service_orders["correct_patch"]]}) + + response = self.client.patch( + "/v2/service_orders", + headers={"Content-Type": "application/json"}, + data=payload, + ) + + self.assertEqual(response.status_code, HTTPStatus.OK) + self.assertEqual(response.json, "") diff --git a/tests/v2/mocks/mock_service_orders.py b/tests/v2/mocks/mock_service_orders.py index dfc7f8e..a271f0d 100644 --- a/tests/v2/mocks/mock_service_orders.py +++ b/tests/v2/mocks/mock_service_orders.py @@ -1,15 +1,9 @@ mock_service_orders = { - 'service_order_with_id': { - '_id': '2020-06-05T15:46:37.204Z' - }, - 'service_order_with_updated': { - 'updated_at': '2020-06-05T15:46:37.204Z' - }, - 'service_order_with_deleted': { - 'deleted_at': '2020-06-05T15:46:37.204Z' - }, - - 'complete':{ + "service_order_with_id": {"_id": "2020-06-05T15:46:37.204Z"}, + "service_order_with_updated": {"updated_at": "2020-06-05T15:46:37.204Z"}, + "service_order_with_deleted": {"deleted_at": "2020-06-05T15:46:37.204Z"}, + + "complete": { "equipamento_id": "5ee37c19d86b6a8893d1a3a7", "numero_ordem_servico": 5, "status": "triagem", @@ -19,27 +13,20 @@ { "item_id": "5eeb74f9ea933e77a703ead5", "quantidade": 1, - "acompanha": True + "acompanha": True, }, - ] + ], }, "diagnostico": { "resultado_tecnico": "top", - "itens": [ - { - "item_id": "5eeb74f9ea933e77a703ead5", - "quantidade": 1 - }, - ] + "itens": [{"item_id": "5eeb74f9ea933e77a703ead5", "quantidade": 1},], }, - "calibragem": { - "status": "TESTE" - } + "calibragem": {"status": "TESTE"}, }, - 'complete_to_mockito':{ + "complete_to_mockito": { "equipamento_id": "5ee37c19d86b6a8893d1a3a7", - "numero_ordem_servico": '0005', + "numero_ordem_servico": "0005", "status": "triagem", "triagem": { "estado_de_conservacao": "teste", @@ -47,25 +34,20 @@ { "item_id": "5eeb74f9ea933e77a703ead5", "quantidade": 1, - "acompanha": True + "acompanha": True, }, - ] + ], }, "diagnostico": { "resultado_tecnico": "top", - "itens": [ - { - "item_id": "5eeb74f9ea933e77a703ead5", - "quantidade": 1 - }, - ] + "itens": [{"item_id": "5eeb74f9ea933e77a703ead5", "quantidade": 1},], }, - "calibragem": { - "status": "TESTE" - } + "calibragem": {"status": "TESTE"}, }, - 'valid_patch': - - + "correct_patch": { + "_id": "5ee37c19d86b6a8893d1a3a7", + "status": "diagnostico", + "calibragem": {"status": "TESTE - OK"}, + } } From 662a81c17208a94ab8863af48e9509e880078a06 Mon Sep 17 00:00:00 2001 From: denisousa Date: Tue, 30 Jun 2020 11:19:08 -0300 Subject: [PATCH 4/5] =?UTF-8?q?[@adrilene/@denisousa]=20#=20issue=2091=20c?= =?UTF-8?q?orre=C3=A7=C3=A3o=20nos=20testes=20quebrados?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tests/v2/controllers/test_service_orders.py | 43 +++++++-------------- tests/v2/mocks/mock_service_orders.py | 10 ++++- 2 files changed, 21 insertions(+), 32 deletions(-) diff --git a/tests/v2/controllers/test_service_orders.py b/tests/v2/controllers/test_service_orders.py index b47e625..dadf2b8 100644 --- a/tests/v2/controllers/test_service_orders.py +++ b/tests/v2/controllers/test_service_orders.py @@ -22,10 +22,6 @@ def test_get_returns_service_orders_on_successful_request(self): when(ServiceOrderService).fetch_active().thenReturn(service_orders) response = self.client.get("/v2/service_orders") - app.add_resource( - ServiceOrdersManyController, - *["/v2/service_orders/", "/v2/service_orders",] - ) self.assertEqual(response.status_code, HTTPStatus.OK) content = response.json["content"] self.assertEqual(type(content), list) @@ -37,11 +33,12 @@ def test_get_returns_service_orders_on_successful_request(self): def test_get_returns_deleted_service_orders_on_successful_request(self): service_orders = [{"equipamento_id": 1, "numero_ordem_servico": "0400"}] - response = self.client.get("/v2/service_orders/?deleted=true") + when(ServiceOrderService).fetch_all().thenReturn(service_orders) + + response = self.client.get("/v2/service_orders?deleted=true") + + self.assertEqual(response.status_code, HTTPStatus.OK) content = response.json["content"] - self.assertEqual(type(content), list) - self.assertIn("content", response.json) - self.assertIn("equipamento_id", content[0]) self.assertEqual( content[0]["equipamento_id"], service_orders[0]["equipamento_id"] ) @@ -60,23 +57,6 @@ def test_get_return_invalid_param_error(self): self.assertEqual(response.status_code, HTTPStatus.BAD_REQUEST) self.assertEqual(response.json["error"], "Parameter deleted is not equal true.") - def test_patch_with_id(self): - payload = json.dumps(valid_service_order()) - - with patch.object( - ServiceOrderService, "update", return_value=None - ) as mock_method: - service = ServiceOrderService() - response = self.client.patch( - "/v2/service_orders", - headers={"Content-Type": "application/json"}, - data=payload, - ) - - self.assertEqual(response.status_code, HTTPStatus.OK) - - mock_method.assert_called_with(valid_service_order()["content"]) - # POST tests def test_returns_list_with_the_saved_ids(self): service_order_id = "5ee37c19d86b6a8893d1a3a7" # Fake Id @@ -158,15 +138,18 @@ def test_patch_with_nonexistent_id_has_error(self): self.assertEqual(response.json["error"][0]["0"], "Nonexistent service order ID") def test_patch_with_valid_request_has_success(self): - when(ServiceOrderService).fetch_service_order_by_id( - mock_service_orders["correct_patch"]["_id"] - ).thenReturn(mock_service_orders["correct_patch"]) + id = mock_service_orders["correct_patch"]["_id"] + service_order = mock_service_orders["correct_patch"] + + when(ServiceOrderService).fetch_service_order_by_id(id).thenReturn( + service_order + ) when(ServiceOrderService).update( - mock_service_orders["correct_patch"] + id, mock_service_orders["correct_patch_mockito"] ).thenReturn(True) - payload = json.dumps({"content": [mock_service_orders["correct_patch"]]}) + payload = json.dumps({"content": [service_order]}) response = self.client.patch( "/v2/service_orders", diff --git a/tests/v2/mocks/mock_service_orders.py b/tests/v2/mocks/mock_service_orders.py index a271f0d..12180c6 100644 --- a/tests/v2/mocks/mock_service_orders.py +++ b/tests/v2/mocks/mock_service_orders.py @@ -5,7 +5,7 @@ "complete": { "equipamento_id": "5ee37c19d86b6a8893d1a3a7", - "numero_ordem_servico": 5, + "numero_ordem_servico": 999, "status": "triagem", "triagem": { "estado_de_conservacao": "teste", @@ -26,7 +26,7 @@ "complete_to_mockito": { "equipamento_id": "5ee37c19d86b6a8893d1a3a7", - "numero_ordem_servico": "0005", + "numero_ordem_servico": "0999", "status": "triagem", "triagem": { "estado_de_conservacao": "teste", @@ -49,5 +49,11 @@ "_id": "5ee37c19d86b6a8893d1a3a7", "status": "diagnostico", "calibragem": {"status": "TESTE - OK"}, + }, + + "correct_patch_mockito": { + "status": "diagnostico", + "calibragem": {"status": "TESTE - OK"}, } + } From 434c7ea8a00a1aab6aaf74842562fefc7a5f7bb4 Mon Sep 17 00:00:00 2001 From: adrilene Date: Thu, 2 Jul 2020 09:46:39 -0300 Subject: [PATCH 5/5] =?UTF-8?q?[@adrilene/@denisousa]=20Issue=20#91=20-=20?= =?UTF-8?q?Corre=C3=A7=C3=B5es=20do=20PR?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- api/v2/controllers/dtos/service_order_request.py | 10 +++++----- api/v2/controllers/service_orders_many_controller.py | 1 - api/v2/utils/util_update.py | 2 +- 3 files changed, 6 insertions(+), 7 deletions(-) diff --git a/api/v2/controllers/dtos/service_order_request.py b/api/v2/controllers/dtos/service_order_request.py index 5b14b00..9c47f50 100644 --- a/api/v2/controllers/dtos/service_order_request.py +++ b/api/v2/controllers/dtos/service_order_request.py @@ -1,13 +1,13 @@ -class ServiceOrderRequest(): +class ServiceOrderRequest: def __init__(self, data): - self.tipo = data['tipo'] + self.tipo = data["tipo"] self.data = data def get(self): - return self.data - + return self.data + def valid(self): return True def errors(self): - return [{}] \ No newline at end of file + return [{}] diff --git a/api/v2/controllers/service_orders_many_controller.py b/api/v2/controllers/service_orders_many_controller.py index 8aa79c6..c7ff90b 100644 --- a/api/v2/controllers/service_orders_many_controller.py +++ b/api/v2/controllers/service_orders_many_controller.py @@ -1,6 +1,5 @@ from http import HTTPStatus from flask import request -from .dtos.service_order_request import ServiceOrderRequest from flask_restful import Resource from ..helpers.helper_response import get_response from ..validation.validation_request import invalid_deleted_parameter diff --git a/api/v2/utils/util_update.py b/api/v2/utils/util_update.py index 4a08df7..44111e6 100644 --- a/api/v2/utils/util_update.py +++ b/api/v2/utils/util_update.py @@ -3,7 +3,7 @@ def pop_id(data): try: del data['_id'] except Exception: - pass + return Exception return id