AttributeError: 'bytes' object has no attribute 'hexdigest' - python-3.x

I wrote the following code but the problem is that I recieved an error (AttributeError: 'bytes' object has no attribute 'hexdigest')
the error syntax doesn't work
import requests
import hashlib
def request_api_data (query_char):
url = 'https://api.pwnedpasswords.com/range/'+ query_char
res = requests.get(url)
if res.status_code != 200:
print('it is an error')
#raise RuntimeError(f'Error fetching: {res.status_code}, check api and try again')
return res
request_api_data('123')
def pwned_api_check(password):
sha1password= hashlib.sha1(password.encode('utf-8').hexdigest().upper())
print (sha1password)
#return sha1password
pwned_api_check('123')
Why does this error occur and how do I fix it??

You need to add a parenthesis after hashlib.sha1(password.encode('utf-8'), so hexdigest().upper() is called on it.
The following code works for me:
hashlib.sha1(password.encode('utf-8')).hexdigest().upper()

I was taking the same class as you and got the same error. The parenthesis are in the wrong place.
sha1password = hashlib.sha1(password.encode('utf-8')).hexdigest().upper()

Related

Pytest mock using decorator to mock function containing context manager return value not passed

So I am struggling with mocking this function due to the context manager.
Function under test
import fitz
def with_test_func(next_pdfs_path):
text = ''
with fitz.open(next_pdfs_path) as doc:
text = doc
return text
Test code
#mock.patch("content_production.fitz.open.__enter__", return_value='value_out')
def test_with_test_func(mock_fitz_open):
assert cp.with_test_func('value_in') == 'value_out'
Error
RuntimeError: cannot open value_in: No such file or directory
I have tested this without the context manager and it works. So how would I fix this? thanks
Edit
So as suggested by #MrBean I tried this
#mock.patch("content_production.fitz.open.return_value.__enter__", return_value='value_out')
def test_with_test_func(mock_fitz_open):
assert cp.with_test_func('value_in') == 'value_out'
It gives me this error
thing = <class 'fitz.fitz.Document'>, comp = 'return_value', import_path = 'content_production.fitz.open.return_value'
def _dot_lookup(thing, comp, import_path):
try:
return getattr(thing, comp)
except AttributeError:
> __import__(import_path)
E ModuleNotFoundError: No module named 'content_production.fitz'; 'content_production' is not a package
The problem is that return_value is a property of the mock, not of the patched function, so you cannot put it into the patch argument string. Instead, you have to set the return value on the mock for the open method:
#mock.patch("content_production.fitz.open")
def test_with_test_func(mock_fitz_open):
mock_fitz_open.return_value.__enter__.return_value = 'value_out'
assert cp.with_test_func('value_in') == 'value_out'

why python is throwing attribute attribute error

I have the following unit test written in python,When i try to run this code, i am getting an attribute error in the console that
AttributeError: 'testLogin' object has no attribute 'lp' I am very new to python and i would like to get some insight on this attribute issue
Is there any issues that needs to be fixed. Your help us highly recommended.
from utilities.teststatus import TestStatus as ts
import unittest
import pytest
#pytest.mark.usefixtures("oneTimeSetup", "setUp")
class testLogin(unittest.TestCase):
#pytest.fixture(autouse=True)
def classSetup(self,oneTimeSetup):
self.lp = LoginPage(self.driver)
#pytest.mark.order1
def test_validLogin(self):
self.lp.login("test#email.com", "abcabc")
userIcon = self.lp.verifyLoginSuccessful()
title = self.lp.verifyPageTitle()
ts.markFinal(title,"Login not successful")
assert userIcon == True
When i try to run this unittest, i am getting the error as AttributeError: 'testLogin' object has no attribute 'lp'
Can some one please help to fix it ?

How can I mock Connection & Timeout Error in Python 3?

I am newbie to Python. I am trying to mock exception in my unit test and test my block of code; however exception message is always empty. Is this below recommended way to mock exception? Also how can I make sure exception message is not empty?
import pytest
import requests
from unittest.mock import patch
#Unit Test
#patch('requests.get')
def test_exception(mock_run):
mock_run.side_effect = requests.exceptions.ConnectionError()
with pytest.raises(SystemExit) as sys_exit:
method_to_test()
assert 'Error ' in str(sys_exit.value) # Here sys_exit.value is always empty
#Method to Test
def method_to_test():
try:
response = requests.get('some_url', verify=False, stream=True)
response.raise_for_status()
except (requests.exceptions.HTTPError,
requests.exceptions.ConnectionError,
requests.exceptions.Timeout) as err:
msg = f'Failure: {err}' # Here err is always empty
raise SystemExit(msg)
Long story short: You don't get a message because you don't specify one.
You probably want to check for 'Failure: ' instead of 'Error: ', since this is what you prefix the original exception message with. This might be the real problem in your code, not the empty string representation of the exception you raise in your test.
Why is str(err) empty?
Take a look at the class hierarchy:
BaseException
Exception
IOError
requests.RequestException
requests.ConnectionError
IOError overrides __str__ if more than one argument is given to the constructor, but otherwise the behavior of BaseException applies:
If str() is called on an instance of this class, the representation of the argument(s) to the instance are returned, or the empty string when there were no arguments.
https://docs.python.org/3/library/exceptions.html#BaseException
>>> import requests
>>> str(requests.exceptions.ConnectionError())
''
>>> str(requests.exceptions.ConnectionError('foo'))
'foo'
>>> str(requests.exceptions.ConnectionError('foo', 'bar'))
'[Errno foo] bar'
The last example is the behavior defined by the IOError exception.
If you want to simulate the exception, raise the exception in your try block, just like you're raising an exception in your except block. When you do this, you can pass a string argument to be the exception message -
raise requests.exceptions.HTTPError("Test this error")
That will filter the message to the except block.
With your example:
def method_to_test():
try:
# ADD EXCEPTION HERE
raise requests.exceptions.HTTPError('Throwing an exception here!')
response = requests.get('some_url', verify=False, stream=True)
response.raise_for_status()
except (requests.exceptions.HTTPError,
requests.exceptions.ConnectionError,
requests.exceptions.Timeout) as err:
# err will now be 'Throwing an exception here!'
msg = f'Failure: {err}' # Here err is always empty
raise SystemExit(msg)

Dictionary in Python 3.6

I have question. I try to get info from function and pack result into dictionary like this:
import requests
class CommonUtils():
def get_data_list(self, url, listType):
c_list = requests.get(url)
data = {"json": c_list.json(), "text": c_list.text}
return data.get(listType)
I debugged function and I know, that requests retrieves info from passed url.
And when I try to return data, I get error with message: "AttributeError: 'dict' object has no attribute 'json'"
What I do wrong?

Exception Handling Python TypeError: 'NoneType' object is not callable

I am scraping a list of urls with the same html format. Here is my scraper
import requests, bs4, csv, json
from pprint import pprint
with open('playerslist.json') as data_file:
data = json.load(data_file)
for i in data['player']:
name = i['player_name']
url = 'https://www.capfriendly.com/players/'+name
r = requests.get(url)
soup = bs4.BeautifulSoup(r.text, 'lxml')
table = soup.find(id="cont_x")
with open(name+".csv", "w", newline='') as team_data:
def parse_td(td):
filtered_data = [tag.text for tag in td.find_all('span', recursive=False)
if 'q' not in tag.attrs['class']]
return filtered_data[0] if filtered_data else td.text;
for tr in table('tr', class_=['column_head', 'odd', 'even']):
row = [parse_td(td) for td in tr('td')]
writer = csv.writer(team_data)
writer.writerow(row)
The problem is that some of the url's (https://www.capfriendly.com/players/'+name) pages no longer exist. Which means that when I try to scrape them, I get the following error
for tr in table('tr', class_=['column_head', 'odd', 'even']):
TypeError: 'NoneType' object is not callable
I could make sure that my list of urls are all valid but I have 10000 urls to go through. That is why I am looking for a way to handle the exception, that way if a page no longer exists, it is skipped and the following url gets scraped.
Also, if there is a more efficient way to store the data, please let me know.
Exception handling in python is done with try...except statement.
try:
for tr in table('tr', class_=['column_head', 'odd', 'even']):
row = [parse_td(td) for td in tr('td')]
writer = csv.writer(team_data)
writer.writerow(row)
except TypeError:
pass
This will ignore the TypeError exception raised when table is None because the url doesn't exist anymore.
You can also check table before the loop, but the try... except approach is considered more 'pythonic', since exception handling isn't that much slower than checks in most cases (and for other subjective reasons of course).
I used the following successfully (Python v. 3.9):
try:
<my_code>
except AttributeError:
<my_code>

Resources