Skip to content

Commit

Permalink
Merge PR #207 from WayneLambert/sourcery/develop
Browse files Browse the repository at this point in the history
Runs Ruff Formatting Over Project (Sourcery refactored)
  • Loading branch information
WayneLambert authored Dec 11, 2023
2 parents 444014c + 82e231f commit d5b89ca
Show file tree
Hide file tree
Showing 12 changed files with 40 additions and 58 deletions.
17 changes: 8 additions & 9 deletions apps/blog/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,17 +30,16 @@ def clean_title(self):
uncapitalized_exceptions = ("with", "them", "your")
updated_words = []
for word in words:
if not word.isupper():
if (
if word.isupper():
updated_words.append(word)
elif (
len(word.strip()) >= 4 or word in capitalized_exceptions
) and word not in uncapitalized_exceptions:
updated_words.append(word.title())
elif (
len(word.strip()) < 4 or word in uncapitalized_exceptions
) and word not in capitalized_exceptions:
updated_words.append(word.lower())
else:
updated_words.append(word)
updated_words.append(word.title())
elif (
len(word.strip()) < 4 or word in uncapitalized_exceptions
) and word not in capitalized_exceptions:
updated_words.append(word.lower())
new_title = " ".join(updated_words).replace("&", "and").strip()
if new_title[0].islower():
new_title = f"{new_title[0].capitalize()}{new_title[1:]}"
Expand Down
3 changes: 1 addition & 2 deletions apps/blog/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -137,8 +137,7 @@ class SearchResultsView(PostView):
def get_queryset(self):
start_time = perf_counter()
initial_query = format_html(self.request.GET.get("q"))
cleaned_query = search.cleanup_string(initial_query)
if cleaned_query:
if cleaned_query := search.cleanup_string(initial_query):
search_vector = SearchVector("title", weight="A") + SearchVector("content", weight="B")
search_query = SearchQuery(cleaned_query)
search_rank = SearchRank(search_vector, search_query)
Expand Down
12 changes: 3 additions & 9 deletions apps/countdown_letters/logic.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,9 +38,7 @@ def get_weighted_vowels() -> List:
"O": 13,
"U": 5,
}
s: str = ""
for key, value in vowel_freq.items():
s += key * value
s: str = "".join(key * value for key, value in vowel_freq.items())
return list(s)

@staticmethod
Expand Down Expand Up @@ -73,9 +71,7 @@ def get_weighted_consonants() -> List:
"Y": 1,
"Z": 1,
}
s: str = ""
for key, value in consonant_freq.items():
s += key * value
s: str = "".join(key * value for key, value in consonant_freq.items())
return list(s)


Expand Down Expand Up @@ -180,9 +176,7 @@ def lookup_definition_data(word: str) -> Dict:
definition = d["definitions"][0].capitalize()
word_class = json["results"][0]["lexicalEntries"][idx]["lexicalCategory"]["text"]
except KeyError:
definition = (
f"The definition for '{word}' cannot be found " + "in the Oxford Dictionaries API."
)
definition = f"The definition for '{word}' cannot be found in the Oxford Dictionaries API."
word_class = "N/A"

return {
Expand Down
6 changes: 3 additions & 3 deletions apps/countdown_letters/tests/test_validations.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,10 @@
def test_is_in_oxford_api(test_word: str):
"""Asserts that given a valid word, `True` is returned else `False`"""
in_api = validations.is_in_oxford_api(test_word)
if test_word == "random":
assert in_api
if test_word == "radnom": # Misspelt on purpose
if test_word == "radnom":
assert not in_api
elif test_word == "random":
assert in_api


def test_is_eligible_answer(given_answers_list, letters: str = "SVEODRETR"):
Expand Down
31 changes: 15 additions & 16 deletions apps/countdown_numbers/logic.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,12 +105,12 @@ def get_best_solution(game_nums: List, target: int) -> str:
"""Calculates a solution closest to the game's target number"""
game_calcs = get_game_calcs(game_nums, stop_on=target)

if int(target) in game_calcs:
return game_calcs[int(target)][0]
if target in game_calcs:
return game_calcs[target][0]
for num in range(1, 11):
if int(target) + num in game_calcs:
return game_calcs[int(target) + num][0]
return game_calcs[int(target) - num][0]
if target + num in game_calcs:
return game_calcs[target + num][0]
return game_calcs[target - num][0]
return "No solution could be found"


Expand All @@ -120,25 +120,24 @@ def get_score_awarded(target_number: int, num_achieved: int) -> int:
calculation's proximity to the target number
"""
if num_achieved == target_number:
points_awarded = 10
return 10
elif target_number - 5 <= num_achieved <= target_number + 5:
points_awarded = 7
return 7
elif target_number - 10 <= num_achieved <= target_number + 10:
points_awarded = 5
return 5
else:
points_awarded = 0
return points_awarded
return 0


def get_game_result(target: int, answers: Dict) -> str:
"""Returns the game's result as a string for template rendering"""
comp_ans_variance = abs(answers["comp_num_achieved"] - target)
player_ans_variance = abs(answers["player_num_achieved"] - target)
if comp_ans_variance == player_ans_variance:
result = "Draw"
return "Draw"
else:
if player_ans_variance < comp_ans_variance:
result = "Player wins"
else:
result = "Rachel wins"
return result
return (
"Player wins"
if player_ans_variance < comp_ans_variance
else "Rachel wins"
)
4 changes: 2 additions & 2 deletions apps/countdown_numbers/tests/test_template_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ def test_add_spacing():
def test_change_symbols():
test_value = "(100 * 9) / (4 + 5) - 1"
outcome = template_helpers.change_symbols(test_value)
expected_outcome = "(100 " + chr(215) + " 9) " + chr(247) + " (4 + 5) - 1"
expected_outcome = f"(100 {chr(215)} 9) {chr(247)} (4 + 5) - 1"
assert (
outcome == expected_outcome
), "Should be reformatted with mathematical multiplication and division symbols"
Expand All @@ -27,7 +27,7 @@ def test_humanise_calculation():
removed_brackets = template_helpers.remove_brackets(test_value)
spacing_added = template_helpers.add_spacing(removed_brackets)
overall_outcome = template_helpers.change_symbols(spacing_added)
expected_outcome = "(100 " + chr(215) + " 9) " + chr(247) + " (4 + 5) - 1"
expected_outcome = f"(100 {chr(215)} 9) {chr(247)} (4 + 5) - 1"
assert overall_outcome == expected_outcome, """ Should have brackets removed, spacing added, and be
reformatted with humanised mathematical multiplication and
division symbols"""
2 changes: 1 addition & 1 deletion apps/countdown_numbers/tests/test_views.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ def test_get_game_screen(client):
def test_post_game_screen(client):
"""Asserts a site visitor can POST from the `game` screen"""
base_path = reverse("countdown_numbers:game")
full_path = base_path + "?target_number=869&numbers_chosen=%5B100%2C+5%1C+8%2C+1%3C+5%4C+2%5D"
full_path = f"{base_path}?target_number=869&numbers_chosen=%5B100%2C+5%1C+8%2C+1%3C+5%4C+2%5D"
data = {
"target_number": "869",
"numbers_chosen": "[100, 1, 2, 3, 4, 5]",
Expand Down
3 changes: 1 addition & 2 deletions apps/pages/tests/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,5 @@

def app_names():
long_form_apps, short_form_apps = base.PROJECT_APPS, []
for app in long_form_apps:
short_form_apps.append(app.split(".")[1])
short_form_apps.extend(app.split(".")[1] for app in long_form_apps)
return short_form_apps
2 changes: 1 addition & 1 deletion apps/roulette/logic.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,4 +82,4 @@ def get_picture_url(destination: str) -> str:
def read_log_file() -> List:
"""Reads log file to a list for later rendering to results page"""
with open(log_file, "r") as file:
return [line for line in file.readlines()]
return list(file.readlines())
5 changes: 1 addition & 4 deletions apps/scraping/referendum.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,7 @@ def get_area_results(results: dict) -> List[Tuple[Any]]:
results["area_votes"],
results["turnout"],
)
results = []
for area in area_results:
results.append(area)

results = list(area_results)
return results


Expand Down
8 changes: 2 additions & 6 deletions apps/users/tests/test_forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -140,12 +140,8 @@ class TestProfileUpdateForm:
"validity": True,
}

def good_data_with_image(test_image):
return {
"profile_picture": test_image,
"author_view": 0,
"validity": True,
}
def good_data_with_image(self):
return {"profile_picture": self, "author_view": 0, "validity": True}

def test_form_tests_for_all_fields(self):
"""Asserts all fields that need to be tested are present"""
Expand Down
5 changes: 2 additions & 3 deletions apps/users/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -155,8 +155,7 @@ def login_user(self, user):

def handle_email_auth_user(self, user):
"""Handles the actions for processing an email authenticated user"""
user_passes_auth = self.authenticate_user(user=user)
if user_passes_auth:
if user_passes_auth := self.authenticate_user(user=user):
self.login_user(user=user)
token = self.retrieve_token_from_db(user)
self.email_two_factor_token(user, token)
Expand Down Expand Up @@ -285,7 +284,7 @@ def get_context_data(self, **kwargs) -> Dict[str, Any]:
email = self.request.user.email.strip()
domain = email.split("@")[-1]
context["user_first_name"] = self.request.user.get_short_name()
context["redacted_user_email"] = f"{email[0:2]}**********@{domain}"
context["redacted_user_email"] = f"{email[:2]}**********@{domain}"
return context

def get_email_token(self) -> EmailToken:
Expand Down

0 comments on commit d5b89ca

Please sign in to comment.