FastAPI not raising HTTPException - python

I'm trying to raise an exception in FastAPI when an object with a specific key already exists (e.g. RethinkDb return "Duplicated key" error). Probably something wrong with my method logic, but can't get what exactly.
#router.post("/brands", response_model=Brand, status_code=status.HTTP_201_CREATED)
def add_brand(brand: Brand):
with r.connect('localhost', 28015, 'expressparts').repl() as conn:
try:
result = r.table("brands").insert({
"id": brand.id,
"name": brand.name}).run(conn)
if result['errors'] > 0:
error = result['first_error'].split(":")[0]
raise HTTPException(
status_code=400, detail=f"Error raised: {error}")
else:
return brand
except Exception as err:
print(err)

You have a try-catch and it captures all the errors that occured. You are just capturing your own Exception which is isn't actually been raised yet.
#router.post("/brands", response_model=Brand, status_code=status.HTTP_201_CREATED)
def add_brand(brand: Brand):
with r.connect('localhost', 28015, 'expressparts').repl() as conn:
result = r.table("brands").insert({
"id": brand.id,
"name": brand.name}).run(conn)
if result['errors'] > 0:
error = result['first_error'].split(":")[0]
raise HTTPException(
status_code=400, detail=f"Error raised: {error}")
else:
return brand
This should be working fine.

Related

How to fix dictionary, get is not a known member of None in Pylance language server prompt message

Love to use pylance, but unable to fix this issue in dictionary get, pylance prompt message as shown in the image
def validate_amount():
try:
json_data = request.json
def isfloat(num: str) -> bool:
try:
float(num)
return True
except ValueError:
return False
amount_val = json_data.get('amount','0.0')
amount_in_words = json_data.get('amount2words','')
if isfloat(amount_val):
split_amt = amount_val.split('.')
response = split_amt
except Exception as e:
response = f'An Error Occurred - {e}'
Below is the image for reference

Cannot get the python test to assert an Exception was thrown

Code:
class ContributionHandler:
def __init__(self):
MetricsConfigurator.setup_metrics("ContributionMutationResolverLambda")
self.entity_linkage_authority_client_factory = EntityLinkageAuthorityClientFactory()
self.entity_linkage_authority_client = self.entity_linkage_authority_client_factory.get_client()
#retry(delay=0.5, tries=2)
def create_contribution(self, input_event):
"""
Calls Entity Linkage Authority to create a contribution between PEs
:return: the contribution created
"""
from_pe = input_event[constants.FROM_PE]
to_pe = input_event[constants.TO_PE]
logging.info(f"Creating contribution from PE: {from_pe} to PE: {to_pe}")
try:
response = self.__create_contribution_call(input_event)
return response
except Exception as e:
logging.info(f"Error creating the contribution from PE: {from_pe} to PE: {to_pe}")
raise e
#retry(delay=0.5, tries=2)
#metric_time
#metric_count
#metric_errors(verbose=True)
def __create_contribution_call(self, input_event):
"""
Separate retryable private function for api call with the client.
"""
relationship_contribution_info = RelationshipContributionInfo(input_event[constants.FROM_PE],
input_event[constants.TO_PE], input_event[constants.RELATIONSHIP_TYPE],
input_event[constants.INTENT], input_event[constants.IS_NEGATIVE])
audit_info = AuditInfo(input_event[constants.AUDIT_INFO][constants.CREATED_BY],
input_event[constants.AUDIT_INFO][constants.CREATED_AT])
try:
return self.entity_linkage_authority_client.create_relationship\
(CreateRelationshipRequest(relationship_contribution_info, audit_info))
except Exception as e:
logging.info("Recreating the client as Credentials expired1")
if isinstance(e, ClientError) and e.response['Error']['Code'] == 'ExpiredToken':
logging.info("Recreating the client as Credentials expired2")
self.entity_linkage_authority_client_factory = EntityLinkageAuthorityClientFactory()
self.entity_linkage_authority_client = self.entity_linkage_authority_client_factory.get_client()
raise e
Test case:
#mock.patch(METRICS_IMPORT_PATH + '.setup_metrics')
#mock.patch(ENTITY_LINKAGE_AUTHORITY_CLIENT_FACTORY_IMPORT_PATH + '.get_client')
#mock.patch(ENTITY_LINKAGE_AUTHORITY_CLIENT_FACTORY_IMPORT_PATH + '.__init__')
def test_create_contribution_handler_token_expiry(mock_client_factory_init, mock_get_client, mock_metrics):
mock_metrics.return_value = None
mock_client_factory_init.return_value = None
error_response = {"Error": {"Code": "ExpiredToken"}}
mock_get_client.return_value.create_relationship(mock.ANY).raiseError.side_effect = ClientError(error_response, "Expired Token")
contribution_handler = ContributionHandler()
with pytest.raises(ClientError) :
contribution_handler.create_contribution(CONTRIBUTION_INPUT)
# make sure we retried 3 times
# assert 3 == mock_client_factory_init.call_count
Output:
Test case is failing with following output:
[CPython36:setup:stdout] with pytest.raises(ClientError) :
[CPython36:setup:stdout] > contribution_handler.create_contribution(CONTRIBUTION_INPUT)
[CPython36:setup:stdout] E Failed: DID NOT RAISE

Mocking a 500 response when an operation is performed

This is my test so far:
test_500(self):
client = ClientConfiguration(token=token, url=url)
client.url = 'https://localhost:1234/v1/' + bucket
keys = None
try:
get_bucket = json.loads(str(client.get_bucket(bucket)))
result = get_bucket['result']
except Exception as e:
expected_status_code = 500
failure_message = "Expected status code %s but got status code %s" % (expected_status_code, e)
self.assertEquals(e, expected_status_code, failure_message)
I need to write a mock that will return a 500 response when the 'https://localhost:1234/v1/' + bucket url is used. Can this be done with unittest and if so, how or where can I find some documentation on this? I've been through this site, the unittest documentation and Youtube and can't find anythingspecific to what I want to do.
I ended up using this to create my test.
The end result is:
#responses.activate
test_500(self):
responses.add(responses.GET, 'https://localhost:1234/v1/' + bucket,
json={'error': 'server error'}, status=500)
client = ClientConfiguration(token=token, url=url)
client.url = 'https://localhost:1234/v1/'
keys = None
try:
get_bucket = json.loads(str(client.get_bucket(bucket)))
result = get_bucket['result']
except Exception as e:
expected_status_code = 500
failure_message = "Expected status code %s but got status code %s" % (expected_status_code, e)
self.assertEquals(e, expected_status_code, failure_message)

Django unittest with not raising exception as expected with assertRaises()

I'm writing a unittest class to ensure a method tests for a success, and then tests for an Exception. I'm passing a response that should trigger the exception, but in the testing method it does not get raised. Of note, I can manually make the exception raise in the actual method.
Test class:
class TestAPI(TestCase):
def test_send_method(self):
with mock.patch('requests.post') as mock_request:
mock_response = mock.Mock()
mock_response.json.return_value = {
"success": "true"
}
mock_request.return_value = mock_response
send_method() // THIS WORKS NICELY
# Test that errors from the API are handled correctly.
with self.assertRaises(SendException):
mock_response.status_code = 500
mock_response.json.return_value = {
'errors': 'An error has occurred.',
}
send_method() // THIS RAISES NO EXCEPTION
As I said, It's odd because I can manually trigger the 500 status code in the actual method and it raises fine. I can even change the initial mock response success to err and it will raise in the actual method. Why would it not raise in the unittest?
Method being tested:
class SendException(Exception):
pass
def send_method():
session_headers = {
"Content-Type": "application/json",
}
session_body = {
"send": "yes"
}
session_url = u'{}'.format(URL)
session_response = requests.post(session_url, json=session_body, headers=session_headers)
try:
if(session_response.json().get('errors') is not None):
raise SendException(
'Returned error with status {}: {}'.format(
session_response.status_code,
session_response.json().get('errors')
)
)
except ValueError as err:
raise SendException(
'Responded with non-json and status code {}. Error: {} - Response Text: {}'.format(
session_response.status_code,
err,
session_response.text
)
)

raise in raise error

I have an error raise eb : list index out of range.
I don't understand why when i do a raise in an other try - catch
I'm doing a try - catch in a try - catch and both raises errors.
Here is my code and the error line is at raise eb :
try:
print("debut edit")
print(p)
modif_box = get_modif_box_profile(p)
post_box = get_Post_Box(p)
print("modi_box")
print(modif_box)
print("mbu id")
print(modif_box.id)
diff = {}
posts = {}
new_post = []
diff["posts"] = posts
posts["modified_post"] = new_post
for post in modif_box.edit_post_user.all():
# print(post.id_mod)
try:
messagenew = post_box.post.all().filter(id=post.id_mod)[0]
# print(post_new)
print("posts")
print(post)
# todo a factoriser
if messagenew.id > int(last_id) and messagenew.sender.id != p.id:
name = get_name_contact(p, messagenew)
return_post = {}
return_post["uid"] = messagenew.sender.id
return_post["pid"] = messagenew.id
return_post["author"] = name
return_post["title"] = messagenew.title
return_post["date"] = unix_time_millis(messagenew.date)
return_post["smile"] = count_smile(messagenew)
return_post["comment"] = count_comment(messagenew)
return_post["data"] = messagenew.data
return_post["type"] = messagenew.type_post.type_name
new_post.append(return_post)
else:
print("depop edit")
modif_box.edit_post_user.remove(post)
modif_box.save()
except Exception as eb:
PrintException()
# raise eb (if i decomment here i have an error in my program)
print(diff)
return diff
except Exception as e:
PrintException()
raise e
Regards and thanks
If you comment the raise statement there, it doesn't mean that you don't have an Error; it simply means that you handled the Exception -- which in your case is from what I can tell an IndexError -- by catching it with the except Exception and then calling PrintException().
When you raise an exception what you actually do is:
The raise statement allows the programmer to force a specified exception to occur.
So, by un-commenting, you allow the IndexError named eb to re-appear after catching it in the inner try-except block and get caught by the outer try - except clause in which you again re-raise it.
Generally, you don't want to catch exceptions in such a generic way because it might hide some unpredicted behaviour of the program that you would like to know about.
Limit the exceptions you catch in the except clause by simply specifying them, in your case, an except clause of the form:
except IndexError as eb:
PrintException()
would probably suffice.

Categories