Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit test for the 'none' type in Python

Tags:

How would I go about testing for a function that does not return anything?

For example, say I have this function:

def is_in(char):     my_list = []     my_list.append(char) 

and then if I were to test it:

class TestIsIn(unittest.TestCase):      def test_one(self):     ''' Test if one character was added to the list'''     self.assertEqual(self.is_in('a'), # And this is where I am lost) 

I don't know what to assert the function is equal to, since there isn't any return value that I could compare it to.

Would assertIn work?

like image 691
peppy Avatar asked Feb 14 '13 05:02

peppy


People also ask

How do you check if a variable is None in Python?

Use the is operator to check if a variable is None in Python, e.g. if my_var is None: . The is operator returns True if the values on the left-hand and right-hand sides point to the same object and should be used when checking for singletons like None .

What is the type of None in Python?

The None keyword is used to define a null value, or no value at all. None is not the same as 0, False, or an empty string. None is a data type of its own (NoneType) and only None can be None.

What does with assertRaises do in Python?

assertRaises() – It allows an exception to be encapsulated, meaning that the test can throw an exception without exiting the execution, as is normally the case for unhandled exceptions. The test passes if exception is raised, gives an error if another exception is raised, or fails if no exception is raised.


2 Answers

All Python functions return something. If you don't specify a return value, None is returned. So if your goal really is to make sure that something doesn't return a value, you can just say

self.assertIsNone(self.is_in('a')) 

(However, this can't distinguish between a function without an explicit return value and one which does return None.)

like image 129
Kevin Christopher Henry Avatar answered Sep 22 '22 12:09

Kevin Christopher Henry


The point of a unit test is to test something that the function does. If it's not returning a value, then what is it actually doing? In this case, it doesn't appear to be doing anything, since my_list is a local variable, but if your function actually looked something like this:

def is_in(char, my_list):     my_list.append(char) 

Then you would want to test if char is actually appended to the list. Your test would be:

def test_one(self):     my_list = []     is_in('a', my_list)     self.assertEqual(my_list, ['a']) 

Since the function does not return a value, there isn't any point testing for it (unless you need make sure that it doesn't return a value).

like image 40
aquavitae Avatar answered Sep 23 '22 12:09

aquavitae