How do I write tests correctly using unittest?

独自空忆成欢 提交于 2020-01-11 14:04:53

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/15847175/how-do-i-write-tests-correctly-using-unittest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!