Unit test in python: Conceptual question regarding dynamic typing / type hinting

29 Views Asked by At

Python is using dynamic typing. This makes me wonder, what I should actual test in unit test. Let's take a simple example:

import numpy as np

def foo(n, m):
    bar = np.multiply(n, m)
    return bar

I only want to allow integers in my calculation. But the function could also run with e.g. float numbers.

Following question/scenarios:

  1. Which function arguments should I unittest? The amount of types is literally infinitive, should I test for all of those? E.g.
  • Only test the intended result by usingint as arguments?
  • Also test the fails on using forbidden types e.g float as arguments
  • If I also test the failure on forbidden types, which types should I actually test? Should I also check for e.g. str (which would let the numpy.multiply function fail)? Shall I just check for exemplary types that demonstrate that a type error is raised?
  • If I check all of those types, should I then also explicitly allow only int?

e.g.

import numpy as np

def foo(n, m):
    if(not isinstance(n, int)):
        raise TypeError('Only int allowed')

    if(not isinstance(m, int)):
        raise TypeError('Only int allowed')

    bar = np.multiply(n, m)
    return bar

I can implement this in all functions I have, but it would bloat the code and spoil the concept of dynamic typing. Should I only implement it, where it is crucial?

  1. If I only implement the type-check for functions, where it is crucial, what unit tests should I actually perform? Again, on all possible allowed types? In this case, if I also want to accept float, shall I also test it? But there might be data types I even don't know and still be working with this function, so how to I properly select the types to test?

  2. What, if I use type hinting? Do the same checks inside the function and implement the same tests?

E.g.

import numpy as np

def foo(n: int, m: int) -> int:
    bar = np.multiply(n, m)
    return bar
  • Can I restrict myself on testing for integers since type hinting "requires" no integers? Shall I still test if its failing for other data types (which one?)
0

There are 0 best solutions below