Best Python code snippet using lemoncheesecake
leave_controller.py
Source:leave_controller.py
1"""2@author: Naveen Maan3@date: 2022-06-114"""5import json6import validictory7from rest_framework import status8from rest_framework.views import APIView9from rest_framework.response import Response10from core.custom_auth import CustomAuthentication, CustomPermission11from src.services.leave.config.leave_config import LEAVE_RAISE, TOKEN_VALIDATION12from src.services.leave.models.leave_model import Leave13from src.services.leave.logic.manager.leave_manager import LeaveManager14class LeaveController(APIView):15 """16 Endpoint to handle employee leave requests17 """18 authentication_classes = [CustomAuthentication]19 permission_classes = [CustomPermission]20 def get(self, request, *args, **kwargs):21 """22 Method to handle the leave details actions23 url: /leave/request24 url: /leave/request/{request_id}25 Args:26 request:{27 status: pending/all28 }29 *args:30 **kwargs:31 Returns:32 """33 response = {}34 response_status = None35 try:36 auth_token = request.META.get('HTTP_TOKEN')37 validictory.validate(auth_token, TOKEN_VALIDATION, disallow_unknown_properties=True, fail_fast=False)38 validictory.validate(request.data, LEAVE_RAISE['get'], disallow_unknown_properties=True, fail_fast=False)39 request_id = kwargs.get("request_id", None)40 response_status, response = LeaveManager(auth_token).get_leaves(request_id, request.data)41 except validictory.ValidationError as ex:42 response_status = status.HTTP_403_FORBIDDEN43 response = {44 "status": "failed",45 "reason": str(ex)46 }47 except Leave.DoesNotExist:48 response_status = status.HTTP_204_NO_CONTENT49 response = {50 "status": "failed",51 "reason": "Request does not exist"52 }53 except Exception as ex:54 response_status = status.HTTP_500_INTERNAL_SERVER_ERROR55 response = {56 "status": "failed",57 "reason": str(ex)58 }59 return Response(response, response_status)60 def post(self, request, *args, **kwargs):61 """62 Method to handle the leave creation action63 url: /leave/request64 Args:65 request: {66 from_date: 2022-03-01,67 to_date: 22-03-05,68 reason: leave69 }70 *args:71 **kwargs:72 Returns:73 """74 response = {}75 response_status = None76 try:77 auth_token = request.META.get('HTTP_TOKEN')78 validictory.validate(auth_token, TOKEN_VALIDATION, disallow_unknown_properties=True, fail_fast=False)79 validictory.validate(request.data, LEAVE_RAISE['post'], disallow_unknown_properties=True, fail_fast=False)80 response_status, response = LeaveManager(auth_token).raise_leave_request(request.data)81 except validictory.ValidationError as ex:82 response_status = status.HTTP_403_FORBIDDEN83 response = {84 "status": "failed",85 "reason": str(ex)86 }87 except Exception as ex:88 response_status = status.HTTP_500_INTERNAL_SERVER_ERROR89 response = {90 "status": "failed",91 "reason": str(ex)92 }93 return Response(response, response_status)94 def patch(self, request, *args, **kwargs):95 """96 Method to handle the change in leave request97 url: /leave/request/{request_id}98 Args:99 request: {100 status: canceled101 comment: test102 }103 *args:104 **kwargs:105 Returns:106 """107 response = {}108 response_status = None109 try:110 auth_token = request.META.get('HTTP_TOKEN')111 if not kwargs.get("request_id"):112 raise validictory.validator.RequiredFieldValidationError("request_id is missing")113 validictory.validate(auth_token, TOKEN_VALIDATION, disallow_unknown_properties=True, fail_fast=False)114 validictory.validate(request.data, LEAVE_RAISE['patch'], disallow_unknown_properties=True, fail_fast=False)115 response_status, response = LeaveManager(auth_token).update_leave_request_status(kwargs['request_id'], request.data)116 except validictory.ValidationError as ex:117 response_status = status.HTTP_403_FORBIDDEN118 response = {119 "status": "failed",120 "reason": str(ex)121 }122 except Leave.DoesNotExist:123 response_status = status.HTTP_204_NO_CONTENT124 response = {125 "status": "failed",126 "reason": "Request does not exist"127 }128 except Exception as ex:129 response_status = status.HTTP_500_INTERNAL_SERVER_ERROR130 response = {131 "status": "failed",132 "reason": str(ex)133 }134 return Response(response, response_status)135class LeaveVerifyController(APIView):136 """137 Endpoint to handle employee leave requests138 """139 authentication_classes = [CustomAuthentication]140 permission_classes = [CustomPermission]141 def get(self, request, *args, **kwargs):142 """143 Method to handle the leave details actions144 url: /leave/verify145 url: /leave/verify/{request_id}146 Args:147 request:{148 status: pending/all149 }150 *args:151 **kwargs:152 Returns:153 """154 response = {}155 response_status = None156 try:157 auth_token = request.META.get('HTTP_TOKEN')158 validictory.validate(auth_token, TOKEN_VALIDATION, disallow_unknown_properties=True, fail_fast=False)159 validictory.validate(request.data, LEAVE_RAISE['get'], disallow_unknown_properties=True, fail_fast=False)160 request_id = kwargs.get("request_id", None)161 response_status, response = LeaveManager(auth_token, admin=True).get_leaves(request_id, request.data)162 except validictory.ValidationError as ex:163 response_status = status.HTTP_403_FORBIDDEN164 response = {165 "status": "failed",166 "reason": str(ex)167 }168 except Leave.DoesNotExist:169 response_status = status.HTTP_204_NO_CONTENT170 response = {171 "status": "failed",172 "reason": "Request does not exist"173 }174 except Exception as ex:175 response_status = status.HTTP_500_INTERNAL_SERVER_ERROR176 response = {177 "status": "failed",178 "reason": str(ex)179 }180 return Response(response, response_status)181 def patch(self, request, *args, **kwargs):182 """183 Method to handle the change in leave request184 url: /leave/verify/{request_id}185 Args:186 request: {187 status: canceled188 comment: test189 }190 *args:191 **kwargs:192 Returns:193 """194 response = {}195 response_status = None196 try:197 auth_token = request.META.get('HTTP_TOKEN')198 validictory.validate(auth_token, TOKEN_VALIDATION, disallow_unknown_properties=True, fail_fast=False)199 if not kwargs.get("request_id"):200 raise validictory.validator.RequiredFieldValidationError("request_id is missing")201 validictory.validate(request.data, LEAVE_RAISE['verify_patch'], disallow_unknown_properties=True, fail_fast=False)202 response_status, response = LeaveManager(auth_token, admin=True).update_leave_request_status(kwargs['request_id'], request.data)203 except validictory.ValidationError as ex:204 response_status = status.HTTP_403_FORBIDDEN205 response = {206 "status": "failed",207 "reason": str(ex)208 }209 except Leave.DoesNotExist:210 response_status = status.HTTP_204_NO_CONTENT211 response = {212 "status": "failed",213 "reason": "Request does not exist"214 }215 except Exception as ex:216 response_status = status.HTTP_500_INTERNAL_SERVER_ERROR217 response = {218 "status": "failed",219 "reason": str(ex)220 }...
test_disallow_unknown_properties.py
Source:test_disallow_unknown_properties.py
1from unittest import TestCase2import validictory3class TestDisallowUnknownProperties(TestCase):4 def setUp(self):5 self.data_simple = {"name": "john doe", "age": 42}6 self.schema_simple = {7 "type": "object",8 "properties": {9 "name": {"type": "string"},10 "age": {"type": "integer"}11 },12 }13 self.data_complex = {14 "inv_number": "123",15 "rows": [16 {17 "sku": "ab-456",18 "desc": "a description",19 "price": 100.4520 },21 {22 "sku": "xy-123",23 "desc": "another description",24 "price": 999.0025 }26 ]27 }28 self.schema_complex = {29 "type": "object",30 "properties": {31 "inv_number": {"type": "string"},32 "rows": {33 "type": "array",34 "items": {35 "sku": {"type": "string"},36 "desc": {"type": "string"},37 "price": {"type": "number"}38 },39 }40 }41 }42 def test_disallow_unknown_properties_pass(self):43 try:44 validictory.validate(self.data_simple, self.schema_simple,45 disallow_unknown_properties=True)46 except ValueError as e:47 self.fail("Unexpected failure: %s" % e)48 def test_disallow_unknown_properties_fail(self):49 self.data_simple["sex"] = "male"50 self.assertRaises(validictory.SchemaError, validictory.validate,51 self.data_simple, self.schema_simple,52 disallow_unknown_properties=True)53 def test_disallow_unknown_properties_complex_pass(self):54 try:55 validictory.validate(self.data_complex, self.schema_complex,56 disallow_unknown_properties=True)57 except ValueError as e:58 self.fail("Unexpected failure: %s" % e)59 def test_disallow_unknown_properties_complex_fail(self):60 newrow = {"sku": "789", "desc": "catch me if you can", "price": 1,61 "rice": 666}62 self.data_complex["rows"].append(newrow)63 self.assertRaises(validictory.SchemaError, validictory.validate,64 self.data_complex, self.schema_complex,...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!