I have read about when to use assert and when to use an exception.
Assertions are intended to be used as a means of detecting programming errors, aka bugs. Some say assert is for debugging purposes only and its trigger condition should not happen.
By contrast, an exception can indicate other kinds of error or "exceptional" condition: invalid user input, missing files, heap full, etc. From my understanding, exceptions can do everything asserts can do except they cannot be disabled.
If all asserts were replaced by exceptions, it would be functionally the same. So, is the ability to disable asserts the only reason why they should be used or are there other reasons?
Thanks.
Asserts are used by test cases to make sure that what you built doesn't, in the future, render something unexpected. You can assert to make sure exceptions are thrown upon false input, for instance.
Many times in programming changing one thing means you have to change other pieces of your code. Assertations make sure that what you change doesn't break code you've written in the past.
Exceptions are good. They are expected and handled via exceptions. You have exceptions for incorrect login and password, for instance.
You can assert that upon an incorrect login or password, the expected exception is raised.
An assert contains three main things. What you're testing (function name for instance, i.e. sign_in
), what goes in (function parameters i.e. {'email': '[email protected]', 'password': hashlib.md5('my_password')}
), and what comes out (assertTrue('user_name' in response, 'Expecting user_name to be in response!')
).
Exceptions are normal, logical alternatives in code. Asserts are tests to make sure logical paths are followed when they should be.
According to the python unittest framework, you can assert that exceptions are thrown:
import random import unittest
class TestSequenceFunctions(unittest.TestCase):
def setUp(self):
self.seq = range(10)
def test_shuffle(self):
# make sure the shuffled sequence does not lose any elements
random.shuffle(self.seq)
self.seq.sort()
self.assertEqual(self.seq, range(10))
# should raise an exception for an immutable sequence
self.assertRaises(TypeError, random.shuffle, (1,2,3))
def test_choice(self):
element = random.choice(self.seq)
self.assertTrue(element in self.seq)
def test_sample(self):
with self.assertRaises(ValueError):
random.sample(self.seq, 20)
for element in random.sample(self.seq, 5):
self.assertTrue(element in self.seq)
if __name__ == '__main__':
unittest.main()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With