Skip to content

[Practice Exercises]: Add Better Error Handling Instructions & Tests for Error Raising Messages (# 1 of 8) #2685

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 11 commits into from
Oct 21, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions exercises/practice/affine-cipher/.docs/instructions.append.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# Instructions append

## Exception messages

Sometimes it is necessary to [raise an exception](https://docs.python.org/3/tutorial/errors.html#raising-exceptions). When you do this, you should always include a **meaningful error message** to indicate what the source of the error is. This makes your code more readable and helps significantly with debugging. For situations where you know that the error source will be a certain type, you can choose to raise one of the [built in error types](https://docs.python.org/3/library/exceptions.html#base-classes), but should still include a meaningful message.

This particular exercise requires that you use the [raise statement](https://docs.python.org/3/reference/simple_stmts.html#the-raise-statement) to "throw" a `ValueError`. The tests will only pass if you both `raise` the `exception` and include a message with it.

To raise a `ValueError` with a message, write the message as an argument to the `exception` type:

```python
raise ValueError("a and m must be coprime.")
```
2 changes: 1 addition & 1 deletion exercises/practice/affine-cipher/.meta/example.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ def modInverse(a, ALPHSZ):
def translate(text, a, b, mode):
inv = modInverse(a, ALPHSZ)
if inv == 1:
raise ValueError("a and alphabet size must be coprime.")
raise ValueError("a and m must be coprime.")

chars = []
for c in text:
Expand Down
7 changes: 4 additions & 3 deletions exercises/practice/affine-cipher/.meta/template.j2
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,13 @@ def test_{{ case["description"] | to_snake }}(self):
{% set a = input["key"]["a"] -%}
{% set b = input["key"]["b"] -%}
{% set expected = case["expected"] -%}
{% set exp_error = expected["error"] -%}
{% set function = case["property"] -%}
{% if case is error_case -%}
with self.assertRaisesWithMessage(ValueError):
with self.assertRaises(ValueError) as err:
{{ function }}("{{ phrase }}", {{ a }}, {{ b }})
self.assertEqual(type(err.exception), ValueError)
self.assertEqual(err.exception.args[0], "{{ exp_error }}")
{% else -%}
self.assertEqual({{ function }}("{{ phrase }}", {{ a }}, {{ b }}), "{{ expected }}")
{% endif -%}
Expand All @@ -28,5 +31,3 @@ class {{ exercise | camel_case }}Test(unittest.TestCase):
{% for supercase in cases -%}
{{ test_supercase(supercase) }}
{% endfor %}

{{ macros.footer(True) }}
16 changes: 6 additions & 10 deletions exercises/practice/affine-cipher/affine_cipher_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,10 @@ def test_encode_all_the_letters(self):
)

def test_encode_with_a_not_coprime_to_m(self):
with self.assertRaisesWithMessage(ValueError):
with self.assertRaises(ValueError) as err:
encode("This is a test.", 6, 17)
self.assertEqual(type(err.exception), ValueError)
self.assertEqual(err.exception.args[0], "a and m must be coprime.")

def test_decode_exercism(self):
self.assertEqual(decode("tytgn fjr", 3, 7), "exercism")
Expand Down Expand Up @@ -72,13 +74,7 @@ def test_decode_with_too_many_spaces(self):
)

def test_decode_with_a_not_coprime_to_m(self):
with self.assertRaisesWithMessage(ValueError):
with self.assertRaises(ValueError) as err:
decode("Test", 13, 5)

# Utility functions
def assertRaisesWithMessage(self, exception):
return self.assertRaisesRegex(exception, r".+")


if __name__ == "__main__":
unittest.main()
self.assertEqual(type(err.exception), ValueError)
self.assertEqual(err.exception.args[0], "a and m must be coprime.")
20 changes: 20 additions & 0 deletions exercises/practice/all-your-base/.docs/instructions.append.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# Instructions append

## Exception messages

Sometimes it is necessary to [raise an exception](https://docs.python.org/3/tutorial/errors.html#raising-exceptions). When you do this, you should always include a **meaningful error message** to indicate what the source of the error is. This makes your code more readable and helps significantly with debugging. For situations where you know that the error source will be a certain type, you can choose to raise one of the [built in error types](https://docs.python.org/3/library/exceptions.html#base-classes), but should still include a meaningful message.

This particular exercise requires that you use the [raise statement](https://docs.python.org/3/reference/simple_stmts.html#the-raise-statement) to "throw" a `ValueError` for different input and output bases. The tests will only pass if you both `raise` the `exception` and include a meaningful message with it.

To raise a `ValueError` with a message, write the message as an argument to the `exception` type:

```python
# for input.
raise ValueError("input base must be >= 2")

# another example for input.
raise ValueError("all digits must satisfy 0 <= d < input base")

# or, for output.
raise ValueError("output base must be >= 2")
```
6 changes: 3 additions & 3 deletions exercises/practice/all-your-base/.meta/example.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,12 @@ def to_digits(number, base_to):

def rebase(from_base, digits, to_base):
if from_base < 2:
raise ValueError("Invalid input base.")
raise ValueError("input base must be >= 2")

if to_base < 2:
raise ValueError("Invalid output base.")
raise ValueError("output base must be >= 2")

if any(True for d in digits if d < 0 or d >= from_base):
raise ValueError("Invalid input digit.")
raise ValueError("all digits must satisfy 0 <= d < input base")

return to_digits(from_digits(digits, from_base), to_base)
5 changes: 4 additions & 1 deletion exercises/practice/all-your-base/.meta/template.j2
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,13 @@

{%- macro test_case(case) -%}
{%- set expected = case["expected"] -%}
{%- set exp_error = expected["error"] -%}
def test_{{ case["description"] | to_snake }}(self):
{%- if case is error_case %}
with self.assertRaisesWithMessage(ValueError):
with self.assertRaises(ValueError) as err:
{{ func_call(case) }}
self.assertEqual(type(err.exception), ValueError)
self.assertEqual(err.exception.args[0], "{{ exp_error }}")
{%- else %}
self.assertEqual({{ func_call(case) }}, {{ expected }})
{%- endif %}
Expand Down
40 changes: 31 additions & 9 deletions exercises/practice/all-your-base/all_your_base_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,40 +45,62 @@ def test_leading_zeros(self):
self.assertEqual(rebase(7, [0, 6, 0], 10), [4, 2])

def test_input_base_is_one(self):
with self.assertRaisesWithMessage(ValueError):
with self.assertRaises(ValueError) as err:
rebase(1, [0], 10)
self.assertEqual(type(err.exception), ValueError)
self.assertEqual(err.exception.args[0], "input base must be >= 2")

def test_input_base_is_zero(self):
with self.assertRaisesWithMessage(ValueError):
with self.assertRaises(ValueError) as err:
rebase(0, [], 10)
self.assertEqual(type(err.exception), ValueError)
self.assertEqual(err.exception.args[0], "input base must be >= 2")

def test_input_base_is_negative(self):
with self.assertRaisesWithMessage(ValueError):
with self.assertRaises(ValueError) as err:
rebase(-2, [1], 10)
self.assertEqual(type(err.exception), ValueError)
self.assertEqual(err.exception.args[0], "input base must be >= 2")

def test_negative_digit(self):
with self.assertRaisesWithMessage(ValueError):
with self.assertRaises(ValueError) as err:
rebase(2, [1, -1, 1, 0, 1, 0], 10)
self.assertEqual(type(err.exception), ValueError)
self.assertEqual(
err.exception.args[0], "all digits must satisfy 0 <= d < input base"
)

def test_invalid_positive_digit(self):
with self.assertRaisesWithMessage(ValueError):
with self.assertRaises(ValueError) as err:
rebase(2, [1, 2, 1, 0, 1, 0], 10)
self.assertEqual(type(err.exception), ValueError)
self.assertEqual(
err.exception.args[0], "all digits must satisfy 0 <= d < input base"
)

def test_output_base_is_one(self):
with self.assertRaisesWithMessage(ValueError):
with self.assertRaises(ValueError) as err:
rebase(2, [1, 0, 1, 0, 1, 0], 1)
self.assertEqual(type(err.exception), ValueError)
self.assertEqual(err.exception.args[0], "output base must be >= 2")

def test_output_base_is_zero(self):
with self.assertRaisesWithMessage(ValueError):
with self.assertRaises(ValueError) as err:
rebase(10, [7], 0)
self.assertEqual(type(err.exception), ValueError)
self.assertEqual(err.exception.args[0], "output base must be >= 2")

def test_output_base_is_negative(self):
with self.assertRaisesWithMessage(ValueError):
with self.assertRaises(ValueError) as err:
rebase(2, [1], -7)
self.assertEqual(type(err.exception), ValueError)
self.assertEqual(err.exception.args[0], "output base must be >= 2")

def test_both_bases_are_negative(self):
with self.assertRaisesWithMessage(ValueError):
with self.assertRaises(ValueError) as err:
rebase(-2, [1], -7)
self.assertEqual(type(err.exception), ValueError)
self.assertEqual(err.exception.args[0], "input base must be >= 2")

# Utility functions
def assertRaisesWithMessage(self, exception):
Expand Down
24 changes: 24 additions & 0 deletions exercises/practice/bank-account/.docs/instructions.append.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# Instructions append

## Exception messages

Sometimes it is necessary to [raise an exception](https://docs.python.org/3/tutorial/errors.html#raising-exceptions). When you do this, you should always include a **meaningful error message** to indicate what the source of the error is. This makes your code more readable and helps significantly with debugging. For situations where you know that the error source will be a certain type, you can choose to raise one of the [built in error types](https://docs.python.org/3/library/exceptions.html#base-classes), but should still include a meaningful message.

This particular exercise requires that you use the [raise statement](https://docs.python.org/3/reference/simple_stmts.html#the-raise-statement) to "throw" a `ValueError` for when an account is or is not open, or the withdrawal/deposit amounts are incorrect. The tests will only pass if you both `raise` the `exception` and include a message with it.

To raise a `ValueError` with a message, write the message as an argument to the `exception` type:


```python
# account is not open
raise ValueError('account not open')

# account is already open
raise ValueError('account already open')

# incorrect withdrawal/deposit amount
raise ValueError('amount must be greater than 0')

# withdrawal is too big
raise ValueError('amount must be less than balance')
```
38 changes: 25 additions & 13 deletions exercises/practice/bank-account/bank_account_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,35 +48,46 @@ def test_checking_balance_of_closed_account_throws_error(self):
account.open()
account.close()

with self.assertRaisesWithMessage(ValueError):
with self.assertRaises(ValueError) as err:
account.get_balance()
self.assertEqual(type(err.exception), ValueError)
self.assertEqual(err.exception.args[0], "account not open")

def test_deposit_into_closed_account(self):
account = BankAccount()
account.open()
account.close()

with self.assertRaisesWithMessage(ValueError):
with self.assertRaises(ValueError) as err:
account.deposit(50)
self.assertEqual(type(err.exception), ValueError)
self.assertEqual(err.exception.args[0], "account not open")


def test_withdraw_from_closed_account(self):
account = BankAccount()
account.open()
account.close()

with self.assertRaisesWithMessage(ValueError):
with self.assertRaises(ValueError) as err:
account.withdraw(50)
self.assertEqual(type(err.exception), ValueError)
self.assertEqual(err.exception.args[0], "account not open")

def test_close_already_closed_account(self):
account = BankAccount()
with self.assertRaisesWithMessage(ValueError):
with self.assertRaises(ValueError) as err:
account.close()
self.assertEqual(type(err.exception), ValueError)
self.assertEqual(err.exception.args[0], "account not open")

def test_open_already_opened_account(self):
account = BankAccount()
account.open()
with self.assertRaisesWithMessage(ValueError):
with self.assertRaises(ValueError) as err:
account.open()
self.assertEqual(type(err.exception), ValueError)
self.assertEqual(err.exception.args[0], "account already open")

def test_reopened_account_does_not_retain_balance(self):
account = BankAccount()
Expand All @@ -91,23 +102,29 @@ def test_cannot_withdraw_more_than_deposited(self):
account.open()
account.deposit(25)

with self.assertRaises(ValueError):
with self.assertRaises(ValueError) as err:
account.withdraw(50)
self.assertEqual(type(err.exception), ValueError)
self.assertEqual(err.exception.args[0], "amount must be less than balance")

def test_cannot_withdraw_negative(self):
account = BankAccount()
account.open()
account.deposit(100)

with self.assertRaisesWithMessage(ValueError):
with self.assertRaises(ValueError) as err:
account.withdraw(-50)
self.assertEqual(type(err.exception), ValueError)
self.assertEqual(err.exception.args[0], "amount must be greater than 0")

def test_cannot_deposit_negative(self):
account = BankAccount()
account.open()

with self.assertRaisesWithMessage(ValueError):
with self.assertRaises(ValueError) as err:
account.deposit(-50)
self.assertEqual(type(err.exception), ValueError)
self.assertEqual(err.exception.args[0], "amount must be greater than 0")

def test_can_handle_concurrent_transactions(self):
account = BankAccount()
Expand Down Expand Up @@ -138,10 +155,5 @@ def transact():
for thread in threads:
thread.join()

# Utility functions
def assertRaisesWithMessage(self, exception):
return self.assertRaisesRegex(exception, r".+")


if __name__ == '__main__':
unittest.main()
14 changes: 14 additions & 0 deletions exercises/practice/binary-search/.docs/instructions.append.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
# Instructions append

## Exception messages

Sometimes it is necessary to [raise an exception](https://docs.python.org/3/tutorial/errors.html#raising-exceptions). When you do this, you should always include a **meaningful error message** to indicate what the source of the error is. This makes your code more readable and helps significantly with debugging. For situations where you know that the error source will be a certain type, you can choose to raise one of the [built in error types](https://docs.python.org/3/library/exceptions.html#base-classes), but should still include a meaningful message.

This particular exercise requires that you use the [raise statement](https://docs.python.org/3/reference/simple_stmts.html#the-raise-statement) to "throw" a `ValueError` when the given value is not found within the array. The tests will only pass if you both `raise` the `exception` and include a message with it.

To raise a `ValueError` with a message, write the message as an argument to the `exception` type:

```python
# example when value is not found in the array.
raise ValueError("value not in array")
```
2 changes: 1 addition & 1 deletion exercises/practice/binary-search/.meta/example.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,4 @@ def find(search_list, value):
low = middle + 1
else:
return middle
raise ValueError("Value not found.")
raise ValueError("value not in array")
10 changes: 6 additions & 4 deletions exercises/practice/binary-search/.meta/template.j2
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,14 @@
class {{ exercise | camel_case }}Test(unittest.TestCase):
{% for case in cases -%}
def test_{{ case["description"] | to_snake }}(self):
{% set expected = case["expected"] -%}
{% set exp_error = expected["error"] -%}
{%- if case is error_case %}
with self.assertRaisesWithMessage(ValueError):
with self.assertRaises(ValueError) as err:
{{- test_call(case) }}
self.assertEqual(type(err.exception), ValueError)
self.assertEqual(err.exception.args[0], "{{ exp_error }}")
{%- else %}
self.assertEqual({{- test_call(case) }}, {{ case["expected"] }})
self.assertEqual({{- test_call(case) }}, {{ expected }})
{%- endif %}
{% endfor %}

{{ macros.footer() }}
Loading