简体   繁体   中英

How do I write tests correctly using unittest?

I am trying to figure out how to write unit tests for functions that I have written in Python - here's the code written below:

def num_buses(n):
    import math
    """ (int) -> int

    Precondition: n >= 0

    Return the minimum number of buses required to transport n people.
    Each bus can hold 50 people.

    >>> num_buses(75)
    2
    """
    bus = int()
    if(n>=0):
        bus = int(math.ceil(n/50.0))
    return bus

I am attempting to write test code but they are giving me fail results - here's code I started with:

import a1
import unittest


class TestNumBuses(unittest.TestCase):
    """ Test class for function a1.num_buses. """
    def test_numbuses_1(self):
        actual = num_buses(75)
        expected = 2
        self.assertEqual(actual, expected)

    # Add your test methods for a1.num_buses here.


if __name__ == '__main__':
    unittest.main(exit=False)

When I run the module by pressing F5 - this is what I get -

E
======================================================================
ERROR: test_numbuses_1 (__main__.TestNumBuses)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\1-blog-cacher\TestNumBuses.py", line 8, in test_numbuses_1
    actual = num_buses(75)
NameError: global name 'num_buses' is not defined

----------------------------------------------------------------------
Ran 1 test in 0.050s

FAILED (errors=1)

So my test Failed - although it should pass since the number of passengers are 75 and each bus can hold a maximum of 50 people - anything more than that will result in a rounding up of the figures.

Can anyone see how I can get the test cases to work and where my writing the test code went wrong?

In your unittest file you have to import num_buses .

This fixes your immediate problem, but if you have defined num_buses in a1 then you have to do a1.num_buses otherwise Python will think that num_buses is a global function.

import a1
import unittest
import num_buses

class TestNumBuses(unittest.TestCase):
    """ Test class for function a1.num_buses. """
    def test_numbuses_1(self):
        actual = num_buses(75) #a1.num_buses(75) <-
        expected = 2
        self.assertEqual(actual, expected)

    # Add your test methods for a1.num_buses here.


if __name__ == '__main__':
    unittest.main(exit=False)

Check this out: Cyber-Dojo Test - just press resume and then in test_untitled.py press the TEST button.

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