简体   繁体   中英

How to do unit test to check input is not null in Python

This is my first time trying to write a unit test in Python. I have a simple function like this:

def sum_num(a, b):
  return a+b

I want to do unit test to check that the input (a, b) is not null and output is not null.

import unittest

class SumTest(unittest.TestCase):
    def test_sum_output_not_null(self):
        self.assertTrue(add_num(3,4))

    def test_sum_input_not_null(self):
        # How to check input (a and b) is not None ?
        self.assertIsNotNone(a)
...

suite = unittest.TestLoader().loadTestsFromTestCase(SumTest)
runner = unittest.TextTestRunner(verbosity=2)
runner.run(suite)

I am getting errors in the unit test run..

test_sum_input_not_null (__main__.SumTest) ... ERROR
test_sum_output_not_null (__main__.SumTest) ... ok

======================================================================
ERROR: test_sum_input_not_null (__main__.SumTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "<command-1933936>", line 7, in test_sum_input_not_null
    self.assertIsNotNone(a)
NameError: name 'a' is not defined

----------------------------------------------------------------------
Ran 2 tests in 0.000s

FAILED (errors=1)
Out[4]: <unittest.runner.TextTestResult run=2 errors=1 failures=0>

How do I check a and b are not null? Also probably want to check both a and b are integers as well. I read somewhere about setup(). Do I need to do that to test inputs for a function?

I want to do unit test to check that the input (a, b) is not null and output is not null.

Either you don't understand yet the purpose of testing or you're asking some TDD related question.

You don't test quoted, you test does your function deal well when such a condition occurs.

So, you should create test function(s) and make a call inside it like:

def test_when_a_is_null(self):
    self.assertIsNotNone(add_num(None, 5))

and the similar when b is None and when both are None.

But, that means your function should deal with the conditions:

def add_num(a, b):
    if a is not None and b is not None:
        return a + b
    elif a is not None:
        return a
    elif b is not None:
        return b
    return 0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM