python - 在 Nose 测试类中定义 Nose 测试方法

标签 python python-3.x nose

定义一个 Nose 测试方法test_circlearea_with_min_radius,它创建一个半径为0的圆c2并检查其计算面积是否与值0匹配

我已经编写了下面提到的代码,但仍然没有得到所需的输出:

import math
from circle import Circle
from nose.tools import assert_raises
from nose.tools import assert_equal


class Circle:

    def __init__(self,radius):

        if not isinstance(radius,(int,float)):
            raise TypeError("radius must be a number")

        if not 1000>=radius>=0:
            raise ValueError("radius must be between 0 and 1000 inclusive")

        self.radius = radius


    def area(self):
        return round(math.pi*self.radius**2,2)

    def circumference(self):
        return round(2*math.pi*self.radius,2)


class TestCircleArea:

    def test_circlearea_with_random_numeric_radius(self):
        c1=Circle(2.5)
        assert_equal(c1.area(),19.63)

    def test_circlearea_with_min_radius(self):
        c2=Circle(0)
        assert_equal(c2.area(),0)

最佳答案

要运行测试,您必须使用nose执行该文件;你不能像普通的 python 脚本一样执行它。例如,如果您帖子中的代码位于名为 test.py 的文件中,您可以运行以下命令:

nosetests test.py

如果运行命令python test.py,您将不会得到任何输出。根据您命名文件的方式等,您应该能够不带参数运行nosetests,并且nose的测试发现应该足够智能,可以找到您的测试类并运行测试。另外,请确保在运行测试之前导入/定义 Circle 类,否则您会收到错误消息。

如果您尝试自己编写 Circle 类,并且希望使用 TDD 以有趣的方式构建它,您可以从以下内容开始:

class Circle:
    def __init__(*args):
        pass

    def area(self):
        pass

from nose.tools import assert_equals
class TestCircleArea:

    def test_circlearea_with_random_numeric_radius(self):
        c1=Circle(0)
        assert_equals(c1.area(),0)

这会给你一个失败的测试,你可以从那里开始构建 area() 方法的功能,going from red (failing test) to green (passing test) .

关于python - 在 Nose 测试类中定义 Nose 测试方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55558578/

相关文章:

python - 在超时中包装 asyncio.gather

Python 连续运行单元测试或每个测试多次

python - 艰难地学习 Python 练习 46 : Installing Python packages (pip, nose 等)在 Windows 上

python - 如何将命令行参数从脚本传递到 python 文件

Python Selenium - 在文本框中输入值

python - 尝试为 AI 过滤字典

python - 当我输入 no 时,它无法正确执行

python - 禁用 Nose 运行设置()

java - 相当于python中的objectmapper

python - 将 “libpython2.7.a”版本从2.7.5更改为2.7.6以安装opencv 2.4.9