Home > Net >  Testing for None on a non Optional input parameter
Testing for None on a non Optional input parameter

Time:10-15

Let's say I have a python module with the following function:

def is_plontaria(plon: str) -> bool:
    if plon is None:
        raise RuntimeError("None found")

    return plon.find("plontaria") != -1

For that function, I have the unit test that follows:

def test_is_plontaria_null(self):
    with self.assertRaises(RuntimeError) as cmgr:
        is_plontaria(None)
    self.assertEqual(str(cmgr.exception), "None found")

Given the type hints in the function, the input parameter should always be a defined string. But type hints are... hints. Nothing prevents the user from passing whatever it wants, and None in particular is a quite common option when previous operations fail to return the expected results and those results are not checked.

So I decided to test for None in the unit tests and to check the input is not None in the function.

The issue is: the type checker (pylance) warns me that I should not use None in that call:

Argument of type "None" cannot be assigned to parameter "plon" of type "str" in function "is_plontaria"
  Type "None" cannot be assigned to type "str"

Well, I already know that, and that is the purpose of that test.

Which is the best way to get rid of that error? Telling pylance to ignore this kind of error in every test/file? Or assuming that the argument passed will be always of the proper type and remove that test and the None check in the function?

CodePudding user response:

You can disable type checking for on a specific line with a comment.

def test_is_plontaria_null(self):
    with self.assertRaises(RuntimeError) as cmgr:
        is_plontaria(None) # type: ignore
    self.assertEqual(str(cmgr.exception), "None found")
  • Related