Skip to content

Commit

Permalink
black formatted
Browse files Browse the repository at this point in the history
  • Loading branch information
PointlessUser committed May 14, 2024
1 parent a5b4da6 commit 38ec8d8
Show file tree
Hide file tree
Showing 7 changed files with 61 additions and 57 deletions.
1 change: 0 additions & 1 deletion PyTests/test_images.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import sys
import os
import pytest
import base64
import mimetypes
from PIL import Image
Expand Down
40 changes: 21 additions & 19 deletions PyTests/test_quiz.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@


class TestAppendToGoogleSheet(unittest.TestCase):
@patch('mecsimcalc.quiz_utils.requests')
@patch("mecsimcalc.quiz_utils.requests")
def test_append_to_google_sheet(self, mock_post):
# mock response
mock_response = MagicMock()
Expand All @@ -33,26 +33,28 @@ def test_append_to_google_sheet(self, mock_post):
"token_uri": "https://oauth2.googleapis.com/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/xxx.com",
"universe_domain": "googleapis.com"
"universe_domain": "googleapis.com",
}
spreadsheet_id = 'dummy_spreadsheet_id'
spreadsheet_id = "dummy_spreadsheet_id"
values = [["dummy_data"]]
range_name = 'Sheet1!A1'
range_name = "Sheet1!A1"

# execute the function
response = append_to_google_sheet(service_account_info, spreadsheet_id, values, range_name, False)
response = append_to_google_sheet(
service_account_info, spreadsheet_id, values, range_name, False
)
assert isinstance(response, dict)


class TestSendEmail(unittest.TestCase):
@patch('mecsimcalc.quiz_utils.smtplib.SMTP_SSL')
@patch("mecsimcalc.quiz_utils.smtplib.SMTP_SSL")
def test_send_email_success(self, mock_smtp_ssl):
# Setup test data
sender_email = '[email protected]'
receiver_email = '[email protected]'
subject = 'Test Subject'
app_password = 'app-specific-password'
values = [('Data1', 'Data2'), ('Data3', 'Data4')]
sender_email = "[email protected]"
receiver_email = "[email protected]"
subject = "Test Subject"
app_password = "app-specific-password"
values = [("Data1", "Data2"), ("Data3", "Data4")]

# Configure the mock SMTP server
mock_server = MagicMock()
Expand All @@ -63,7 +65,7 @@ def test_send_email_success(self, mock_smtp_ssl):

# Assertions
assert res == True
mock_smtp_ssl.assert_called_once_with('smtp.gmail.com', 465)
mock_smtp_ssl.assert_called_once_with("smtp.gmail.com", 465)
mock_server.login.assert_called_once_with(sender_email, app_password)
mock_server.sendmail.assert_called_once()
args, _ = mock_server.sendmail.call_args
Expand All @@ -75,14 +77,14 @@ def test_send_email_success(self, mock_smtp_ssl):
for value in values:
self.assertIn(", ".join(value), email_body)

@patch('mecsimcalc.quiz_utils.smtplib.SMTP_SSL')
@patch("mecsimcalc.quiz_utils.smtplib.SMTP_SSL")
def test_send_email_failure(self, mock_smtp_ssl):
# Setup test data with same parameters as success test
sender_email = '[email protected]'
receiver_email = '[email protected]'
subject = 'Test Subject'
app_password = 'app-specific-password'
values = [('Data1', 'Data2'), ('Data3', 'Data4')]
sender_email = "[email protected]"
receiver_email = "[email protected]"
subject = "Test Subject"
app_password = "app-specific-password"
values = [("Data1", "Data2"), ("Data3", "Data4")]

# Configure the mock SMTP server to raise an exception
mock_smtp_ssl.return_value.__enter__.side_effect = Exception("SMTP Error")
Expand All @@ -92,4 +94,4 @@ def test_send_email_failure(self, mock_smtp_ssl):

# Assertions
assert res == False
mock_smtp_ssl.assert_called_once_with('smtp.gmail.com', 465)
mock_smtp_ssl.assert_called_once_with("smtp.gmail.com", 465)
1 change: 0 additions & 1 deletion PyTests/test_spreadsheet.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import sys
import os
import pytest
import base64
import mimetypes
import io
Expand Down
1 change: 0 additions & 1 deletion PyTests/test_text.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import sys
import os
import pytest

# caution: path[0] is reserved for script path (or '' in REPL)
THIS_DIR = os.path.dirname(os.path.abspath(__file__))
Expand Down
2 changes: 1 addition & 1 deletion mecsimcalc/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,5 +26,5 @@
"metadata_to_filetype",
"file_to_PIL",
"append_to_google_sheet",
"send_gmail"
"send_gmail",
]
62 changes: 30 additions & 32 deletions mecsimcalc/quiz_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,12 @@
import logging



def append_to_google_sheet(
service_account_info: dict,
spreadsheet_id: str,
values: list,
range_name: str = 'Sheet1!A1',
include_timestamp: bool = True
service_account_info: dict,
spreadsheet_id: str,
values: list,
range_name: str = "Sheet1!A1",
include_timestamp: bool = True,
) -> dict:
"""
>>> append_to_google_sheet(
Expand Down Expand Up @@ -69,29 +68,29 @@ def _get_access_token(service_account_info: dict):
exp = iat + 3600 # Token valid for 1 hour
# JWT payload
payload = {
'iss': service_account_info['client_email'],
'scope': 'https://www.googleapis.com/auth/spreadsheets',
'aud': 'https://oauth2.googleapis.com/token',
'iat': iat,
'exp': exp
"iss": service_account_info["client_email"],
"scope": "https://www.googleapis.com/auth/spreadsheets",
"aud": "https://oauth2.googleapis.com/token",
"iat": iat,
"exp": exp,
}
# Generate JWT
additional_headers = {'kid': service_account_info['private_key_id']}
additional_headers = {"kid": service_account_info["private_key_id"]}
signed_jwt = jwt.encode(
payload,
service_account_info['private_key'],
algorithm='RS256',
headers=additional_headers
service_account_info["private_key"],
algorithm="RS256",
headers=additional_headers,
)
# Exchange JWT for access token
params = {
'grant_type': 'urn:ietf:params:oauth:grant-type:jwt-bearer',
'assertion': signed_jwt
"grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer",
"assertion": signed_jwt,
}
response = requests.post('https://oauth2.googleapis.com/token', data=params)
response = requests.post("https://oauth2.googleapis.com/token", data=params)
response.raise_for_status() # Raises HTTPError, if one occurred
response_data = response.json()
return response_data['access_token']
return response_data["access_token"]
except Exception as e:
print(f"Error getting access token: {e}")
return None
Expand All @@ -106,12 +105,12 @@ def _get_access_token(service_account_info: dict):
values = [row + [current_timestamp] for row in values]

try:
url = f'https://sheets.googleapis.com/v4/spreadsheets/{spreadsheet_id}/values/{range_name}:append?valueInputOption=RAW&insertDataOption=INSERT_ROWS'
url = f"https://sheets.googleapis.com/v4/spreadsheets/{spreadsheet_id}/values/{range_name}:append?valueInputOption=RAW&insertDataOption=INSERT_ROWS"
headers = {
'Authorization': f'Bearer {access_token}',
'Content-Type': 'application/json'
"Authorization": f"Bearer {access_token}",
"Content-Type": "application/json",
}
body = {'values': values}
body = {"values": values}
response = requests.post(url, headers=headers, json=body)
response.raise_for_status() # Raises HTTPError, if one occurred
return response.json()
Expand All @@ -120,13 +119,12 @@ def _get_access_token(service_account_info: dict):
return {"error": "Failed to append to Google Sheet"}



def send_gmail(
sender_email: str,
receiver_email: str,
subject: str,
app_password: str,
values: list
sender_email: str,
receiver_email: str,
subject: str,
app_password: str,
values: list,
) -> bool:
"""
>>> send_gmail(
Expand Down Expand Up @@ -157,7 +155,7 @@ def send_gmail(
Returns
-------
bool
Returns True if the email was sent successfully, otherwise False.
Returns True if the email was sent successfully, otherwise False.
Examples
--------
Expand All @@ -175,10 +173,10 @@ def send_gmail(
# Construct the email body
body = "\n".join(", ".join(str(v) for v in value) for value in values)
message.attach(MIMEText(body, "plain"))

try:
# Send the email
with smtplib.SMTP_SSL('smtp.gmail.com', 465) as server:
with smtplib.SMTP_SSL("smtp.gmail.com", 465) as server:
server.login(sender_email, app_password)
server.sendmail(sender_email, receiver_email, message.as_string())
logging.info("Email sent successfully!")
Expand Down
11 changes: 9 additions & 2 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,15 @@
long_description_content_type="text/markdown",
long_description=long_description,
packages=find_packages(),
install_requires=["Pillow", "pandas", "matplotlib", "openpyxl", "PyJWT", "cryptography",
"requests"],
install_requires=[
"Pillow",
"pandas",
"matplotlib",
"openpyxl",
"PyJWT",
"cryptography",
"requests",
],
keywords=["python", "MecSimCalc", "Calculator", "Simple"],
classifiers=[
"Development Status :: 5 - Production/Stable",
Expand Down

0 comments on commit 38ec8d8

Please sign in to comment.